Tuesday 31 May 2022

Terraform Operators and Conditional Expressions

 



Numeric Operators


% terraform console
> 1+2
3
> 2-1
1
> 2*3
6
> 8/2
4


Equality & Comparison Operators


> 1 == 1
true
> 1 < 2
true
> 2 < 1
false
> 2 >= 1
true
> 1 == "1"
false
> 1 != "1"
true
>  


Logical Operators


AND, OR, NOT

> 1 < 2 && false
false
> 1 < 2 && true
true
> 1 < 2 || false
true
> 1 < 2 || true
true
> !(1 < 2) || false
false
> !(1 < 2)
false


main.tf:

variable flag {
type = bool
default = false
}

variable num_a {
type = number
default = 11
}

variable num_b {
        type = number
        default = 22
}

> var.flag
false
> !var.flag
true
> var.num_a
11
> var.num_b
22
> var.num_b < var.num_a
false

Conditional Expressions


value = condition ? value_if_condition_is_true : value_if_condition_is_false

Example: We want to provision a password generator that creates a random password of the length specified by the user. If length is less than 8 characters then generator will use the default length value of 8.

main.tf:

resource "random_password" "pwd-generator" {
length = var.length < 8 ? 8 : var.length
}

output password {
value = random_password.pwd-generator.result
    sensitive = true
}

variable length {
type = number
}

In terminal:

$ terraform apply -var=length=6 -auto-approve
$ terraform output password
"DIo${L-*"

$ terraform apply -var=length=10 -auto-approve
$ terraform output password
"0Y3}Fh2Na2"

No comments: