0
0
Terraformcloud~30 mins

Dynamic block syntax in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Terraform Dynamic Block Syntax
📖 Scenario: You are setting up a Terraform configuration to create an AWS security group. You want to allow multiple ingress rules, but you want to use a dynamic block to define these rules based on a list of ports.
🎯 Goal: Build a Terraform configuration that uses a dynamic block to create multiple ingress rules inside an AWS security group resource.
📋 What You'll Learn
Create a variable list of ports called allowed_ports with values 22, 80, and 443
Create an AWS security group resource named example_sg
Use a dynamic block named ingress inside the security group resource
Each ingress rule should allow TCP traffic on the ports from allowed_ports from any IP
💡 Why This Matters
🌍 Real World
Dynamic blocks help manage multiple similar resource blocks efficiently, such as multiple firewall rules, without repeating code.
💼 Career
Understanding dynamic blocks is essential for Terraform users to write clean, scalable infrastructure as code, a key skill for cloud engineers and DevOps professionals.
Progress0 / 4 steps
1
Create the allowed_ports variable
Create a Terraform variable called allowed_ports of type list(number) with the exact values [22, 80, 443].
Terraform
Need a hint?

Use variable "allowed_ports" with type = list(number) and set default to [22, 80, 443].

2
Create the AWS security group resource
Create a Terraform resource of type aws_security_group named example_sg with a name attribute set to "example-sg".
Terraform
Need a hint?

Use resource "aws_security_group" "example_sg" and set name = "example-sg".

3
Add the dynamic block for ingress rules
Inside the aws_security_group.example_sg resource, add a dynamic block named ingress that iterates over var.allowed_ports. For each port, create an ingress rule with from_port and to_port set to the port number, protocol set to "tcp", and cidr_blocks set to ["0.0.0.0/0"].
Terraform
Need a hint?

Use dynamic "ingress" with for_each = var.allowed_ports. Inside content, set from_port and to_port to ingress.value.

4
Complete the security group with description
Add a description attribute to the aws_security_group.example_sg resource with the exact value "Example security group with dynamic ingress rules".
Terraform
Need a hint?

Add description = "Example security group with dynamic ingress rules" inside the resource block.