data "aws_organizations_organization" "main" {} locals { aws_account_ids = length(var.assume_role_account_names) > 0 ? { for info in data.aws_organizations_organization.main.accounts : info.name => info.id } : {} } resource "aws_iam_user" "main" { force_destroy = true name = var.name } resource "aws_iam_user_policy" "main" { name = var.name policy = jsonencode({ Statement = concat( length(var.assume_role_account_names) > 0 ? [ { # Assume roles in AWS sub-accounts Action = "sts:AssumeRole" Effect = "Allow" Resource = [for name in var.assume_role_account_names : format( "arn:aws:iam::%s:role/%s", local.aws_account_ids[name], var.name, ) ] } ] : [], [ { Action = [ # Manage the user's own IAM access key "iam:CreateAccessKey", "iam:DeleteAccessKey", "iam:UpdateAccessKey", # Read only access to the user's IAM object "iam:Get*", "iam:List*", ] Effect = "Allow" Resource = aws_iam_user.main.arn }, { Action = [ # Necessary for removing an IAM user "iam:ListVirtualMFADevices", # Describe and list the organization accounts "organizations:DescribeOrganization", "organizations:List*", ] Effect = "Allow" Resource = "*" }, ] ) Version = "2012-10-17" }) user = aws_iam_user.main.name } resource "aws_iam_access_key" "main" { user = aws_iam_user.main.name }