5

I have been trying to conditionally use a module from the root module, so that for certain environments this module is not created. Many people claim that by setting the count in the module to either 0 or 1 using a conditional does the trick.

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

However, this changes the type of conditionally_used_module: instead of an object (or map) we will have a list (or tuple) containing a single object. Is there another way to achieve this, that does not imply changing the type of the module?

4

2 回答 2

4

要有条件地创建一个模块,您可以使用一个变量,假设它在模块create_modulevariables.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 
}
于 2021-03-08T14:19:35.773 回答
-1

terraform-aws-eks 存储库显示了一个示例,可在文件的“条件创建”块中实现您想要的README

于 2021-03-08T00:51:14.037 回答