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.


var.a != "" ? var.a : "default-a"
Enter fullscreen mode Exit fullscreen mode

Terraform documentation :

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 :

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 :

I hope it will help you! 🍺

Top comments (0)