10

Terraform tips for newcomers

 2 years ago
source link: https://dev.to/adaendra/terraform-tips-for-newcomers-4cpb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK