Terraform Function (Part-14)

Posted by

Terraform functions are built-in functions that allow you to manipulate and process data within your Terraform configuration files. They help in transforming and handling various data types, making your configurations more dynamic and flexible. Terraform provides a wide range of functions grouped into categories such as string functions, numeric functions, collection functions, filesystem functions, and more.

official link – https://developer.hashicorp.com/terraform/language/functions

Categories of Terraform Functions

  1. String Functions
  2. Numeric Functions
  3. Collection Functions
  4. Filesystem Functions
  5. Date and Time Functions
  6. Encoding Functions
  7. IP Network Functions
  8. Type Conversion Functions

Detailed Explanation and Examples

1. String Functions

Common string functions include:

  • upper(): Converts a string to uppercase.
  • lower(): Converts a string to lowercase.
  • trimspace(): Removes leading and trailing whitespace from a string.
  • replace(): Replaces occurrences of a substring within a string.

Examples:

variable "input_string" {
  default = " Hello, Terraform! "
}

output "upper_case" {
  value = upper(var.input_string) # Outputs: " HELLO, TERRAFORM! "
}

output "lower_case" {
  value = lower(var.input_string) # Outputs: " hello, terraform! "
}

output "trimmed_string" {
  value = trimspace(var.input_string) # Outputs: "Hello, Terraform!"
}

output "replaced_string" {
  value = replace(var.input_string, "Terraform", "World") # Outputs: " Hello, World! "
}

2. Numeric Functions

Common numeric functions include:

  • abs(): Returns the absolute value of a number.
  • min(): Returns the smallest of the numbers provided.
  • max(): Returns the largest of the numbers provided.

Examples:

variable "numbers" {
  default = [-10, 0, 5, 15]
}

output "absolute_value" {
  value = abs(var.numbers[0]) # Outputs: 10
}

output "minimum_value" {
  value = min(var.numbers...) # Outputs: -10
}

output "maximum_value" {
  value = max(var.numbers...) # Outputs: 15
}

3. Collection Functions

Common collection functions include:

  • length(): Returns the number of elements in a collection.
  • concat(): Concatenates multiple lists into one.
  • element(): Retrieves an element from a list by its index.

Examples:

variable "list1" {
  default = ["a", "b", "c"]
}

variable "list2" {
  default = ["d", "e", "f"]
}

output "list_length" {
  value = length(var.list1) # Outputs: 3
}

output "concatenated_list" {
  value = concat(var.list1, var.list2) # Outputs: ["a", "b", "c", "d", "e", "f"]
}

output "second_element" {
  value = element(var.list1, 1) # Outputs: "b"
}

4. Filesystem Functions

Common filesystem functions include:

  • file(): Reads the contents of a file.
  • dirname(): Returns the directory part of a file path.
  • basename(): Returns the base name of a file path.

Examples:

variable "file_path" {
  default = "/path/to/myfile.txt"
}

output "file_content" {
  value = file(var.file_path) # Outputs the content of the file
}

output "directory_name" {
  value = dirname(var.file_path) # Outputs: "/path/to"
}

output "base_name" {
  value = basename(var.file_path) # Outputs: "myfile.txt"
}

5. Date and Time Functions

Common date and time functions include:

  • timestamp(): Returns the current timestamp.
  • timeadd(): Adds a specified duration to a timestamp.

Examples:

output "current_time" {
  value = timestamp() # Outputs the current timestamp
}

output "future_time" {
  value = timeadd(timestamp(), "1h") # Outputs the timestamp one hour from now
}

6. Encoding Functions

Common encoding functions include:

  • base64encode(): Encodes a string using Base64 encoding.
  • base64decode(): Decodes a Base64 encoded string.

Examples:

variable "input_string" {
  default = "Hello, Terraform!"
}

output "base64_encoded" {
  value = base64encode(var.input_string) # Outputs: "SGVsbG8sIFRlcnJhZm9ybSE="
}

output "base64_decoded" {
  value = base64decode("SGVsbG8sIFRlcnJhZm9ybSE=") # Outputs: "Hello, Terraform!"
}

7. IP Network Functions

Common IP network functions include:

  • cidrsubnet(): Calculates a subnet within a given CIDR range.
  • cidrhost(): Calculates an IP address within a given CIDR range.

Examples:

variable "cidr_block" {
  default = "10.0.0.0/16"
}

output "subnet_cidr" {
  value = cidrsubnet(var.cidr_block, 8, 1) # Outputs: "10.0.1.0/24"
}

