MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform Tutorials: Functions in terraform

Terraform console testing max, min, upper and lower functions, with an unterminated function call error

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 category of terraform Built-in Functions

Terraform docs listing built-in function categories, with abs examples under Numeric Functions

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"
}
Code language: JavaScript (javascript)
  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"
}
Code language: JavaScript (javascript)
  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)]
}
Code language: JavaScript (javascript)
  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
  )
}
Code language: JavaScript (javascript)

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"
  }
}Code language: JavaScript (javascript)

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"
  }
}

Code language: JavaScript (javascript)

resource "aws_key_pair" "example" {
  key_name   = "examplekey"
  public_key = file("~/.ssh/terraform.pub")
}Code language: JavaScript (javascript)

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"
    ]
  }
}Code language: PHP (php)

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Terraform Variable Example: Azure & AWS

This page shows how to declare and use Terraform input variables of type number, string, bool, list and map with AWS and Azure resources. Below the original…

Read More

Terraform dynamaic block details explaination with example

A Terraform dynamic block generates repeated nested blocks inside a resource, data source, provider or provisioner, such as ingress rules in a security group or rule blocks…

Read More

Terraform Error Handing with Try Catch

Terraform has no try { } catch { } block. Error handling in HCL uses the try() function, which returns the first of its arguments that evaluates…

Read More

Terraform: Example Code for Create Multiple Azure Linux Vms

This page shows how to create several Azure Linux virtual machines from one Terraform configuration by using the count meta-argument. The VMs sit behind a load balancer…

Read More

Terraform Tools for Developer Productivity Master Guide

Tools, Workflow, Security, Testing, CI/CD, Automation, AI Assistance, Governance, and Production Best Practices Verified baseline: 5 September 2026Audience: Terraform developers, DevOps/SRE, platform/cloud engineers, module authors, DevSecOps teams, and engineering…

Read More

Terraform Conditional Expressions and Logic: Complete Guide with Examples

Terraform Conditional Expressions and Logic — Summary Table # Concept Purpose Example Creates Resources? 1 Ternary operator Choose between two values var.env == “prod” ? “t3.large” :…

Read More