Created
July 13, 2022 15:35
-
-
Save sergsoares/4fd688bc848eee7a43a38ca4c6987aff to your computer and use it in GitHub Desktop.
Generate dynamically policies based on input and attach for already created roles and users
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
locals { | |
policies_arns = { | |
for item in aws_iam_policy.policy : | |
item.name => item.arn | |
} | |
users_attachment = distinct( | |
flatten([ | |
for item in var.policies : [ | |
for user in item.users_to_attach : { | |
policy_name = item.policy_name | |
name = user | |
} | |
] | |
])) | |
roles_attachment = distinct( | |
flatten([ | |
for item in var.policies : [ | |
for role in item.roles_to_attach : { | |
policy_name = item.policy_name | |
name = role | |
} | |
] | |
])) | |
} | |
output "name" { | |
value = local.users_attachment | |
} | |
# Data block used for validate users names during plan phase. | |
data "aws_iam_user" "validate" { | |
count = length(local.users_attachment) | |
user_name = local.users_attachment[count.index]["name"] | |
} | |
# Data block used for validate role names during plan phase. | |
data "aws_iam_role" "validate" { | |
count = length(local.roles_attachment) | |
name = local.roles_attachment[count.index]["name"] | |
} | |
resource "aws_iam_policy" "policy" { | |
count = length(var.policies) | |
name = var.policies[count.index]["policy_name"] | |
policy = jsonencode(var.policies[count.index]["content"]) | |
} | |
resource "aws_iam_user_policy_attachment" "attach_users" { | |
depends_on = [ | |
local.policies_arns, | |
local.users_attachment | |
] | |
count = length(local.users_attachment) | |
user = local.users_attachment[count.index]["name"] | |
policy_arn = local.policies_arns[local.users_attachment[count.index]["policy_name"]] | |
} | |
resource "aws_iam_role_policy_attachment" "attach_roles" { | |
depends_on = [ | |
local.policies_arns, | |
local.roles_attachment | |
] | |
count = length(local.roles_attachment) | |
role = local.roles_attachment[count.index]["name"] | |
policy_arn = local.policies_arns[local.roles_attachment[count.index]["policy_name"]] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment