Interpolate variables in Terraform Script:
June 27, 2023 2023-06-28 1:12Interpolate variables in Terraform Script:
In Terraform, you can use variables within other variables by utilizing the variable interpolation syntax:
A ${ … }
Terraform official document says,
A ${ … } sequence is an interpolation, which evaluates the expression given between the markers, converts the result to a string if necessary, and then inserts it into the final string.
"cloudish, ${var.company_name}!"
The above script line the named object company_name variable value inserted into the string and you can get the result like cloudish soft!
Here’s more examples of how you can use Terraform variables within other variables:
variable "aws_region" {
type = string
default = "us-west-2"
}
variable "environment" {
type = string
default = "production"
}
variable "bucket_name" {
type = string
description = "The name of the bucket"
default = "cloudishsoft-data-${var.environment}-${var.region}"
}
resource "aws_s3_bucket" "s3_bucket" {
bucket = var.bucket_name
# ...
}
In the above example, there are three variables: region, environment, and bucket_name. The bucket_name variable is defined using variable interpolation, which references the values of the region and environment variables. The ${var.environment} and ${var.region} syntax allows you to access the values of other variables.
When you apply this configuration, Terraform will evaluate the variable expressions and populate the bucket_name variable with the concatenated string of cloudishsoft-data-production-us-west-2. The aws_s3_bucket resource will then use this interpolated value when creating the S3 bucket.
Note that variable interpolation can be used not only within variables but also within resource definitions, data blocks, and other parts of your Terraform configuration.