Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

“Invest in yourself — your confidence is always worth it.”

Explore Cosmetic Hospitals

Start your journey today — compare options in one place.

Terraform Tutorials: Functions in terraform

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

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 a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at <a href="https://www.cotocus.com/">Cotocus</a>. I share tech blog at <a href="https://www.devopsschool.com/">DevOps School</a>, travel stories at <a href="https://www.holidaylandmark.com/">Holiday Landmark</a>, stock market tips at <a href="https://www.stocksmantra.in/">Stocks Mantra</a>, health and fitness guidance at <a href="https://www.mymedicplus.com/">My Medic Plus</a>, product reviews at <a href="https://www.truereviewnow.com/">TrueReviewNow</a> , and SEO strategies at <a href="https://www.wizbrand.com/">Wizbrand.</a> Do you want to learn <a href="https://www.quantumuting.com/">Quantum Computing</a>? <strong>Please find my social handles as below;</strong> <a href="https://www.rajeshkumar.xyz/">Rajesh Kumar Personal Website</a> <a href="https://www.youtube.com/TheDevOpsSchool">Rajesh Kumar at YOUTUBE</a> <a href="https://www.instagram.com/rajeshkumarin">Rajesh Kumar at INSTAGRAM</a> <a href="https://x.com/RajeshKumarIn">Rajesh Kumar at X</a> <a href="https://www.facebook.com/RajeshKumarLog">Rajesh Kumar at FACEBOOK</a> <a href="https://www.linkedin.com/in/rajeshkumarin/">Rajesh Kumar at LINKEDIN</a> <a href="https://www.wizbrand.com/rajeshkumar">Rajesh Kumar at WIZBRAND</a> <a href="https://www.rajeshkumar.xyz/dailylogs">Rajesh Kumar DailyLogs</a>

Related Posts

Terraform workspace explained!!!

What is Terraform workspace? Have you worked with terraform workflow? such as terraform init/plan/apply/destroy with terraform configuration file? If Yes, you already have worked with Terraform workspace….

Read More

Terraform Tutorials: Templating in Terraform

Top 10 Templating Engines Across Major Programming Languages # Templating Engine Programming Language Common Framework / Ecosystem Typical Real Use 1 Jinja2 Python Flask, Ansible HTML generation,…

Read More

Terraform provisioners Tutorials and Complete Guide

Terraform provisioners are used to execute scripts or shell commands on a local or remote machine as part of resource creation/deletion. They are similar to “EC2 instance…

Read More

Terraform Tutorials: Local Values using Local Block

What is local value in terraform? In Terraform, a locals block is used to define local variables within a module, allowing you to create reusable expressions and…

Read More

Terraform Tutorials: Module Complete Guide

A Terraform module is a collection of configuration files that encapsulate resources used together to achieve a specific outcome. Modules promote reusability, organization, and maintainability in infrastructure…

Read More

What is Terrafile?

Terrafile is a tool used to manage Terraform modules as dependencies. It simplifies the process of downloading and managing Terraform modules by automating the fetching of modules…

Read More