Terrform provides a way of interpolating values using ${...}. We can use simple math functions, refer to other variables, or use conditional logic here. For example,
Variables: ${var.VARIABLE_NAME} refers to a variable.
Resources: ${type.resource-name.attr} refers to a resource declared.
Data source: ${data.type.resource-name.attr} refers to any rendered or dynamic data.
Usage of different variable types with interpolation
Name
Syntax
Example
Strings
var.name
${var.SOMETHING}
Maps
var.MAP["key"]
${var.AMIS["us-east-1"]}
${lookup(var.AMIS, var.AWS_REGION)}
Lists
var.LIST, var.LIST[i]
${var.subnets[i]}
${join(",", var.subnets)}
Usage of some other types of items with interpolation
Name
Syntax
Example
Output of a module
module.NAME.output
${module.aws_vpc.vpcid}
Count information
count.FIELD
When using the attribute count = number in a resource, we can use ${count.index}
Path information
path.TYPE
path.cwd(current directory)
path.module(module path)
path.root(root module path)
Meta information
terraform.FIELD
terraform.env shows active workspace
In addition to these, interpolation supports Add (+), Subtract (-), and Divide (/) for float types, and additionally Modulo (%) for integer types.
Conditionals
Interpolations may contain conditionals. The syntax looks like below for conditional statements.
Two important things to notice in here are that I use interpolation to name availability zones of the VPC, and that I introduce tag with the name Environment for future use.
Next let's create a file with the name securitygroup.tf,
resource "aws_security_group" "allow-ssh-prod" {
vpc_id = module.vpc-prod.vpc_id
name = "allow-ssh"
description = "security group that allows ssh and all egress traffic"
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "allow-ssh"
}
}
resource "aws_security_group" "allow-ssh-dev" {
vpc_id = module.vpc-dev.vpc_id
name = "allow-ssh"
description = "security group that allows ssh and all egress traffic"
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "allow-ssh"
}
}