Terraform Conditionals

While terraform makes a lot of infrastructure deployment easy, sometimes it can feel a little bit like trying to thread a needle with while wearing oven mitts. The idea is simple, the execution is hard. One of those principles that hasn’t found it’s way into the HCL is the idea of conditionals.

Let’s say you’re trying to write a service module. The meat of this particular class of service is the same whether provided publicly or privately. So you may want to add a parameter to your module that allows the end user to choose whether to make it a public service or a private service. The public service just needing a handful of different components such as where the DNS zone is created, which TLS certificates to use, how to configure the load balancer, etc.

For these use cases, terraform provides us with a rudimentary ternary operator for conditionals:

CONDITION ? TRUEVAL : FALSEVAL

This allows you to, for example, use a public DNS zone for your record instead of a private DNS zone (modified example taken from terraform.io):

resource "dns_a_record_set" "www" {
  zone = "${var.is_public ? "example.com." : "priv.example.com."}"
  name = "www"
  addresses = [
    "192.168.0.1",
    "192.168.0.2",
    "192.168.0.3",
  ]
  ttl = 300
}

But what if you completely don’t want the resource? This part is less clear, but just as simple:

resource "dns_a_record_set" "www" {
  zone = "example.com."
  name = "www"
  addresses = [
    "192.168.0.1",
    "192.168.0.2",
    "192.168.0.3",
  ]
  ttl = 300
  count = "${var.is_public ? 0 : 1}"
}

By using the conditional on the count parameter we tell terraform to make 0 DNS records if is_public was passed, otherwise make the DNS record.

Derek Anderson

Detroit, United States
Email me

A self proclaimed technologist, nature observer, and aspiring woodworker.