DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

3 2

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! 🍺

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay