How to use Terraform Dynamic blocks?
Terraform Dynamic Block is important when you want to create multiple resources inside of similar types, so instead of copy and pasting the same terraform configuration in the terraform file does not make sense and it is not feasible if you need to create hundreds of resources using terraform.
If we describe terraform dynamic block
in simple words then it is for loop
which is going to iterate over and will help you to create a dynamic resource. With the help of dynamic blocks
you can create nested repeatable blocks such as settings
, ingress
rules etc...
If this is the first time you are trying to learn to terraform then I would highly recommend reading my Getting started guide on Terraform -
In this post, we are going to see the examples and how to implement dynamic blocks.
Table of Content
- Syntax of Dynamic Block
- How to create your first terraform dynamic block
- Best practices for dynamic block
1. Syntax of Dynamic Block
As we said dynamic block
is more or less another way to implement for
loop. Here are few facts about dynamic block
which you should keep in mind -
- Collections - You need to have collections .e.g. -
list, map, set
- Iterator - To create a
dynamic block
you need to define an iterator. - Content - Content is something onto which you wanna iterate.
Here is the syntax of dynamic block
-
2. How to create your first terraform dynamic block
Before we implement our first terraform dynamic block let's first see an example without dynamic block.
In this example, we are going to create two ingress rules for the aws_security_group
. Both ingress rules are exactly the same apart from the port numbers .i.e. - 80 and 443. So if we do not use dynamic block then we need to create two ingress rules blocks inside the terraform file.
1resource "aws_security_group" "main" {
2 name = "resource_without_dynamic_block"
3 vpc_id = data.aws_vpc.main.id
4
5 ingress {
6 description = "ingress_rule_1"
7 from_port = 443
8 to_port = 443
9 protocol = "tcp"
10 cidr_blocks = ["0.0.0.0/0"]
11 }
12
13 ingress {
14 description = "ingress_rule_2"
15 from_port = 80
16 to_port = 80
17 protocol = "tcp"
18 cidr_blocks = ["0.0.0.0/0"]
19 }
20
21 tags = {
22 Name = "AWS security group non-dynamic block"
23 }
24}
The same terraform file can be improved by using dynamic block, now look at the following terraform file -
1locals {
2 ingress_rules = [{
3 port = 443
4 description = "Ingress rules for port 443"
5 },
6 {
7 port = 80
8 description = "Ingree rules for port 80"
9 }]
10}
11
12resource "aws_security_group" "main" {
13 name = "resource_with_dynamic_block"
14 vpc_id = data.aws_vpc.main.id
15
16 dynamic "ingress" {
17 for_each = local.ingress_rules
18
19 content {
20 description = ingress.value.description
21 from_port = ingress.value.port
22 to_port = ingress.value.port
23 protocol = "tcp"
24 cidr_blocks = ["0.0.0.0/0"]
25 }
26 }
27
28 tags = {
29 Name = "AWS security group dynamic block"
30 }
31}
Now you can imagine, if you need to define more than 2 ingress rules then using dynamic block can help you to reduce the line of code inside your terraform file.
Ingress rules are just an example but the same concept can be applied to another resource block.
3. Best practices for dynamic block
- Do not overuse the dynamic block when it is not necessary
- Multiple nested dynamic blocks should be avoided otherwise it might cause you trouble in debugging and troubleshooting.
- If the dynamic block is getting too complex inside your terraform file then it's better to use terraform module.
Read More - Terragrunt -
Posts in this Series
- Securing Sensitive Data in Terraform
- Boost Your AWS Security with Terraform : A Step-by-Step Guide
- How to Load Input Data from a File in Terraform?
- Can Terraform be used to provision on-premises infrastructure?
- Fixing the Terraform Error creating IAM Role. MalformedPolicyDocument Has prohibited field Resource
- In terraform how to handle null value with default value?
- Terraform use module output variables as inputs for another module?
- How to Reference a Resource Created by a Terraform Module?
- Understanding Terraform Escape Sequences
- How to fix private-dns-enabled cannot be set because there is already a conflicting DNS domain?
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Variables - Locals,Input,Output
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11