Terraform:在模块之间共享资源

时间:2021-07-15 13:04:16

标签: terraform terraform-modules

我正在创建一个工作正常的 terraform 模块。但是,当我多次使用它时,它会创建多个完全相同的角色和策略。

我在想是否有办法让模块在我第一次调用它时创建一个角色并继续为后续模块使用相同的角色

1 个答案:

答案 0 :(得分:4)

不,Terraform 不支持此功能。最好的办法是在模块外(或在单独的模块中)创建共享资源,然后将它们作为输入参数传入您正在创建的模块多次。

我喜欢为“共享”资源设置一个模块的方法,因为这样您就可以将整个模块作为输入参数传递给使用这些共享资源的任何模块。

编辑:共享模块的示例代码:

main.tf

module "mod1" {
  source = "./mymodule1"
}

module "mod2" {
  source       = "./mymodule2"
  input_module = module.mod1
}

output "mod2" {
  value = module.mod2
}

mymodule1/main.tf

output "some_field" {
  value = "foo"
}

mymodule2/main.tf

variable "input_module" {}

output "module_that_was_input" {
  value = var.input_module
}

结果:

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

mod2 = {
  "module_that_was_input" = {
    "some_field" = "foo"
  }
}