Terraform is quite large. You have a lot of possibilities do to with, and here are some tips to help you with your scripts.
Conditionnal Expressions
condition ? true_val : false_val
If quite simple, it looks like ternary condition in Java for example.
If the condition is true, the true_val will be used, otherwise it will be the false_val.
example
var.a != "" ? var.a : "default-a"
Terraform documentation : https://www.terraform.io/docs/language/expressions/conditionals.html
Conditionnal/Multiple resources
resource "xxx" "yyyy" {
....
count = "${var.a == "a" ? 1 : 0}"
}
To create some elements depending conditions, or to create multiple instances of a resource, we can use count.
Mixed with a conditional expression we can defined how much elements the script needs to create. So if you're defining a case were the script must create 0 instances, so you have a conditionnal resource.
Documentation : https://dev.to/tbetous/how-to-make-conditionnal-resources-in-terraform-440n
Local values
locals {
service_name = "forum"
owner = "Community Team"
name = "${var.env}-xxxx"
}
locals is an object with static values (which can't be overrided by variables) or can help to create some values from the variables inputs.
It can be really useful to avoid redefining a value in multiple resources.
Terraform documentation : https://www.terraform.io/docs/language/values/locals.html
I hope it will help you! 🍺
Top comments (0)