Lab description
In this lab we learn about functions
in Terraform.
Expressions
Setup
Make sure you are in the correct folder:
1
cd ~/terraform-labs
1
cd ~/terraform-labs
If you were unable to complete the last lab, you can find a copy of the files in the solutions folder
1. Launch Interactive Console
Terraform comes with an interactive console that is very handy to evaluate expresssions and exploring functions.
1
terraform console
1
terraform console
You should see your prompt >
appear.
To exit the console at any time and go back to cloud shell’s terminal, just type exit
or press ctrl + c. To clear the screen, press ctrl + l
NOTE: The Terraform console can be tricky to paste into. Right-click your mouse after copying an individual command to get it to work.
1. Explore and practice a handful of built-in functions using the console
Built-in functions greatly help with writing cleaner code. We will use some of the functions in our config later as well.
-
Numeric Functions
1 2 3 4 5 6 7 8 9 10 11
# max value max(5,12,9) # max value from a list max([12,54,3]...) # ceil to return closest whole number that is greater than or equal to given value ceil(5.3) # parseint - parse a string as int for given base (decimal here) parseint("35", 10)
-
String Functions
1 2 3 4 5 6 7 8
# split string into a list split(",", "foo,bar,baz") # convert list to a string based on a separator join(" ", ["foo", "bar", "baz"]) # convert string to lower-case lower("HELLO")
-
Collection Functions
1 2 3 4 5 6 7 8
# retrieve keys from a map as a list keys({a=1, c=2, d=3}) # sort a list sort(["e", "d", "a"]) # get length of string, list or map length([1, 2, 3, 4, 5])
-
Type Conversion functions
1 2
# convert list to a set to remove duplicates toset(["c", "b", "b"])
-
Encoding Functions
1 2 3 4 5
# decode a base64 encoded string base64decode("SGVsbG8gV29ybGQ=") # encode given value as a json string jsonencode({"hello"="world"})
-
Hash and Crypto Functions
1 2
# compute sha256 for given string sha256("hello world")
-
Filesystem functions
1 2 3 4 5
# get absolute path of given filesystem path abspath(path.root) # read file contents and return them as a string file("main.tf")
-
Date and time functions
1 2
# timeadd(timestamp, duration) timeadd("2020-06-08T00:00:00Z", "10m")
-
IP Network functions
1 2 3
# calculate a subnet address within given IP network address prefix. # cidrsubnet(prefix, newbits, netnum) cidrsubnet("172.16.0.0/16", 8, 0)
2. Use the console to see Terraform settings
-
Update
main.tf
include this locals block:1 2 3
locals { subnets = cidrsubnets("10.0.0.0/24", 8, 7) }
-
Exit the console with ctrl + c and then run
terraform console
again. -
Now you can access the values of the locals block:
1
local.subnets
1
local.subnets
For a full list of built-in functions, see below and try out the ones that you find interesting.
Back to Lab Index