output "host_ip" {
  value = cidrhost(var.subnet_cidr, 5) # Outputs an IP address within the subnet
}

8. Type Conversion Functions

Common type conversion functions include:

  • toset(): Converts a list to a set.
  • tolist(): Converts a set or map to a list.
  • tomap(): Converts a list of pairs to a map.

Examples:

variable "list_of_pairs" {
  default = [
    ["key1", "value1"],
    ["key2", "value2"]
  ]
}

output "converted_set" {
  value = toset(["a", "b", "c"]) # Outputs: ["a", "b", "c"]
}

output "converted_list" {
  value = tolist({key1 = "value1", key2 = "value2"}) # Outputs: ["key1", "key2"]
}

output "converted_map" {
  value = tomap(var.list_of_pairs) # Outputs: { key1 = "value1", key2 = "value2" }
}

Terraform functions provide powerful tools to manipulate data within your configurations. By understanding and utilizing these functions, you can create more dynamic, flexible, and reusable Terraform code. Whether you’re working with strings, numbers, collections, or more complex data types, Terraform functions help streamline your infrastructure as code workflows.

Terraform console

The Terraform language includes a number of built-in functions that you can call from within expressions to transform and combine values. The general syntax for function calls is a function name followed by comma-separated arguments in parentheses:

max(5, 12, 9)

The Terraform language does not support user-defined functions, and so only the functions built in to the language are available for use.

You can experiment with the behavior of Terraform’s built-in functions from the Terraform expression console, by running the terraform console command:

max(5, 12, 9)
12

List of top 20 terraform Function

Here are the top 20 Terraform functions with one-liner explanations:

  1. concat: Concatenates two or more lists together.
  2. element: Selects a specific element from a list.
  3. join: Joins a list of strings into a single string.
  4. map: Creates a map from a list of keys and values.
  5. slice: Extracts a slice of a list.
  6. format: Formats a string with placeholders for variables.
  7. file: Reads the contents of a file.
  8. lookup: Looks up a value in a map based on a key.
  9. replace: Replaces parts of a string with other values.
  10. setproduct: Generates all combinations of elements from multiple sets.
  11. sort: Sorts a list of values.
  12. toset: Converts a list to a set, removing any duplicates.
  13. transpose: Transposes a matrix.
  14. uuid: Generates a unique ID.
  15. abs: Returns the absolute value of a number.
  16. ceil: Rounds up to the nearest integer.
  17. floor: Rounds down to the nearest integer.
  18. max: Returns the maximum value from a list.
  19. min: Returns the minimum value from a list.
  20. timeadd: Adds a duration to a timestamp.

These functions can be used to manipulate and transform data within your Terraform configurations, and can help you to write more flexible and dynamic infrastructure as code.

Top terraform function with example usecase with aws provider

  1. count: The count function allows you to create multiple instances of a resource based on a variable value. For example, you can use count to create multiple EC2 instances.
