Creating AWS Security Groups with Dynamic Ingress Rules Using Terraform
Imesh Ruchira
Posted on January 10, 2024
What are Terraform Dynamic Blocks?
In Terraform, dynamic blocks provide a way to generate repetitive configurations dynamically. They are used in resource, data, and provider blocks to handle situations where you need to define multiple nested blocks with similar configurations.
The dynamic block allows you to generate multiple instances of a nested block within a resource or module, based on a list or map variable. This can help you reduce code duplication and make your Terraform configurations more concise and maintainable.
How to Use the Dynamic Blocks
Terraform provides the dynamic block to create repeatable nested blocks within a resource. A dynamic block is similar to the for expression. Where for creates repeatable resources, like Security group rules, dynamic creates nested blocks within a resource, like ports within a security group. A dynamic block iterates over a child resource and generates a nested block for each element of that resource.
Example
The following code shows the configuration of an AWS security group and four open ports. In this example, the ports blocks are written out explicitly, creating repeated code.
provider "aws" {
region = "us-east-1"
}
resource "aws_security_group" "example_sg" {
name = "example-sg"
description = "Example Security Group"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
That same configuration using a dynamic block is shown below. Replacing the four port blocks with a dynamic block removes repeated attributes, leading to cleaner code that is easier to maintain.
provider "aws" {
region = "us-east-1"
}
resource "aws_security_group" "example_sg" {
name = "example-sg"
description = "Example Security Group"
dynamic "ingress" {
for_each = [80, 443, 8080, 8000]
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
The for_each expression in Terraform is a powerful feature that enables the dynamic generation of multiple resources. in this case,
The for_each expression is used to open multiple ports of a security group or configuration block based on the elements of a given collection. It is commonly used to iterate over lists, sets, or maps and create individual ports for each element.
Got a project that needs some Terraform love? I've got you covered! Check out my Terraform configuration at this link:https://github.com/98ruchira/Terraform-AWS-Security-group-with-Dynamic-block/tree/main
Posted on January 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.