在Terraform中如何创建模块之间的依赖关系

44次阅读
没有评论

问题描述

有两个模块,分别是模块A和模块B。他希望在模块A中的特定资源完全创建完成之后,才能创建模块B中的特定资源。他尝试通过在模块A中设置输出,然后在模块B中引用这个输出来实现这个目标,但遇到了问题。

解决方案

请注意以下操作可能涉及不同版本的Terraform,确保你使用的是合适的版本。

最佳解决方案

根据你的描述,你的方法是正确的,但在Terraform 0.11中无法使用这种方式。这种方法在Terraform 0.12中引入了”first-class expressions”语法。这种语法允许你直接引用资源而不是插值表达式。以下是在Terraform 0.12中的示例:

在模块A中:

output "alb_arn" {
  value = aws_alb.model-server.arn
}

在模块B中:

module "common" {
  source = "./modules/common"
}

module "other" {
  source                    = "./modules/other"
  target_group_depends_on   = module.common.alb_arn
}

在模块B中的变量文件中:

variable "target_group_depends_on" {
  type    = any # 只有依赖关系重要,值不重要
  default = null
}

在模块B的主配置文件中:

resource "aws_alb_target_group" "modelServer" {
  # ...
  depends_on = [var.target_group_depends_on]
}

Terraform 0.11的解决方案

在Terraform 0.11中,不能直接引用变量作为依赖关系。但是,你可以通过引入一个额外的虚拟资源来解决这个问题。这个虚拟资源只存在于作为依赖关系的目的。以下是解决方案的步骤:

在模块A中:

output "alb_arn" {
  value = "${aws_alb.model-server.arn}"
}

在模块B中:

module "common" {
  source = "./modules/common"
}

module "other" {
  source                    = "./modules/other"
  target_group_depends_on   = "${module.common.alb_arn}"
}

在模块B的变量文件中:

variable "target_group_depends_on" {
  type    = "string" # (因为Terraform 0.11不支持“any”)
  default = ""
}

在模块B的主配置文件中:

resource "null_resource" "target_group_depends_on" {
  triggers = {
    # 对变量的引用会隐式地创建一个依赖关系
    dependency = "${var.target_group_depends_on}"
  }
}

resource "aws_alb_target_group" "modelServer" {
  # ...
  # 将null_resource标记为显式依赖关系,这样它就间接地依赖于所有null_resource依赖的资源
  depends_on = ["null_resource.target_group_depends_on"]
}

请注意,在Terraform 0.11中,depends_on参数只接受字面字符串列表,包含资源地址,而不接受插值表达式。这也是你尝试你的例子时看到的错误消息的具体原因。

正文完