May 4, 2021

Terraform functions

In this post, we will discuss Terraform features. The Terraform language includes a number of built-in functions that you can call from expressions to transform and combine values. The general syntax for standard functions is the name of the function, followed by the arguments, separated by commas, in parentheses.

Next, we’re going to explain Terraform’s features with examples. We will be using the terraform console for this demo.

Terraform Functions

Open the terraform console.

terraform console

Numeric Functions

abs(number) returns the absolute value of the given number.

abs(-19.86) # returns 19.86

ceil (number) returns the closest integer that is greater than or equal to the given value.

ceil(7.1) # returns 8

floor(number) returns the closest integer less than or equal to the given value.

floor(7.1) # returns 7

log(number, base) returns the logarithm of a given number to a given base.

log(16,2) # returns 4

max(N1, N2, .. Nn) takes one or more numbers and returns the largest number in the set.

max(3,2,6,8.8,7) # returns 8.8

min(N1, N2, .. Nn) takes one or more numbers and returns the smallest number in the set.

min(3,2,6,8.8,7) # returns 2

pow(number, power) computes an exponent by raising its first argument to the power of its second argument.

pow(8,2) # returns 64

signum(number) specifies the sign of a number, returning a number between -1 and 1 to represent the sign.

signum(-4) # returns -1
signum(4) # returns 1

String functions

chomp(“string”) removes newline characters at the end of the string.

chomp("cloudaffaire\n") # returns cloudaffaire (** only removes \n from the end)

format(spec, values …) creates a string by formatting a number of other values according to the spec string.

format("Welcome, to% s", "CloudAffaire") # returns Welcome, to CloudAffaire.
format("The year is% d", 2019) # returns The year is 2019
format("% 4.4f +", 3.86) # returns 3.8600+

Formatting Specification

formatlist(spec, values ​​…) formatlist creates a list of strings by formatting a number of other values
according to the BOM line. The BOM line uses the same syntax as the format.

formatlist("www.% s.com",list("azure","aws","google")) # returns [www.azure.com, www.aws.com, www.google.com]

indent(num_spaces, string) adds the specified number of spaces to the beginning of all but the first lines in a given multiline line.

indent(8,"hi,\n welcome \n to \n cloudaffaire") # returns the first line without indentation

join(separator, list) creates a string by joining together all the elements of a given list of strings with a given separator.

join(".",list("www","google","com")) # returns www.google.com

lower(string) converts all letters in the given string to lowercase.

lower("CLOUDAFFAIRE") # returns cloudaffaire

upper(string) converts all letters in the given string to uppercase.

upper("cloudaffaire") # returns CLOUDAFFAIRE

replace(string, substring, replacement) searches a given string for another given substring,
and replaces each occurrence with the specified replacement string.

replace("www.google.com","google","cloudaffaire") # returns www.cloudaffaire.com

split(separator, string) creates a list by splitting the given string into all occurrences of the given separator.

split(".","www.google.com") # returns ["www", "google", "com"]

strrev(string) swaps characters in a string. Note that characters are treated as Unicode characters.

strrev("google") # returns: elgoog (only supported in terraform version 0.12 or newer)

substr(string, offset, length) extracts a substring from a given string at offset and length.

substr("www.google.com",4,6) # returns google

title(string) converts the first letter of every word in the given string to uppercase.

title("welcome to cloudaffaire") # returns Welcome To Cloudaffaire

trimspace(string) removes any spaces from the beginning and end of the given string.

trimspace(" hello, all ") # returns "hello, all"

Collection functions

chunklist(list, chunk_size) splits one list into fixed-size chunks, returning a list of lists.

chunklist(list("a", "b", "c", "d", "e", "f"), 3) # returns [["a", "b", "c"] , ["d", "e", "f"]]

coalesce(strings\numbers) takes any number of arguments and returns the first one, which is not null or an empty string.

coalesce("", 1, "a") # returns 1

coalescelist(list1, list2,… listn) accepts any number of list arguments and returns the first non-empty argument.

coalescelist(list(), list("a", "b", "c"), list("d", "e")) # returns ["a", "b", "c", ]

compact(list (string)) takes a list of strings and returns a new list with empty string elements removed.

compact(list("a", "", "c", "", "d")) # returns ["a", "c", "d"]

concat(list1, list2,… listn) takes two or more lists and concatenates them into one list.

concat(list("a", "b"), list("c", "d"), list("e", "f")) # returns ["a", "b", " c "," d "," e "," f "]

