4
votes

When running the command terraform apply the following error occurred because the role already exists.

Error: Error creating IAM Role iam_for_lambda: EntityAlreadyExists: Role with name iam_for_lambda already exists.
    status code: 409, request id: 204c6c00-0b1d-4fb9-bf9c-fca48c67d669

  on main.tf line 1, in resource "aws_iam_role" "iam_for_lambda":
   1: resource "aws_iam_role" "iam_for_lambda" {

can I use conditions/tricks to check without error if the role already exists?

2
Ideally, you would create the IAM role that you need in this template so its life cycle is the same as the underlying stack. Or, if you need to support an existing role, then it would be an input parameter to the template and it would have a life cycle independent of the stack.jarmod
Are you trying to manage an IAM role that already exists?Matt Schuchard
@MattSchuchard yes, I should create IAM role if not exists, otherwise create them via terraform resourceLorenzo D'Isidoro
@LorenzoD'Isidoro you could import the resource to Terraform state, and them apply. More info in official docMauro Baraldi

2 Answers

1
votes

I'm guessing you worked this out yourself, since the question is a year old, but if the resource exists for legitimate reasons, you can have your code take ownership by importing it:

terraform import aws_iam_role.iam_for_lambda iam_for_lambda

Now, when you run Terraform, it will think it already created the resource, and if you update your code, the rolle gets the updates too.

That being said, you should probably not try to create a role that already exists. Even if you use terraform import to take ownership of the resource, you might get odd results if your code is modifying a role that is also owned by another module.

0
votes

Having the same question. If my build breaks but the role has been already created, I want a new build to not fail just because the role already exists. I mean it finds other resources in the tf state and it either skips or updates them. Why not role? I wonder if that's the answer - it just doesn't deal with it yet. Which is really annoying because I need to delete role manually before retriggering the build again.