Taking advantage of Terraform’s dynamic blocks
Updated: Jul 15
When using Terraform to create and maintain our infrastructure, sometimes we need to define different block properties for our environments.
For example, let’s say we use the same module for creating AWS Cloudfront Distributions in our environments, but we only want to apply geographic restrictions to the production environment.
To solve this problem we can use Terraform dynamic blocks. In order to apply geographic restrictions to an aws_cloudfront_distribution resource we need to define a restrictions configuration block in the resource as the following:
restrictions {
geo_restriction {
restriction_type = "whitelist"
locations = ["US", "CA", "GB", "DE"]
}
}
If we wanted to apply this configuration only for the production environment we could do the following:
dynamic "restrictions" {
for_each = var.environment == "production" ? toset([1]) : toset([])
content {
geo_restriction {
restriction_type = "whitelist"
locations = ["US", "CA", "GB", "DE"]
}
}
}
On the first line we are going to use a foreach statement to create this block only if the environment variable is set to “production”. Inside the content block, we are going to define all the previous properties that were defined on the restrictions block.
With Terraform dynamic blocks we can customize our infrastructure creation and avoid creating
the same configuration blocks for resources in our different environments.
Happy coding and see you in the Cloud! :)
Juan Bermudez
Cloud Engineer
Teracloud
If you want to know more about Cloud Security, we suggest checking Streamlining Security with Amazon Security Hub: A where to start Step-by-Step Guide If you want to learn more about our TeraTips or our blog's content, we invite you to see all the content entries we have created for you and your needs.