Interview Prep/Terraform/Resources Variables and Expressions

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.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions