DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Updated on

Terraform tips for newcomers

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Terraform documentation : https://www.terraform.io/docs/language/expressions/conditionals.html


Conditionnal/Multiple resources

resource "xxx" "yyyy" {
  ....
  count            = "${var.a == "a" ? 1 : 0}"
}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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)