Document

SUBSCRIBE TO GET FULL ACCESS TO THE E-BOOKS FOR FREE 🎁SUBSCRIBE NOW

Professional Dropdown with Icon

SUBSCRIBE NOW TO GET FREE ACCESS TO EBOOKS

Terraform – dynamic blocks

 
 
 

Dynamic Blocks are more or less another way to implement for a loop. Here are a few facts  dynamic block which you should keep in mind –

  1. Collections – You need to have collections .e.g. – list, map, set
  2. Iterator – To create a dynamic block you need to define an iterator.
  3. 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.

provider “aws” {
  region =“us-east-1”
}
//security
resource “aws_security_group” “sg1” {

 ingress {
      description = “ingress_rule_1”
      from_port   = 443
      to_port     = 443
      protocol    = “tcp”
      cidr_blocks = [“0.0.0.0/0”]
   }
   
   ingress {
      description = “ingress_rule_2”
      from_port   = 80
      to_port     = 80
      protocol    = “tcp”
      cidr_blocks = [“0.0.0.0/0”]
   }
   tags = {
     “Name” = “Static Inbound Rule”
   }
}


 
The same terraform file can be improved by using dynamic block, now look at the following terraform file –
provider “aws” {
  region =“us-east-1”
}
//locals
locals {
   ingress_rules = [{
      port        = 443
      description = “Ingress rules for port 443”
   },
   {
      port        = 80
      description = “Ingree rules for port 80”
   }]
}
//security
resource “aws_security_group” “sg1” {
dynamic “ingress” {
      for_each = local.ingress_rules

      content {
         description = ingress.value.description
         from_port   = ingress.value.port
         to_port     = ingress.value.port
         protocol    = “tcp”
         cidr_blocks = [“0.0.0.0/0”]
      }
   }
   tags = {
     “Name” = “Dynamic Inbound Rule”
   }
}


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.
Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *