Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Terraform to maintain/manage IAM users

Terraform Version

Terraform v0.7.8 Terraform v0.7.11

Affected Resource(s)

  • aws_iam_user

Terraform Configuration Files

I am trying to use a list to manage IAM users:

variable "iam_user_list" { default = "aaa,bbb,ccc,ddd,eee,fff" }

resource "aws_iam_user" "iam_user" {
    count = "${length(split(",", var.iam_user_list))}"
    name = "${element(split(",", var.iam_user_list), count.index)}"
    force_destroy = true
}

output "user_list" {
  value = "VPC IAM Base Users: ${var.iam_user_list}"
}

When the AWS account is empty, users created as expected
When I delete the user from end of the list, i.e. fff, is deleted as expected. But when I delete the user in the middle of the list, i.e. bbb, there is an error:

Modifying...
  name: "bbb" => "ccc"
Error applying plan:

1 error(s) occurred:

* aws_iam_user.iam_user.1: Error updating IAM User bbb: EntityAlreadyExists: User with name ccc already exists.
    status code: 409, request id: ed0b4447-abf3-11e6-9b38-0fb23af37c82

Seems there is no user existence check in terraform aws_iam_user, what is the work around/ proper way to manage IAM users in terraform?

like image 682
user271785 Avatar asked Nov 16 '16 12:11

user271785


1 Answers

Thanks for the answer/suggestion from Martin Atkins in hashicorp-terraform Gitter room:

The issue discussed here is that when you use "count" with an array variable Terraform doesn't really "see" the relationships between the items in the array and the resources, so when a value is deleted from the middle of the list everything after that point is suddenly "off by one" and Terraform will want to replace them all.

This is the sort of use-case that would benefit from a first-class iteration feature in Terraform, but sadly we don't have that yet I would suggest that instead of trying to pass the user list in as variables, the most robust approach for now is to have a separate program that reads the user list from somewhere and writes out a .tf.json file containing a separate aws_iam_user block for each user. That way Terraform will understand which block belongs to which user because the local identifier can be the username or some sort of user id, allowing the correlation to be maintained.

like image 85
user271785 Avatar answered Oct 02 '22 09:10

user271785