terraformhclterraform-modules

conditional module creation terraform


I have the following main.tf

module "vpc" {

 source = "registry.terraform.io/terraform-aws-modules/vpc/aws"
  version = "~> 3.14.0"
  name = var.environment
  cidr = var.vpc_cidr
  azs             = var.az
  private_subnets = var.private_subnets
  private_subnet_tags = var.private_subnet_tags
  public_subnets  = var.public_subnets

  enable_dns_hostnames = true
  enable_dns_support = true
  enable_nat_gateway = true
  single_nat_gateway = true
  one_nat_gateway_per_az = false
}

Is there any way to conditionally add this module? Just like when using resource which can achieved by:

count = var.enabled ? 1 : 0 

I am asking this because I do not have access to the underling module files, I can only run the module as shown above.


Solution

  • Beginning in version 0.13 of core Terraform, you can use the for_each meta-argument in the module block for conditional management in the same manner as resource or data:

    module "vpc" {
      source = "registry.terraform.io/terraform-aws-modules/vpc/aws"
      version = "~> 3.14.0"
    
      for_each = var.enabled ? toset(["this"]) : []
    
      name = var.environment
      cidr = var.vpc_cidr
      azs             = var.az
      private_subnets = var.private_subnets
      private_subnet_tags = var.private_subnet_tags
      public_subnets  = var.public_subnets
      enable_dns_hostnames = true
      enable_dns_support = true
      enable_nat_gateway = true
      single_nat_gateway = true
      one_nat_gateway_per_az = false
    }