跳到主要内容

depends_on 元参数

使用 depends_on 元参数处理 OpenTofu 无法自动推断的隐藏资源或模块依赖关系。仅当资源或模块依赖另一个资源的行为但未在其参数中访问该资源的任何数据时,才需要明确指定依赖关系。

处理和规划后果

depends_on 元参数指示 OpenTofu 在执行声明依赖关系的对象的操作之前,完成对依赖关系对象的所有操作(包括读取操作)。当依赖关系对象是整个模块时,depends_on 会影响 OpenTofu 处理与该模块关联的所有资源和数据源的顺序。有关更多详细信息,请参阅 资源依赖关系数据资源依赖关系

您应将 depends_on 作为最后的手段,因为它会导致 OpenTofu 创建更保守的计划,从而替换比必要更多的资源。例如,OpenTofu 可能会将更多值视为未知(“应用后已知”),因为它不确定上游对象上将发生哪些变化。当您对模块使用 depends_on 时,这种情况尤其可能发生。

我们建议您使用 表达式引用 来暗示依赖关系(如果可能),而不是使用 depends_on。表达式引用让 OpenTofu 了解引用从哪个值派生,并避免在该特定值未更改的情况下规划更改,即使上游对象的其他部分已规划更改。

用法

您可以在 module 块以及所有 resource 块中使用 depends_on 元参数,无论资源类型如何。它需要一个列表,其中包含对同一调用模块中其他资源或子模块的引用。此列表不能包含任意表达式,因为 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
]
}