Use Boolean Variables for Conditional Resource Creation

Create Terraform bool variables that control whether optional resources are created using the count or for_each meta-argument.

Advanced Patterns

Detailed Explanation

Conditional Resource Creation with Bool Variables

Boolean variables combined with the count meta-argument let you make resources optional — created in some environments but not others.

Variable Definitions

variable "create_vpc" {
  type        = bool
  description = "Whether to create a new VPC (false to use existing)"
  default     = true
}

variable "enable_nat_gateway" {
  type        = bool
  description = "Whether to create NAT gateways for private subnet internet access"
  default     = true
}

variable "enable_flow_logs" {
  type        = bool
  description = "Whether to enable VPC flow logs"
  default     = false
}

variable "enable_dns_hostnames" {
  type        = bool
  description = "Whether to enable DNS hostnames in the VPC"
  default     = true
}

Usage with count

resource "aws_vpc" "main" {
  count = var.create_vpc ? 1 : 0

  cidr_block           = var.vpc_cidr
  enable_dns_hostnames = var.enable_dns_hostnames

  tags = var.tags
}

resource "aws_nat_gateway" "main" {
  count = var.enable_nat_gateway ? length(var.availability_zones) : 0

  subnet_id     = aws_subnet.public[count.index].id
  allocation_id = aws_eip.nat[count.index].id
}

resource "aws_flow_log" "main" {
  count = var.enable_flow_logs ? 1 : 0

  vpc_id          = local.vpc_id
  traffic_type    = "ALL"
  iam_role_arn    = aws_iam_role.flow_log[0].arn
  log_destination = aws_cloudwatch_log_group.flow_log[0].arn
}

Environment-Specific Toggles

# dev.tfvars — minimal infrastructure
create_vpc         = true
enable_nat_gateway = false  # Use VPC endpoints instead to save cost
enable_flow_logs   = false

# prod.tfvars — full infrastructure
create_vpc         = true
enable_nat_gateway = true
enable_flow_logs   = true

The count vs for_each Decision

Pattern Use When
count = var.flag ? 1 : 0 Single resource toggle
for_each = var.flag ? toset(["this"]) : [] When you need stable keys

The for_each approach avoids index-based references ([0]) and is safer when resources might be added or removed from the middle of a list.

Use Case

Flexible infrastructure modules where some resources (NAT gateways, monitoring, backups) should only be created in certain environments to optimize cost.

Try It — Terraform Variable Generator

Open full tool