resource "aws_instance" "example" {
  count = var.instance_count
  ami = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
  1. element: The element function allows you to select a specific element from a list. For example, you can use element to select a specific subnet in a list of subnets.
resource "aws_instance" "example" {
  subnet_id = element(var.subnet_ids, 0)
  ami = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
  1. join: The join function allows you to join a list of strings into a single string. For example, you can use join to create a comma-separated list of security group IDs.
resource "aws_security_group_rule" "example" {
  security_group_id = aws_security_group.example.id
  type = "ingress"
  from_port = 0
  to_port = 65535
  protocol = "tcp"
  cidr_blocks = [join(",", aws_security_group.allow_all_sg.*.id)]
}
  1. merge: The merge function allows you to merge multiple maps into a single map. For example, you can use merge to merge multiple tags into a single map.
resource "aws_instance" "example" {
  ami = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = merge(
    {
      "Name" = "example-instance"
    },
    var.extra_tags
  )
}

List 20 of terraform functions command example on terraform console

Here are 20 examples of Terraform functions that you can try out in the Terraform console:

  1. abs(-5) – Returns the absolute value of a number.
  2. basename("path/to/file.txt") – Returns the basename of a file path.
  3. ceil(3.14159) – Returns the smallest integer greater than or equal to a number.
  4. coalesce(null, "default") – Returns the first non-null argument.
  5. compact(["a", "", "b", null]) – Returns a list with all empty and null values removed.
  6. element(["a", "b", "c"], 1) – Returns the element at a specific index of a list.
  7. file("path/to/file.txt") – Returns the contents of a file.
  8. format("Hello, %s!", "Terraform") – Returns a formatted string.
  9. index(["a", "b", "c"], "b") – Returns the index of an element in a list.
  10. join(", ", ["a", "b", "c"]) – Returns a string with the elements of a list joined together with a delimiter.
  11. jsonencode({"key": "value"}) – Returns a JSON-encoded string.
  12. length("hello") – Returns the length of a string.
  13. list("a", "b", "c") – Returns a list.
  14. lower("HELLO") – Returns a string with all characters in lowercase.
  15. map("key", "value") – Returns a map.
  16. merge({"a": 1}, {"b": 2}) – Returns a map with two maps merged together.
  17. range(1, 5) – Returns a list of numbers between two values.
  18. regex("hello", "^h") – Returns a boolean indicating whether a string matches a regular expression.
  19. reverse(["a", "b", "c"]) – Returns a list with the elements in reverse order.
  20. timeadd("2022-02-15T00:00:00Z", "24h") – Returns a string representing a time that is a specified duration after a given time.

You can try these functions out in the Terraform console by running terraform console in your terminal and typing in the function call. For example, to try out lower("HELLO"), you would type lower("HELLO") into the console and hit enter.

Example Program


variable "instance_count1" {
  type = number
  default = 1
}

variable "instance_count2" {
  type = number
  default = 2
}

resource "aws_instance" "web" {
  ami           = "ami-053b0d53c279acc90"
  instance_type = "t3.micro"
  count = sum([var.instance_count1,var.instance_count2])
  tags = {
    Name = "RajeshKumar"
  }
}

variable "plans" {
    type = map
    default = {
        "5USD"  = "1xCPU-1GB"
        "10USD" = "1xCPU-2GB"
        "20USD" = "2xCPU-4GB"
    }
}

variable "storage_sizes" {
    type = map
    default = {
        "1xCPU-1GB"  = "25"
        "1xCPU-2GB"  = "50"
        "2xCPU-4GB"  = "80"
    }
}

resource "aws_ebs_volume" "example" {
  availability_zone = "us-east-1a"       
  size              = lookup(var.storage_sizes, var.plans["5USD"])                

  tags = {
    Name = "example-ebs-volume"
  }
}


resource "aws_key_pair" "example" {
  key_name   = "examplekey"
  public_key = file("~/.ssh/terraform.pub")
}

resource "aws_instance" "example" {
  key_name      = aws_key_pair.example.key_name
  ami           = "ami-04590e7389a6e577c"
  instance_type = "t2.micro"

  connection {
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("rajesh.pem")
    host        = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }
}

Explanation of Terraform Commands and Invoked Functions

1. terraform apply (initial deploy)

Invoked Functions: Create(), Read()

  • Create(): This function is invoked to create new resources as specified in the Terraform configuration. During the initial deployment, all resources are created.
  • Read(): After creating the resources, Terraform reads the current state of the resources to ensure that they match the expected configuration. This function verifies that the resources have been created correctly.

2. terraform plan

Invoked Functions: Read()

  • Read(): This function reads the current state of the resources. During the terraform plan command, Terraform compares the current state with the desired state described in the configuration files. It then outputs the actions that would be taken to achieve the desired state.

3. terraform apply (update)

Invoked Functions: Read(), Update()

  • Read(): Terraform reads the current state of the resources to determine if there are any differences from the desired state specified in the configuration.
  • Update(): If there are any changes needed, the Update() function is invoked to modify the existing resources to match the new desired state.

4. terraform apply (force new update)

Invoked Functions: Read(), Delete(), Create()

  • Read(): Terraform reads the current state of the resources.
  • Delete(): In some cases, it may be necessary to destroy existing resources before recreating them. This function deletes the resources that need to be replaced.
  • Create(): After deleting the resources, the Create() function is invoked to create new resources as specified in the updated configuration.

5. terraform destroy

Invoked Functions: Delete()

  • Delete(): This function is invoked to destroy all the resources managed by Terraform. The terraform destroy command will remove all resources specified in the configuration.

Benefits of Understanding Invoked Functions

  1. Predictability: Understanding the functions invoked by Terraform commands helps predict what actions Terraform will take when managing your infrastructure.
  2. Debugging: Knowing which functions are invoked can help troubleshoot and debug issues when the desired state of the infrastructure is not achieved.
  3. Optimization: By understanding these functions, you can optimize your Terraform configurations and workflows to avoid unnecessary resource modifications and improve deployment efficiency.

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x