terraform condition - ghdrako/doc_snipets GitHub Wiki

Ternary operator

output "b1" {
  value = contains(["a","b","c"], "d") ? "is true" : "is false"
}
output "b2" {
  value = keys({a: 1, b: 2, c: 3}) == ["a","b","c"] ? "is true" : "is false"
}
output "b3" {
  value = contains(keys({a: 1, b: 2, c: 3}), "b") ? "is true" : "is false"
}
$ terraform apply -auto-approve
Outputs:

b1 = is false
b2 = is true
b3 = is true

Ternary: Multi-line Expression Caveat

You mast wrapping the multi-line ternary expressions with (...)

output "c3" {
  value = (
            contains(["a","b","c"], "d")
              ? "is true"
              : "is false"
          )
}

Count Technique

variable "create1" {
  default = true
}
resource "random_pet" "pet1" {
  count = var.create1 ? 1 : 0
  length = 2
}
output "pet1" {
  value = random_pet.pet1
}

Using the Terraform count attribute is that the result of the resource declaration is no longer a single element. It’s an Array.

Another example

locals {
  make_bucket = "${var.create_bucket == "true" ? true : false}"
}

resource "google_storage_bucket" "twinkiebucket" {
  count   = "${local.make_bucket ? 1 : 0}"
  name    = "${var.bucket_name}'
  project = "${var.project_name}" 
}

Condition in for each

resource "aws_security_group_rule" "allowlist" {
  for_each           = var.cidr_blocks == [] ? [] : var.cidr_blocks
  type               = "ingress"
  from_port          = 22
  to_port            = 22
  protocol           = "tcp"
  cidr_blocks        = [each.value]
  security_group_id  = aws_security_group.bastion.id
}

Condition in Parameter

Terraform allows write the conditional expression that will set the null value for the argument. It means the absence or omission and Terraform would behave the same as if you did not specify the argument at all.

resource "aws_launch_template" "this" {
  name     = "my-launch-template"
  ...
  key_name = var.use_default_keypair ? var.keypair_name : null
  ...

Condition in dynamic block

resource "aws_cloudfront_distribution" "cdn" {
  enabled = true
  ...
  dynamic "custom_error_response" {
    for_each = var.custom_error_response == null ? [] : [var.custom_error_response]
    iterator = cer
    content {
      error_code            = lookup(cer.value, "error_code", null)
      error_caching_min_ttl = lookup(cer.value, "error_caching_min_ttl", null)
      response_code         = lookup(cer.value, "response_code", null)
      response_page_path    = lookup(cer.value, "response_page_path", null)
    }
  }
  ...
}