Conditionally skipping a variable assignment in a terraform module

1.4k views Asked by At

I'm currently using the terraform-aws-eks module and wanted to setup a managed node group in an existing cluster. However, I only want this node group to appear in our dev environment (but still want the cluster to remain unchanged). Is there a way to skip a variable assignment conditionally for a module? I tried the below approach but get an error if var.deploy_managed_node_group = false. Terraform version 0.14.11.

module "eks" {
  source = "./modules/eks-17.24.0"

  cluster_enabled_log_types = var.cluster_enabled_log_types
  cluster_name              = local.eks_cluster_name
  cluster_version           = local.eks_version
  iam_path                  = "/eks/"
  manage_aws_auth           = true
  map_users                 = local.eks_users
  map_roles                 = local.eks_roles
  subnets                   = module.eks_vpc.private_subnets

  vpc_id        = module.eks_vpc.vpc_id
  worker_groups = local.worker_groups

  node_groups = var.deploy_managed_node_group ? local.node_groups : null

}
Error: Iteration over null value

node_groups variable from module:

variable "node_groups" {
  description = "Map of map of node groups to create. See `node_groups` module's documentation for more details"
  type        = any
  default     = {}
}
1

There are 1 answers

1
Matthew Schuchard On BEST ANSWER

When using types in Terraform such as set, list, or map, the omitted value should be "empty" instead of null if the value is utilized for iteration instead of an argument. Therefore:

node_groups = var.deploy_managed_node_group ? local.node_groups : {}

would be the ideal ternary here as the falsey value returned by the conditional is an empty map constructor.