Terraform

Terraform Functions Tutorial

This is a Terraform Functions tutorial for beginners.

1. Overview

Terraform was first developed by Mitchell Hashimotoon May 21st, 2014 in HashiCorp. It is used for deveoping application code and handling infrastructure security. Terraform is a popular DevOps tool in the technology space. Terraform has in built functions. Functions can be invoked in the expressions to join and modify the values. The syntax followed is function name and comma-separated arguments within the parentheses.

2. Terraform Functions Tutorial

Terraform functions help in changing the data and are used for joining, modifying, and other operations. Terra has functions for type conversions, value combinations, selection, correction, date, time, hashing, IP addresses and others.

2.1 Prerequisites

Terraform is necessary on the operating system in which you want to execute the code.

2.2 Download

You can download Terraform from this website.

2.3 Setup

2.3.1 Terraform Setup

You can set up the Terraform by using the command below on macOS:

Terraform Setup

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

You can run this command to check if it is working:

Terraform Execution

 terraform -v

The output of the above command executed is shown below:

Terraform Execution Output

apples-MacBook-Air:~ bhagvan.kommadi$  terraform -v
Terraform v1.1.5
on darwin_amd64
apples-MacBook-Air:~ bhagvan.kommadi$

The terraform execution command has other options which are shown below:

Terraform Execution Options

$ terraform Usage: terraform [-version] [-help]  [args] ... help content omitted

2.4 What is Terraform ?

Terraform is used for creating projects with resource definitions. You can define resources with files and add suffix .tf. Terraform language is used for resource configuration. Resources can be for AWS EC2, Azure Maria Database, and DNS entry.

2.5 Why do we use terraform?

Terraform helps in improving the development operations. It improves efficiency by automating the operations. It is used for managing the infrastructure like in Infrastructure as a code. You can manage the low-level and high-level components. Low-level components that can be managed are computed instances, storage, and networking. High level components which can be managed are DNS entries, SaaS features, and others.

2.6 Numeric Functions

Now let us see the numeric functions supported in Terraform language.

  • abs : This function abs(x) returns the  absolute value of the input number
  • ceil : This function ceil(x) returns the closest whole number that is greater than or equal to the input value
  • floor : This function floor(x)  returns the closest whole number that is less than or equal to the input value
  • log : This function log(x,ibase)  returns the logarithm of an input number in an input base.
  • max: This function max(x,y,z) takes one or more input numbers and returns the greatest number from the input set.
  • min: This function min(x,y,z) takes one or more input numbers and returns the smallest number from the input set
  • parseint : This function parseint(strx) parses the input string as a representation of an integer in the specified base and returns the output which is resulting number.
  • pow: This fuction pow(x,y) calculates an exponent x, by raising its first argument to the power of the second input y.
  • signum: This function signup(x) finds the sign of a number, returning a number between -1 and 1 to represent the sign.

2.7 String Functions

Now let us look at the string functions supported in terraform language.

  • chomp : This function chomp(stry) removes newline characters at the end of a string.
  • format : This function format(stry) returns a string by formatting a number of other values according to a specification string
  • formatlist: This function formatlist(pattern,stry) returns a list of strings by formatting a number of other values according to a specification string pattern.
  • indent : This function indent(spacecount,stry) adds a given number of spaces to the beginnings of all but the first line in a given multi-line string
  • join : This function join(delimiter,str2) returns a string by concatenating together all elements of a given list of strings with the given delimiter.
  • lower : This function lower(str2) transforms all cased letters in the given string to lowercase.
  • regex : This function regex(pattern, str1) applies a regex pattern to a string and returns the matching substrings.
  • regexall : This function regexall(pattern, str1) applies a regex pattern to and returns a list of all matches.
  • replace : This function replace(str1,str2, replace) searches a given string for another given substring, and replaces each occurrence with a given replacement string.
  • split : This function split(delimiter,str1) creates a list by dividing a given string at all occurrences of a given delimiter.
  • strrev: This function strive(str1) reverses the characters in a string. Note that the characters are treated as Unicode characters
  • substr : This function subset(str1,offset,len) a substring from a given string by offset and length
  • title: This function title(str1) changes the first letter of each word in the given string to uppercase
  • trim: This function trim(str1) deletes the specified set of characters from the start and end of the given string.
  • trimprefix : This function trimprefix(pre,str1) deletes the specified prefix pre from the start of the input string str1.
  • trimsuffix : This function trim suffix(str1,suff) deletes the specified suffix prefix from the end of the input string str1.
  • trimspace: This function trimspace(str1) deletes any space characters from the start and end of the input string str1
  • upper: This function upper(str1)  transforms all cased letters in the input string str1 to uppercase

2.8 Collection Functions

Now let us see the collection functions in terraform language.

  • alltrue : returns true if all elements in a given collection are true or “true”. It also returns true if the collection is empty.
  • anytrue : returns true if any element in a given collection is true or "true". It also returns false if the collection is empty.
  • chunklist : splits a single list into fixed-size chunks, returning a list of lists
  • coalesce : takes any number of arguments and returns the first one that isn’t null or an empty string.
  • coalescelist : takes any number of list arguments and returns the first one that isn’t empty.
  • compact : takes a list of strings and returns a new list with any empty string elements removed.
  • concat : takes two or more lists and combines them into a single list.
  • contains : determines whether a given list or set contains a given single value as one of its elements.
  • distinct :  takes a list and returns a new list with any duplicate elements removed.
  • element : retrieves a single element from a list.
  • flatten : takes a list and replaces any elements that are lists with a flattened sequence of the list contents.
  • index :  finds the element index for a given value in a list.
  • keys :  takes a map and returns a list containing the keys from that map.
  • length : determines the length of a given list, map, or string.
  • lookup : retrieves the value of a single element from a map, given its key. If the given key does not exist, the given default value is returned instead.
  • matchkeys : constructs a new list by taking a subset of elements from one list whose indexes match the corresponding indexes of values in another list.
  • merge : takes an arbitrary number of maps or objects, and returns a single map or object that contains a merged set of elements from all arguments.
  • one : takes a list, set, or tuple value with either zero or one elements.
  • range : generates a list of numbers using a start value, a limit value, and a step value.
  • reverse : takes a sequence and produces a new sequence of the same length with all of the same elements as the given sequence but in reverse order.
  • setintersection :  takes multiple sets and produces a single set containing only the elements that all of the given sets have in common
  • setproduct : finds all of the possible combinations of elements from all of the given sets by computing the Cartesian product.
  • setsubtract : returns a new set containing the elements from the first set that are not present in the second set
  • setunion : takes multiple sets and produces a single set containing the elements from all of the given sets.
  • slice :  extracts some consecutive elements from within a list.
  • sort : takes a list of strings and returns a new list with those strings sorted lexicographically.
  • sum :  takes a list or set of numbers and returns the sum of those numbers.
  • transpose :  takes a map of lists of strings and swaps the keys and values to produce a new map of lists of strings.
  • values : takes a map and returns a list containing the values of the elements in that map.
  • zipmap : constructs a map from a list of keys and a corresponding list of values.

2.9 Encoding Functions

Now let us see the encoding functions in the terraform language.

  • base64decode : takes a string containing a Base64 character sequence and returns the original string
  • base64encode : applies Base64 encoding to a string
  • base64gzip : compresses a string with gzip and then encodes the result in Base64 encoding
  • csvdecode : decodes a string containing CSV-formatted data and produces a list of maps representing that data
  • jsondecode :  interprets a given string as JSON, returning a representation of the result of decoding that string.
  • jsonencode : encodes a given value to a string using JSON syntax.
  • textdecodebase64 : decodes a string that was previously Base64-encoded, and then interprets the result as characters in a specified character encoding
  • textencodebase64 : encodes the unicode characters in a given string using a specified character encoding, returning the result base64 encoded
  • urlencode : applies URL encoding to a given string
  • yamldecode : parses a string as a subset of YAML, and produces a representation of its value.
  • yamlencode : encodes a given value to a string using YAML 1.2 block syntax

2.10 Filesystem Functions

Now let us see the Filesystem functions in the terraform language.

  • abspath : takes a string containing a filesystem path and converts it to an absolute path.
  • dirname : takes a string containing a filesystem path and removes the last portion from it.
  • pathexpand : takes a filesystem path that might begin with a ~ segment, and if so it replaces that segment with the current user’s home directory path
  • basename : takes a string containing a filesystem path and removes all except the last portion from it.
  • file : reads the contents of a file at the given path and returns them as a string.
  • fileexists : determines whether a file exists at a given path
  • fileset : enumerates a set of regular file names given a path and pattern.
  • filebase64 : reads the contents of a file at the given path and returns them as a base64-encoded string
  • templatefile : reads the file at the given path and renders its content as a template using a supplied set of template variables.

2.11 Date and Time Functions

Now let us see the date and time functions in the terraform language.

  • formatdate : This function formatdate(format, timestamp) changes a timestamp into a different time format.
  • timeadd: This function timeadd(timestamp, duration) adds a input duration to a timestamp, returning a new timestamp
  • timestamp: This function timestamp() returns a UTC timestamp string in RFC 3339 format

2.12 Hash and Crypto Functions

Now let us see the hash and crypto functions in the terraform language.

  • base64sha256 :computes the SHA256 hash of a given string and encodes it with Base64
  • base64sha512 : computes the SHA512 hash of a given string and encodes it with Base64
  • bcrypt : computes a hash of the given string using the Blowfish cipher
  • filebase64sha256 : hashes the contents of a given file rather than a literal string using sha256
  • filebase64sha512 : hashes the contents of a given file rather than a literal string.using sha512
  • filemd5 : hashes the contents of a given file rather than a literal string using md5
  • filesha1 : hashes the contents of a given file rather than a literal string using sha1
  • filesha256 : hashes the contents of a given file rather than a literal string using sha256
  • filesha512 : hashes the contents of a given file rather than a literal string using sha512
  • md5 :  computes the MD5 hash of a given string and encodes it with hexadecimal digits
  • rsadecrypt:  decrypts an RSA-encrypted ciphertext, returning the corresponding cleartext.
  • sha1 : computes the SHA1 hash of a given string and encodes it with hexadecimal digits.
  • sha256 :  computes the SHA256 hash of a given string and encodes it with hexadecimal digits
  • sha512 : computes the SHA512 hash of a given string and encodes it with hexadecimal digits
  • uuid : generates a unique identifier string
  • uuidv5 : generates a name-based UUID,

2.13 IP Network Functions

Now let us see the IP Network functions in this terraf language in this terra functions tutorial.

  • cidrhost :  calculates a full host IP address for a given host number within a given IP network address prefix
  • cidrnetmask : converts an IPv4 address prefix given in CIDR notation into a subnet mask address.
  • cidrsubnet : calculates a subnet address within given IP network address prefix.
  • cidrsubnets : calculates a sequence of consecutive IP address ranges within a particular CIDR prefix

2.14 Type Conversion Functions

Now let us see the type conversion functions in the terraform language.

  • can : evaluates the given expression and returns a boolean value indicating whether the expression produced a result without any errors.
  • defaults : used with input variables whose type constraints are object types or collections of object types that include optional attributes
  • nonsensitive : takes a sensitive value and returns a copy of that value with the sensitive marking removed, thereby exposing the sensitive value
  • sensitive : takes any value and returns a copy of it marked so that Terraform will treat it as sensitive, with the same meaning and behavior as for sensitive input variables.
  • tobool :  converts its argument to a boolean value.
  • tolist : converts a set or tuple value to a list.
  • tomap : converts an object value to a map.
  • tonumber : converts its argument to a number value.
  • toset : converts its argument to a set value.
  • tostring : converts its argument to a string value
  • try : evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors.
  • type : retuns the type of a given value.

3. Download the Source Code

Download
You can download the full source code of this example here: Terraform Functions Tutorial

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button