I have Terraform with Workspaces. When I run Terraform my resources are created but when I change the Workspace then the errors below appear because the resources are already created:
Error: creating IAM Role: EntityAlreadyExists (role): Role with name env-role already exists.
Error: creating IAM Policy (policy): EntityAlreadyExists: A policy called env-with-policy already exists. Duplicate names are not allowed.
These are the resources:
resource "aws_iam_role" "payload_for_lambda" {
name = "${var.iam_role_name}"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
}
resource "aws_iam_policy" "AWSLambdaBasicExecutionRole" {
name = "${var.iam_policy_name}"
path = "/"
description = "AWS IAM Policy for managing aws lambda role"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*",
"Effect": "Allow"
}
]
}
EOF
}
I run both terraform init and terraform apply commands to apply the changes.
Is there a way Terraform to recognize the existing resources for my Workspaces and don’t try to create them every time?
Regards,
Ivo
2
Answers
The problem you have is that Terraform knows that the resources are unique (this is handled by the statefile) but you are using explicit names and this causes conflicts in AWS:
So the errors you are seeing come from AWS and not from Terraform.
You can add a resource like this:
First run terraform init
Then you can add this suffix to all resources that require a unique name:
Upon replanning, Terraform will see that the random string is already generated (it is in your statefile so it does not change).
Instead of using a random string, you can also use a prefix or suffix that you know is unique in the environment (ie. workspace-a, workspace-b).
This is an AWS error. You don’t show here but I guess you try to deploy both of you workspaces to the same AWS account. But due to that the AWS account already have resources named what you try to create with the second workspace it this fails.
See AWS docs here:
https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html#:~:text=RoleName,MyResource%22%20and%20%22myresource%22.