MANGESH PATIL
MANGESH PATIL

Reputation: 1

terraform code for creating bulk IAM Users and attaching multiple user policy to the same

My goal is to create multiple IAM users and also attach multiple policies to each user in a single piece of code but I am not able to achieve this.

Could you please help me with the code.

Below is the code I am trying to run but it is failing.

resource "aws_iam_user" "example" {
  count = "${length(var.aws_iam_user)}"
  name = "${element(var.aws_iam_user,count.index )}"
}

resource "aws_iam_user_policy_attachment" "user-policy-attachment" {
  aws_iam_user       = "${var.aws_iam_user}"
  count      = "${length(var.iam_policy_arn)}"
  policy_arn = "${var.iam_policy_arn[count.index]}"
}

Can anyone please help me with the correct code to achieve this task? In the code we should be able to create bulk users and also attach policy to each user. The policy can be the same or different for each user.

Upvotes: 0

Views: 1540

Answers (1)

Erico
Erico

Reputation: 1461

If you're using terraform 0.12 or newer you can use for_each to interact over a map and generate a map, if you use count and delete a user, all users defined after that position will be recreated.

Here is a quick example.

terraform.tfvars

users = [
   "user1": [ "policy1ARN", "policy3ARN" ]
   "user2": [ "policy1ARN" ],
   "user3": [ "police2ARN" ]
]

example.tf

resource "aws_iam_user" "list" {
  for_each      = var.users
  name          = each.key
  force_destroy = true
}

resource "aws_iam_user_policy_attachment" "list" {
  for_each   = var.users
  user       = aws_iam_user[each.key].name
  policy_arn = each.value
}

Just an example to show how to use for_each based on how you want to implement, but as a best practice, it's better if you create IAM groups with their respective policies and instead of attaching policies to each user, you add users to groups.

Upvotes: 1

Related Questions