带模块的 Terraform 计数方法

Sim*_*nSK 1 terraform terraform-provider-aws

我正在使用 terraform 并通过模块配置资源。在某些环境中我想创建一个模块,在其他环境中则不想,最好的方法是什么?尝试使用计数方法:

module "module_name" {
  create                   = var.create_module
  source                   = "../../modules/module" 
}
Run Code Online (Sandbox Code Playgroud)

模块内部当然包含检查是否创建资源的资源:

resource "some resource" "main" {
  count = var.create  == true ? 1 : 0
Run Code Online (Sandbox Code Playgroud)

由于我在模块内使用 count,我在模型中的所有资源(数十个)上收到以下错误:

Because some_resource.main has "count" set, its attributes must
be accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    some_resource.main[count.index]
Run Code Online (Sandbox Code Playgroud)

有没有办法在模块或根内部使用 count,而不重构 [count.index] 的整个代码(谁知道可能会导致许多其他问题)?

小智 7

some_resource.main.some_attribute该错误消息表明您在需要访问时(由于计数)在某处尝试访问some_resource.main[0].some_attribute

但是,如果应根据某些条件创建整个模块,则从count资源中删除并将其添加到模块是一种更简洁的方法:

module "module_name" {
  count                    = var.create_module ? 1 : 0
  source                   = "../../modules/module" 
}
Run Code Online (Sandbox Code Playgroud)