Terraform Conditionals Cheat Sheet
Conditionals in Terraform
Just a quick cheat sheet to use when writing conditionals in Terraform.
In my role, I write a lot of Terraform but can go a few weeks in between. It’s handy to have a quick reference to look back at.
As AI coding companions improve, this will likely become less useful.
The Ternary Operator
As opposed to a traditional if statement, Terraform uses ternary operators for conditional expressions. A conditional expression uses the value of a boolean expression to select one of two values.
The condition can be any expression that resolves to a boolean value. This will usually be an expression that uses the equality, comparison, or logical operators.
Format is:
Basic Conditional Expression
Prod key vaults should use the Premium SKU, all others should use Standard SKU.
Using And/Or
And
If it’s Prod AND a critical app, use the premium sku, otherwise use standard.
Or
Prod and UAT should both use the Premium SKU, all other environments will use Standard.
Replace Invalid Values
In the example below, the user is given the option to supply a diagnostic_setting_name. If they elect not to, we will set the value to a dynamic expression ${var.app_name}-diag. This is a useful workaround to not being able to use calculated values in your variable defaults.
Nested Conditions
Nested conditionals are possible:
Nested Conditionals Example
If the workload is both a production workload and a high CPU workload, we’ll use c5.xlarge. If it’s a production workload but not a high CPU workload, we’ll assign t3.large. All other workloads will receive a t3.small.
Conditional Creation
Count
Count resources use zero-based indexing.
Create a redis cache only for Prod environments.
If high_availability is true, deploy 3 VMs, otherwise deploy a single instance.
For_Each
Below, we configure environment settings in independent maps, local.prod_settings and local.dev_settings.
We then use a conditional to assign the appropriate settings to active_settings.
Once in our Redis resource, we check for the presence of a cache key and create the cache with appropriate settings if found.
Conditionals as Filters
Filter Example
admin_group_members will be a map consisting only of Admin users from var.users.
This can then be used to feed a for_each for a resource, module, or even a data source.
Dynamic Blocks
Conditional expressions can be used within dynamic blocks as well.