Write a dynamic block that creates ingress rules from a variable list.
IntermediateHands-onWrite-Terraform tasks
Answer
variable "ingress" {
type = list(object({ port = number, cidr = string, desc = string }))
default = [
{ port = 80, cidr = "0.0.0.0/0", desc = "http" },
{ port = 443, cidr = "0.0.0.0/0", desc = "https" },
{ port = 22, cidr = "10.0.0.0/8", desc = "ssh internal" },
]
}
resource "aws_security_group" "app" {
name = "app"
vpc_id = var.vpc_id
dynamic "ingress" {
for_each = var.ingress
content {
description = ingress.value.desc
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = [ingress.value.cidr]
}
}
}
Key trick → Inside content, the iterator is named after the block (ingress.value). Use dynamic blocks sparingly, because they hurt readability.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a VPC with public and private subnets across 3 AZs using `count` or `for_each`.IntermediateWrite a reusable module for an EC2 instance with inputs, outputs and validation.AdvancedWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.Beginner