Expressions & Functions

terraform-learning Hands-on Terraform configs, modules, and practice projects on GitHub.

Terraform Expressions & Functions

An expression is something Terraform evaluates to produce a value.

Example:

instance_type = var.instance_type

Here:

var.instance_type

is an expression.


1. References

References are used to access values from variables, resources, locals, data sources, etc.

# Variable
var.instance_type

# Local
local.project_name

# Resource attribute
aws_instance.backend.public_ip

# Data source
data.aws_ami.ubuntu.id

# Module output
module.vpc.vpc_id

Example:

resource "aws_subnet" "public" {
  vpc_id = aws_vpc.main.id
}

Here:

aws_vpc.main.id
   │      │   │
   │      │   └── Attribute
   │      └────── Resource name
   └───────────── Resource type

2. String Interpolation

Used to combine variables/values with strings.

Syntax:

"${expression}"

Example:

locals {
  project = "taskify"
}

variable "environment" {
  default = "production"
}

resource "aws_s3_bucket" "uploads" {
  bucket = "${local.project}-${var.environment}-uploads"
}

Result:

taskify-production-uploads

Very commonly used for resource names and tags.

tags = {
  Name = "${var.environment}-backend"
}

3. Conditional Expression

Terraform supports ternary-style conditions.

Syntax:

condition ? true_value : false_value

Example:

instance_type = var.environment == "production"
  ? "t3.medium"
  : "t3.micro"

Meaning:

environment == production?
          │
     ┌────┴────┐
     │         │
    YES        NO
     │         │
     ▼         ▼
t3.medium   t3.micro

This is useful for environment-based configurations.


Most Useful Functions

You don’t need to memorize Terraform functions. These few are enough to start.

4. length()

Returns the number of items.

variable "zones" {
  default = [
    "ap-south-1a",
    "ap-south-1b"
  ]
}
length(var.zones)

Returns:

2

Common usage:

count = length(var.zones)

5. contains()

Checks whether a value exists in a collection.

contains(
  ["development", "staging", "production"],
  var.environment
)

Returns:

true / false

Commonly used for validation.


6. merge()

Combines maps.

Very useful for AWS tags.

locals {
  common_tags = {
    Project     = "taskify"
    Environment = "production"
  }
}

Then:

tags = merge(
  local.common_tags,
  {
    Name = "backend"
  }
)

Result:

{
  Project     = "taskify"
  Environment = "production"
  Name        = "backend"
}

7. file()

Reads content from a file.

For example:

terraform/
├── main.tf
└── scripts/
    └── startup.sh

Use:

resource "aws_instance" "backend" {
  ami           = "ami-123456"
  instance_type = "t3.micro"

  user_data = file("${path.module}/scripts/startup.sh")
}