Create multiple IAM users from a list with `for_each`, and output their ARNs as a map.
BeginnerHands-onWrite-Terraform tasks
Answer
variable "users" {
type = set(string)
default = ["alice", "bob", "carol"]
}
resource "aws_iam_user" "this" {
for_each = var.users
name = each.value
}
output "user_arns" {
value = { for name, u in aws_iam_user.this : name => u.arn }
}
Key trick → for_each over a set keys each resource by name (aws_iam_user.this["bob"]), so removing "alice" deletes only alice. With count, bob and carol would shift index and be recreated.
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.BeginnerWrite Terraform that looks up an existing VPC by tag instead of hardcoding its ID.Intermediate