contains(list, value) determines whether the given list or set contains a given single value as one of its elements.

contains(list("a", "b", "c"), "a") # returns true
contains(list("a", "b", "c"), "d") # returns false

distinct(list) takes in a list and returns a new list with duplicate elements removed.

distinct(list("a", "b", "b", "c")) # returns ["a", "b", "c",]

element(list, index) retrieves one element from the list.

element(list("a", "b", "c"), 2) # returns c #index start from 0

index(list, value) finds the index of the element for the given value in the list.

index(list("a", "b", "c"), "b") # returns 1

flatten(list(list1, list2, .., listn)) takes a list and replaces any items that are lists with a flattened sequence of the contents of the list.

flatten(list(list("a", "b"), list("c"), list(), list("d", "e"))) # returns ["a", "b "," c "," d "," e ",]

keys(map) takes a map and returns a list containing the keys from that map.

keys(map("name", "debjeet", "sex", "male")) # returns ["name", "debjeet", "sex", "male"]

length(list\map\string) determines the length of the given list, map, or string.

length(list("a", "b")) # returns 2
length("debjeet") # returns 7
length(map("name", "debjeet", "sex", "male")) # returns 2

list() takes an arbitrary number of arguments and returns a list containing those values ​​in the same order.

list("a", "b", "c") # returns ["a", "b", "c",]

lookup(map, key, default) retrieves the value of one element from the map, given its key. If the given key does not exist, the specified default value is returned instead.

lookup(map("name", "debjeet", "sex", "male"), "sex", "not found!") # returns male
lookup(map("name", "debjeet", "", "male"), "gender", "not found!") # returns not found!

map(“key1”, “value1”, “key2”, “value2”, …, “keyn”, “valuen”) takes an even number of arguments and returns a map whose elements are constructed from sequential pairs of arguments.

map("name", "debjeet", "sex", "male") # returns {"name" = "debjeet" "sex" = "male"}

matchkeys(valueslist, keyslist, searchset) creates a new list by taking a subset of items from one list whose indices are matches the corresponding indices of values ​​in another list.

matchkeys(list ("a", "b", "c"), list("one", "two", "three"), list("two")) # returns b
matchkeys(list ("a", "b", "c"), list("one", "two", "three"), list("one")) # returns a
matchkeys(list ("a", "b", "c"), list("one", "two", "three"), list("three")) # returns c

merge(map1, map2, .., mapn) takes an arbitrary number of maps and returns one map contains a combined set of elements from all cards.

merge(map("a", "one"), map("b", "two"), map("c", "three")) # returns {"a" = "one" "b "=" two "" c "=" three "}

reverse(list) takes a sequence and creates a new sequence of the same length with all.
the same elements as the given sequence, but in reverse order.

reverse(list("a", "b", "c")) # returns: ["c", "b", "a",] (only supported in terraform version 0.12 or newer)

setintersection(sets …) takes multiple sets and creates one set containing only the elements that are common to all given sets.

setintersection(list("a", "b"), list("b", "c"), list("b", "d")) # returns ["b",] (only supported in terraform version 0.12 or newer)

setproduct(sets …) finds all possible combinations of elements from all given sets, calculating the Cartesian product.

setproduct(list("a", "b"), list("c", "d")) # returns [["a", "c"], ["a", "d"], ["b", "c"], ["b", "d"],] (only supported in terraform version 0.12 or newer)

setunion(sets …) takes multiple sets and creates one set containing elements from all given sets.
In other words, it computes the union of the sets.

setunion(list("a", "b"), list("c", "d")) # returns ["a", "b", "c", "d",] (only supported in terraform version 0.12 or newer)

slice(list, startindex, endindex) extracts multiple consecutive elements from a list.

slice(list("zero", "one", "two", "three"), 1,3) # returns ["one", "two"]

sort(list) takes a list of strings and returns a new list with those strings sorted lexicographically.

sort(list ("d", "c", "a", "b")) # returns ["a", "b", "c", "d",]

transpose() takes a map of string lists and swaps the keys and values ​​to create a new map of string lists.

transpose(map("a", list("one", "two"), "b", list("three", "four"))) # returns {"four" = ["b", ] "one" = ["a",] "three" = ["b",] "two" = ["a",]}

values​(map) takes a map and returns a list containing the values ​​of the elements in that map.

values​(map("name", "debjeet", "sex", "male")) # returns ["debjeet", "male",]

zipmap(keyslist, valueslist) creates a map from a list of keys and a corresponding list of values.

zipmap(list("name", "sex"), list("debjeet", "male")) # returns {"name" = "debjeet" "sex" = "male"}

Encoding functions

base64encode(string) applies base64 encoding to the string.

base64encode("cloudaffaire") # returns Y2xvdWRhZmZhaXJl

base64gzip(string) compresses the string with gzip and then base64 encodes the result.

base64gzip("cloudaffaire") # returns H4sIAAAAAAAA/0rOyS9NSUxLS8wsSgUAAAD//wEAAP//38z9sQwAAAA=

base64decode(string) takes a string containing a sequence of base64 characters and returns the original string.

base64decode("Y2xvdWRhZmZhaXJl") # returns cloudaffaire

csvdecode(string) decodes a string containing CSV data and creates a list of cards representing that data.

csvdecode("a, b,c\n1,2,3\n") # returns [{"a" = "1" "b" = "2" "c" = "3"},] ( only supported in terraform version 0.12 or newer)

jsonencode() encodes a given value into a string using JSON syntax.

jsonencode(map("name", "debjeet")) # returns {"name": "debjeet"}

jsondecode() interprets the given string as JSON, returning a representation of the decoded result of that string.

jsondecode("{\"name\":\"debjeet\"}") # returns {"name" = "debjeet"} (only supported in terraform version 0.12 or newer)

urlencode() applies url encoding to the given string.

urlencode("https://cloudaffaire.com/?s=terraform") # returns https%3A%2F%2Fcloudaffaire.com%2F%3Fs%3Dterraform

Functions for working with the file system

dirname(string) takes a string containing the path to the filesystem and removes the last part from it.

dirname("/home/ec2-user/terraform/main.tf") # returns /home/ec2-user/terraform

pathexpand() accepts a filesystem path, which may start with a segment ~, and if so, it replaces that segment with the path to the current user’s home directory.

pathexpand("~/.ssh/id_rsa") # returns /home/ec2-user/.ssh/id_rsa

basename(string) takes a string containing the path to the filesystem and removes everything from it except the last part.

basename("/home/ec2-user/terraform/main.tf") # returns main.tf

file(path) reads the contents of the file at the given path and returns it as a string

file("/home/ec2-user/terraform/main.tf") # returns content of main.tf

fileexists(path) determines if the file exists at the given path.

fileexists("/home/ec2-user/terraform/main.tf") # returns true if main.tf exist (only supported in terraform version 0.12 or newer)

filebase64(path) reads the contents of the file at the given path and returns it as a base64 encoded string.

filebase64("/home/ec2-user/terraform/main.tf") # returns the content of main.tf as base64 data. (only supported in terraform version 0.12 or newer)

templatefile(path, vars) reads a file at a given path and displays its contents as a template using the provided set of template variables.

templatefile(/home/ec2-user/terraform/main.tf, var1, var2, etc...) # returns the contents of main.tf filled with values ​​from function parameters.

Functions for working with date and time

formatdate(spec, timestamp) converts a timestamp to a different time format.

formatdate("MMM DD, YYYY", "2018-01-02T23:12:01Z") # returns Jan 02, 2018 (only supported in terraform version 0.12 or newer).
See specification https://www.terraform.io/docs/configuration/functions/formatdate.html

timeadd(timestamp, duration) adds a duration to a timestamp, returning a new timestamp.
Duration is a string representation of the time difference, consisting of sequences of pairs of numbers and units, such as “1.5 hours” or “1 hour 30 minutes.”
Accepted units: “ns”, “us” (or “µs”), “ms”, “s”, “m”, and “h”.
The first number can be negative to indicate negative duration, such as “-2h5m”.

timeadd("2019-05-10T00:00:00Z", "10m") # returns 2019-05-10T00:10:00Z

timestamp() returns the current date and time


Functions for working with IP networks

cidrhost(prefix, hostnum) computes the full host IP address for the given host number within the given network IP prefix.

cidrhost("", 4) # returns
cidrhost("", -4) # returns

cidrnetmask(prefix) converts the IPv4 address prefix specified in CIDR notation to a subnet mask address.

cidrnetmask("") # returns
cidrnetmask("") # returns

cidrsubnet(prefix, newbits, netnum) computes a subnet address within a given network IP prefix.
the prefix must be specified in CIDR notation
newbits is the number of extra bits that can be used to extend the prefix.
netnum is an integer that can be represented as a binary integer with no more than binary digits newbits

cidrsubnet("", 8.2) # returns
cidrsubnet("", 8.1) # returns

Exit Terraform Console

Posted in TechTaggs: