有条件地在 Terraform 中创建单个模块

2024-04-14

我一直在尝试有条件地使用根模块中的模块,以便在某些环境下不会创建该模块。许多人声称通过设置count在模块中使用条件将其设置为 0 或 1 就可以了。

module "conditionally_used_module" {
  source = "./modules/my_module"
  count  = (var.create == true) ? 1 : 0
}

然而,这改变了类型conditionally_used_module:我们将拥有一个包含单个对象的列表(或元组),而不是对象(或映射)。是否有另一种方法可以实现此目的,而不意味着更改模块的类型?


要有条件地创建模块,您可以使用变量,假设它被称为create_module in the variables.tf模块的文件conditionally_used_module.

然后对于里面的每个资源conditionally_used_module您将使用的模块count有条件地创建或不创建该特定资源。

下面的示例应该可以工作并为您提供所需的效果。

# Set a variable to know if the resources inside the module should be created
module "conditionally_used_module" {
  source = "./modules/my_module"
  create_module = var.create
}

# Inside the conditionally_used_module file
# ( ./modules/my_module/main.tf ) most likely 
# for every resource inside use the count to create or not each resource
resource "resource_type" "resource_name" {
 count = var.create_module ? 1 : 0
 ... other resource properties 
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有条件地在 Terraform 中创建单个模块 的相关文章

随机推荐