0
0
Terraformcloud~30 mins

Dynamic blocks in ingress rules in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic blocks in ingress rules
📖 Scenario: You are managing a cloud infrastructure using Terraform. You need to create a security group that allows multiple ingress rules. Instead of writing each rule manually, you want to use dynamic blocks to generate these rules from a list.
🎯 Goal: Build a Terraform configuration that uses a dynamic block inside a security group resource to create multiple ingress rules from a list of maps.
📋 What You'll Learn
Create a variable called ingress_rules with a list of maps containing from_port, to_port, protocol, and cidr_blocks.
Create a security group resource named example_sg.
Use a dynamic block named ingress inside the security group to generate ingress rules from var.ingress_rules.
Print the security group resource block with the dynamic ingress rules.
💡 Why This Matters
🌍 Real World
Cloud engineers often need to manage security groups with many ingress rules. Using dynamic blocks in Terraform helps automate and simplify this process.
💼 Career
Understanding dynamic blocks in Terraform is essential for infrastructure as code roles, enabling efficient and scalable cloud resource management.
Progress0 / 4 steps
1
Create the ingress rules variable
Create a Terraform variable called ingress_rules with the following list of maps exactly: { from_port = 80, to_port = 80, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"] } and { from_port = 443, to_port = 443, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"] }.
Terraform
Need a hint?

Use a variable block with type = list(object({ ... })) and set the default to the list of maps.

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

Use resource "aws_security_group" "example_sg" { ... } and set the name attribute.

3
Add dynamic ingress rules block
Inside the aws_security_group.example_sg resource, add a dynamic block named ingress that iterates over var.ingress_rules. Use for_each = var.ingress_rules and inside the block set from_port, to_port, protocol, and cidr_blocks using each.value.
Terraform
Need a hint?

Use dynamic "ingress" { for_each = var.ingress_rules content { ... } } and access values with ingress.value.

4
Output the security group resource
Add a Terraform output named security_group_id that outputs the ID of the aws_security_group.example_sg resource using value = aws_security_group.example_sg.id.
Terraform
Need a hint?

Use output "security_group_id" { value = aws_security_group.example_sg.id } to show the security group ID.