Tuesday 31 May 2022

Terraform Functions

 


file() reads data from a file.

content = file("users.json")

 
length() returns number of elements in a list or map:
 
count = length(var.users)

 
toset() converts a list (duplicates are allowed) into a set (no duplicates).

variable users {
    type = list
    default = [
        "Anne",
        "Anne",
        "Billy",
        "Connor",
    ]
    description = "A list of users"
}

resource "local_file" "users" {
    ...
    for_each = toset(var.users)
}

Terraform Interactive Console


It can be used for testing functions and interpolations. To launch it:

$ terraform console

Let's test file function:

$ terraform console
> file("users.txt")
<<EOT
Anne
Anne
Billy
Connor

EOT
>  

> length(var.users)
4

> toset(var.users)
toset([
  "Anne",
  "Billy",
  "Connor",
])


 

Numeric Functions



> max(1, 2, 3)
3
> min(1, 2, 3)
1


variable values {
    type = set(number) 
    default = [1, 2, 3]
}

To use variable as a function parameter, we need to use the expansion symbol

> max(var.values...)
3

> ceil(1.1)
2
> ceil(1.99)
2
> floor(1.01)
1
> floor(1.99)
1




String Functions

 
 variable ami_ids {
    type = string
    default = "ami-000, AMI-001, ami-002, ami-003"
}

> var.ami_ids
"ami-000, AMI-001, ami-002, ami-003"

> split(",", var.ami_ids)
tolist([
  "ami-000",
  " AMI-001",
  " ami-002",
  " ami-003",
])

> lower(var.ami_ids)
"ami-000, ami-001, ami-002, ami-003"
 
> upper(var.ami_ids)
"AMI-000, AMI-001, AMI-002, AMI-003"

 
To convert only the first character to uppercase:

> title(var.ami_ids)
"Ami-000, AMI-001, Ami-002, Ami-003"

substr - extracts the substring.

> substr(var.ami_ids, 0, 3)
"ami"
> substr(var.ami_ids, 0, 7)
"ami-000"


To get the all characters from the offset to the end of the string, length should be set to -1.


> join(".", [192, 168, 0, 1])
"192.168.0.1"
> join(".", ["192", "168", "0", "1"])
"192.168.0.1"

> join(",", var.users)
"Anne,Anne,Billy,Connor"



Collection Functions

 
> length(var.users)
4

 
 
> index(var.users, "Anne")
0
> index(var.users, "Billy")
2

 
 
To return the element at the specified index:
 
> element(var.users, 3)
"Connor"

 
 
> contains(var.users, "Bojan")
false
> contains(var.users, "Billy")
true

 
 
variable "amis" {
    type = map
    default = {
        "eu-west-1" = "ami-000"
        "eu-south-2" = "ami-001"
        "us-east-1" = "ami-002"
    }
}
 
 
> keys(var.amis)
tolist([
  "eu-south-2",
  "eu-west-1",
  "us-east-1",
])

 
 
> values(var.amis)
tolist([
  "ami-001",
  "ami-000",
  "ami-002",
])
 
 
> lookup(var.amis, "us-east-1")
"ami-002"> lookup(var.amis, "us-east-2")

│ Error: Error in function call

│   on <console-input> line 1:
│   (source code not available)

│ Call to function "lookup" failed: lookup failed to find key "us-east-2".


> lookup(var.amis, "us-east-2", "ami-003")
"ami-003"
 
 

No comments: