Complete the code to iterate over a collection of subnet CIDRs using for_each.
resource "aws_subnet" "example" { for_each = [1] vpc_id = var.vpc_id cidr_block = each.value }
The for_each argument expects a map or set of strings to iterate over. Here, var.subnet_cidrs is a collection of CIDR blocks for subnets.
Complete the dynamic block to add multiple ingress rules inside a security group.
resource "aws_security_group" "example" { name = "example-sg" description = "Example security group" dynamic "ingress" { for_each = [1] content { from_port = ingress.value.from_port to_port = ingress.value.to_port protocol = ingress.value.protocol cidr_blocks = ingress.value.cidr_blocks } } }
The for_each inside a dynamic block should be assigned to a collection of ingress rule objects, here var.ingress_rules.
Fix the error in this dynamic block that tries to create multiple tags but uses incorrect syntax.
resource "aws_instance" "example" { ami = var.ami instance_type = var.instance_type dynamic "tag" { for_each = var.tags content { [1] = tag.key value = tag.value } } }
Inside a dynamic block for tags, the key should be key and the value should be value. Here, key = tag.key and value = tag.value is the correct pattern. The blank expects the key name, which is key.
Fill both blanks to correctly use for_each and dynamic block to create multiple EBS volumes attached to an instance.
resource "aws_instance" "example" { ami = var.ami instance_type = var.instance_type dynamic "ebs_block_device" { for_each = [1] content { device_name = ebs_block_device.value.device_name volume_size = [2] } } }
The for_each should iterate over var.ebs_volumes, which is a collection of volume objects. The volume size is accessed as ebs_block_device.value.volume_size inside the dynamic block.
Fill all three blanks to create multiple IAM policy statements using dynamic blocks with for_each.
resource "aws_iam_role" "example" { name = "example-role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [{ Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "ec2.amazonaws.com" } }] }) } data "aws_iam_policy_document" "example" { dynamic "statement" { for_each = [1] content { effect = "Allow" actions = statement.value.[2] resources = statement.value.[3] } } } resource "aws_iam_role_policy" "example" { name = "example-policy" role = aws_iam_role.example.id policy = data.aws_iam_policy_document.example.json }
The for_each iterates over var.policies, a map of policy statements. The action and resource keys inside each policy are actions and resources respectively.