Expressions and Interpolation

Expressions compute values; interpolation embeds them inside strings with the dollar-brace syntax.

Syntax"${var.project}-${var.environment}"

Expressions compute values in Terraform — references, arithmetic, function calls, and more. You use them anywhere a value is expected.

String interpolation

Embed an expression inside a string with ${ ... }. Terraform evaluates it and inserts the result.

References

Common reference forms include var.name, local.name, aws_instance.web.id, and data.aws_ami.latest.id.

Example

Example · hcl
locals {
  bucket_name = "${var.project}-${var.environment}-assets"
  instance_count = 2 + 1
}

resource "aws_s3_bucket" "assets" {
  bucket = local.bucket_name
}

When to use it

  • An engineer builds an S3 bucket name dynamically by interpolating the project name, environment, and account ID into a single string expression.
  • A team uses a reference expression (aws_vpc.main.id) in a subnet block to link resources without hard-coding any IDs.
  • A module uses an expression that evaluates a function call like length(var.subnets) to derive a capacity count rather than accepting a separate variable.

More examples

String interpolation expression

Embeds two variables into a string using ${...} interpolation to build a consistent, parameterized bucket name.

Example · hcl
variable "project" { default = "myapp" }
variable "env"     { default = "prod" }

locals {
  bucket_name = "${var.project}-${var.env}-assets"
}

resource "aws_s3_bucket" "assets" {
  bucket = local.bucket_name
}

Attribute reference expression

Uses a resource reference expression (resource_type.name.attribute) to pass the VPC's id to the internet gateway block.

Example · hcl
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_internet_gateway" "gw" {
  # Reference another resource's attribute directly
  vpc_id = aws_vpc.main.id
}

Complex expression with function

Combines the length() function with arithmetic in an expression to derive max_size from the number of availability zones.

Example · hcl
variable "availability_zones" {
  type    = list(string)
  default = ["us-east-1a", "us-east-1b", "us-east-1c"]
}

resource "aws_autoscaling_group" "app" {
  min_size           = 1
  max_size           = length(var.availability_zones) * 2
  availability_zones = var.availability_zones
}

Discussion

  • Be the first to comment on this lesson.