Interpolation and Conditionals
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.
For example,
I will provision an EC2 instance in the example below.
First let's start creating a file with the name vars.tf
,
Then the provider.tf
,
Next let's create a file for out VPCs; vpc.tf
,
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
,
To keep out keys a file with the name key.tf
,
Finally, instance.tf
,
In here you can notice that I'm assigning subnet and security group ids based on the environment type.
Generate ssh keys,
Initialize the providers,
Apply the changes,
Don't forget to clean up once experiments are done,
Last updated
Was this helpful?