0
0
Terraformcloud~30 mins

Dynamic blocks in security groups in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic blocks in security groups
📖 Scenario: You are setting up a cloud network security group to control access to your servers. You want to allow multiple ports for incoming traffic, but the list of ports might change. Using dynamic blocks in Terraform helps you manage this easily.
🎯 Goal: Create a Terraform configuration for an AWS security group that uses a dynamic block to add multiple ingress rules for specified ports.
📋 What You'll Learn
Create a variable with a list of ports
Define an AWS security group resource
Use a dynamic block to add ingress rules for each port in the list
Set the protocol to TCP and allow traffic from anywhere (0.0.0.0/0)
💡 Why This Matters
🌍 Real World
Managing security groups with dynamic blocks helps automate and simplify cloud network security configurations, especially when the allowed ports change frequently.
💼 Career
Cloud engineers and DevOps professionals often use Terraform dynamic blocks to write clean, scalable infrastructure code for security groups and other resources.
Progress0 / 4 steps
1
Create a variable with a list of ports
Create a Terraform variable called allowed_ports with the list [22, 80, 443].
Terraform
Need a hint?

Use variable "allowed_ports" and set default to the list of ports.

2
Define an AWS security group resource
Define a resource called aws_security_group named example with name = "example-sg" and description = "Example security group".
Terraform
Need a hint?

Use resource "aws_security_group" "example" and set name and description.

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

Use dynamic "ingress" with for_each = var.allowed_ports and set the block content accordingly.

4
Add an egress rule to allow all outbound traffic
Inside the aws_security_group.example resource, add an egress block that allows all outbound traffic by setting from_port and to_port to 0, protocol to "-1", and cidr_blocks to ["0.0.0.0/0"].
Terraform
Need a hint?

Add an egress block with the specified settings to allow all outbound traffic.