Skip to content

Instantly share code, notes, and snippets.

@disaac
Forked from kerr-bighealth/config.tf
Created February 14, 2020 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disaac/961a3dfb5a77c621f310a9e21fdc1deb to your computer and use it in GitHub Desktop.
Save disaac/961a3dfb5a77c621f310a9e21fdc1deb to your computer and use it in GitHub Desktop.
iam-user module
terraform {
required_version = ">=0.12, <0.13"
}
locals {
# Flatten policy attachments to list(user:policy) as aws_iam_user_policy_attachment does not accept a policy list.
policy_attachments = flatten([
for username, value in var.users : [
for policy_arn in value["policy_attachments"] : {
username = username
policy_arn = policy_arn
}
]
])
}
resource "aws_iam_user" "this" {
for_each = var.users
name = each.key
path = each.value["path"]
force_destroy = each.value["force_destroy"]
permissions_boundary = each.value["permissions_boundary"]
tags = merge(each.value["tags"], { Provisioner : var.provisioner, EmailAddress : each.value["email_address"] })
}
resource "aws_iam_user_group_membership" "this" {
for_each = var.users
user = each.key
groups = each.value["group_memberships"]
depends_on = ["aws_iam_user.this"]
}
resource "aws_iam_user_policy_attachment" "this" {
for_each = {
for item in local.policy_attachments :
"${item.username} ${item.policy_arn}" => item
}
user = each.value.username
policy_arn = each.value.policy_arn
depends_on = ["aws_iam_user.this"]
}
output "users" {
description = "A nested map of user resources, with username as the key, and each value map containing the user's ARN and Unique ID."
value = {
for user, properties in aws_iam_user.this : user => {
arn : properties.arn
unique_id : properties.unique_id
}
}
}
variable "provisioner" {
description = "Value to use in Provisioner tags"
type = string
default = "Terraform"
}
variable "users" {
description = "A nested map of users and properties. The outer keys are usernames, and the inner properties map is documented in the User Properties section."
type = map(object({
path = string
force_destroy = bool
email_address = string
group_memberships = list(string)
permissions_boundary = string
policy_attachments = list(string)
tags = map(string)
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment