Terraform patterns: conditionals

This is a back to basics post about a Terraform pattern: conditionals. It's Azure centric.

Conditionals: if then else

Imagine we want a resource group name to follow the rules of naming convention but in other cases we don't want to. So if there is a naming convention, implement that, if not than do not.

For example, the naming convention should follow this pattern: <projectname>-<environment>-<resource> . We want every resource to be prefixed by that pattern. So if the prefix is set, please use the prefix pattern, else just take the variable of the full name.

This is where the ternary operator comes in. If var.prefix is an empty string then the result is "my-prefix-rg", but otherwise it is the actual value of var.rg_name:

Symbol Meaning
if var.prefix condition
? then
do stuff
: else
do other stuff
1# condition ? true_val : false_val
2name  = var.rg_name == null ? "${var.prefix}-rg" : var.rg_name

A full example

main.tf

1resource "azurerm_resource_group" "rg" {
2  name     = var.rg_name == null ? "${var.prefix}-rg" : var.rg_name
3  location = var.location
4  tags     = var.tags
5}

variables.tf

 1variable prefix {
 2  default = "projextx-dev"
 3}
 4
 5variable rg_name {
 6  default = null
 7}
 8
 9variable "location" {
10  default = "westeurope"
11}
12
13# let's add tags
14variable "tags" {
15  default = {
16    owner = "jacqueline"
17    department = "research"
18  }
19}

What about the null value?

Terraform v0.12 allows assigning the special value null to an argument to mark it as "unset". So a module can allow its caller to conditionally override a value while retaining the default behavior if the value is not defined.

In other words:

  • null can be used with conditionals
  • in other cases: null does not mean a resource does not get created. It just means its default behaviour will be applied.

https://www.hashicorp.com/blog/terraform-0-12-conditional-operator-improvements

The next pattern will be loops.