I'm writing a terraform module which should be reused across different environments.
In order to make things simple, here's a basic example of calling a module from one of the environments root module:
##QA-resources.tf
module "some_module" {
source = "./path/to/module"
}
some_variable = ${module.some_module.some_output}
The problem is that when a module was already created Terraform throws an error of:
Error creating [resource-type] [resource-name]: EntityAlreadyExists: [resource-type] with [resource-name] already exists. status code: 409, request id: ...
This is happening when the module was created under the scope of external terraform.tfstate
and one of the resources has a unique field like 'Name'.
In my case, it happened while trying to use an IAM module which already created an role with that specific name, but it can happen in many other cases (I don't want the discussion to be specific to my use case).
I would expect that if one of the module's resources exist, no failure will occur and the module's outputs would be available to the root
module.
Any suggestions how to manage this (maybe using specific command or a flag)?
A few related threads I found:
Terraform doesn't reuse an AWS Role it just created and fails?
what is the best way to solve EntityAlreadyExists error in terraform?
Terraform error EntityAlreadyExists: Role with name iam_for_lambda already exists
Edit
For @Martin Atkins request here's the resource which caused the error.
It is a basic role for an AWS EKS cluster which have 2 policies attached (passed via var.policies
):
resource "aws_iam_role" "k8s_role" {
name = "k8s-role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "eks.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "role-policy-attach" {
role = "${aws_iam_role.k8s_role.name}"
count = "${length(var.policies)}"
policy_arn = "${element(var.policies, count.index)}"
}
This role was wrapped as a module and was passed to the root module.
The error mentioned above in blockquotes occurred because the role already exist while the root module tried to create it.