A YAML file lists 40 IAM users with groups. How do you create users and memberships without hand-writing 40 blocks?
IntermediateScenarioResources Variables and Expressions
Answer
Situation read → Data-driven infrastructure from a file.
What I'd do →
locals {
users = yamldecode(file("${path.module}/users.yaml")) # list of {name, groups}
memberships = flatten([
for u in local.users : [for g in u.groups : { user = u.name, group = g }]
])
}
resource "aws_iam_user" "this" {
for_each = { for u in local.users : u.name => u }
name = each.key
}
resource "aws_iam_user_group_membership" "this" {
for_each = { for m in local.memberships : "${m.user}/${m.group}" => m }
user = aws_iam_user.this[each.value.user].name
groups = [each.value.group]
}
Why → Onboarding becomes a one-line YAML PR, reviewed and audited like code.
Interview tip → Validate the YAML with a variable validation or precondition so typos fail early.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced