- OpenTofu言語
- メタ引数
- depends_onメタ引数
depends_on
メタ引数
OpenTofuが自動的に推測できない非表示のリソースまたはモジュールの依存関係を処理するには、depends_on
メタ引数を使用します。リソースまたはモジュールが他のリソースの動作に依存しているが、その引数でそのリソースのデータにアクセスしない場合にのみ、明示的に依存関係を指定する必要があります。
処理と計画の結果
depends_on
メタ引数は、OpenTofuに対して、依存オブジェクトに対するすべての処理(Read処理を含む)を、依存関係を宣言しているオブジェクトに対する処理を実行する前に完了するように指示します。依存オブジェクトがモジュール全体である場合、depends_on
はそのモジュールに関連付けられたすべてのリソースとデータソースをOpenTofuが処理する順番に影響を与えます。詳細は、リソース依存関係とデータリソース依存関係を参照してください。
depends_on
は、OpenTofuにより保守的な計画が作成され、必要以上に多くのリソースが置き換えられる可能性があるため、最終手段として使用する必要があります。たとえば、上流のオブジェクトでどのような変更が発生するかが不確実なため、OpenTofuはより多くの値を「(適用後に判明)」として不明なものとして扱う可能性があります。これは、モジュールにdepends_on
を使用する場合に特に可能性が高くなります。
depends_on
の代わりに、可能な限り式参照を使用して依存関係を暗示することをお勧めします。式参照を使用すると、OpenTofuは参照がどの値に由来するかを理解し、その特定の値が変更されていない場合、上流のオブジェクトの他の部分が計画された変更があっても、変更の計画を回避できます。
使用方法
depends_on
メタ引数は、module
ブロックとすべての resource
ブロックで使用できます(リソースの種類に関係なく)。同じ呼び出し元モジュール内の他のリソースまたは子モジュールへの参照のリストが必要です。depends_on
の値は、OpenTofuがリソースの関係を理解する前、つまり式を安全に評価できるようになる前に知られている必要があるため、このリストには任意の式を含めることはできません。
depends_on
を使用する必要がある理由を説明するコメントを常に含めることをお勧めします。次の例では、depends_on
を使用して、aws_iam_instance_profile.example
に対する「非表示の」依存関係を処理します。
resource "aws_iam_role" "example" {
name = "example"
# assume_role_policy is omitted for brevity in this example. Refer to the
# documentation for aws_iam_role for a complete example.
assume_role_policy = "..."
}
resource "aws_iam_instance_profile" "example" {
# Because this expression refers to the role, OpenTofu can infer
# automatically that the role must be created first.
role = aws_iam_role.example.name
}
resource "aws_iam_role_policy" "example" {
name = "example"
role = aws_iam_role.example.name
policy = jsonencode({
"Statement" = [{
# This policy allows software running on the EC2 instance to
# access the S3 API.
"Action" = "s3:*",
"Effect" = "Allow",
}],
})
}
resource "aws_instance" "example" {
ami = "ami-a1b2c3d4"
instance_type = "t2.micro"
# OpenTofu can infer from this that the instance profile must
# be created before the EC2 instance.
iam_instance_profile = aws_iam_instance_profile.example
# However, if software running in this EC2 instance needs access
# to the S3 API in order to boot properly, there is also a "hidden"
# dependency on the aws_iam_role_policy that OpenTofu cannot
# automatically infer, so it must be declared explicitly:
depends_on = [
aws_iam_role_policy.example
]
}