IAM "EntityAlreadyExists: Role With Name Already Exists": The Fix for Terraform, CloudFormation, CDK and the CLI, and Why Changing the Capital Letters Doesn't Help
"EntityAlreadyExists: Role with name app-role already exists" means your AWS account already has an IAM role, user, group, policy or instance profile with that name, so IAM refused to create a second one (HTTP 409). Nothing is broken. You have three ways out: reuse the existing one, import it into Terraform, CloudFormation or CDK so your code owns it, or delete it if nothing uses it. Two surprises catch almost everyone. First, IAM names belong to the whole account, not to a Region, so the same role name in a second Region, a second stack or a second environment collides. Second, IAM names aren't case-sensitive: if app-role exists, you can't create App-Role either, so "just change the capital letter" doesn't work. This page shows how to find what's already there and who made it, then the exact fix for the AWS CLI, Python, Terraform, CloudFormation and CDK, plus the leftover instance profile that causes the same error after you've deleted a role.
Ethan, a developer, runs the small AWS setup behind his friend Jake's phone repair shop. Weeks ago, to test something quickly, he made an EC2 role called app-role in the console. Then he did things properly and wrote it in Terraform. The first terraform apply stopped with a 409. He renamed the role in his code to App-Role, and got the same error. That second failure is the one that sent him looking for answers.
New to IAM? It's the part of AWS that decides who and what can do things in your account. A role is a set of permissions that a service, such as an EC2 server or a Lambda function, can take on. Our guides to IAM and IAM policies cover the basics.
What "EntityAlreadyExists" means
IAM sends this error, with HTTP status 409, whenever a create call asks for a name that's already taken. The AWS CLI shows it like this:
An error occurred (EntityAlreadyExists) when calling the CreateRole operation: Role with name app-role already exists.
Terraform adds the operation and status code around the same message:
Error: creating IAM Role (app-role): operation error IAM: CreateRole, https response error StatusCode: 409, RequestID: ..., EntityAlreadyExists: Role with name app-role already exists.
It isn't only roles. The same rule covers five kinds of IAM name, and each create call can hit it:
| What you're creating | Create call | See what's already there |
|---|---|---|
| Role | CreateRole | aws iam get-role --role-name NAME |
| User | CreateUser | aws iam get-user --user-name NAME |
| Group | CreateGroup | aws iam get-group --group-name NAME |
| Customer managed policy | CreatePolicy | aws iam list-policies --scope Local |
| Instance profile | CreateInstanceProfile | aws iam get-instance-profile --instance-profile-name NAME |
Two rules behind most of these errors
- Names are unique per account, not per Region. IAM resources are global, which is why the Region part of an IAM ARN is always blank (
arn:aws:iam::111122223333:role/app-role). Deploy the same template with a fixed role name tous-east-1and theneu-west-1, and the second one fails. - Names aren't distinguished by case.
app-role,App-RoleandAPP-ROLEare the same name as far as uniqueness goes. You can't create both.
Jake: "So changing the A to a capital didn't make it a new name?"
Ethan: "Not to IAM. To IAM, it's the same name with a different hat on."
Find the existing one, and who made it
Before you change anything, look at what's there. This shows the role's ARN, when it was created and when it was last used:
aws iam get-role --role-name app-role --query "Role.{Arn:Arn,Created:CreateDate,LastUsed:RoleLastUsed}" --output json
If LastUsed is empty, the role hasn't been used in the tracking period, which is the last 400 days. A role that's been used yesterday belongs to something running, and deleting it would break that thing.
Because names ignore case, an exact get-role for App-Role can come back empty when app-role exists. To find every spelling, list all role names and search without case:
aws iam list-roles --query "Roles[].RoleName" --output text | tr '\t' '\n' | grep -i '^app-role$'
On Windows PowerShell, the same search is (aws iam list-roles --query "Roles[].RoleName" --output json | ConvertFrom-Json) -match '^app-role$'; PowerShell's -match already ignores case.
Then find out whether a CloudFormation stack owns it. For an IAM role, the physical resource ID is the role name:
aws cloudformation describe-stack-resources --physical-resource-id app-role --query "StackResources[].{Stack:StackName,Logical:LogicalResourceId,Status:ResourceStatus}"
If it names a stack, that stack created the role, and you should change it there, not by hand. Run it in each Region you deploy stacks to. If none of them names a stack, the role was made by hand, by a script, or by a tool that has since lost track of it.
Why it happens: the usual causes
| What happened | What it looks like | Best fix |
|---|---|---|
| You made it by hand first, in the console or the CLI | Your first Terraform or stack deploy fails | Import it |
| Your tool lost track: a deleted or new Terraform state file, a new backend, a new workspace | Code that worked before suddenly fails | Import it back into state |
A stack was deleted with DeletionPolicy: Retain, or the delete failed partway | Redeploying a deleted stack fails | Import into the new stack, or delete the orphan |
| The same fixed name in a second Region, stack or environment | The first deploy works; the second fails | Stop hard-coding names, or put the Region and environment in them |
| A name that differs only in capital letters | "But mine is spelled differently" | Pick a genuinely different name, or reuse the existing role |
| A leftover instance profile after deleting a role with the CLI | CreateInstanceProfile fails, though the role is gone | Delete the instance profile |
| A script that creates without checking | The second run fails | Check first, or catch the error |
Reuse it, import it, or delete it?
Your answer depends on what the existing role is doing:
- It's in use (recent
LastUsed) and you want your code to manage it: import it. Your Terraform, stack or CDK app takes it over without the role ever disappearing. - It's in use and something else should keep managing it: reference it instead of creating it. In Terraform, use a
data "aws_iam_role"lookup; in CDK,Role.fromRoleName; in CloudFormation, pass its ARN in as a parameter. - It's an abandoned leftover (empty
LastUsed, no stack owns it, nobody recognizes it): delete it properly, then create it again from code.
Importing is almost always the safer first choice. Deleting a role that a running service uses breaks that service at once, and anything that pointed at the old role's unique ID won't simply reconnect to a new role with the same name.
AWS CLI and Python: make your scripts safe to re-run
A deploy script that always calls create-role fails the second time it runs. Check first:
#!/bin/bash
set -euo pipefail
ROLE=app-role
if aws iam get-role --role-name "$ROLE" >/dev/null 2>&1; then
echo "Role $ROLE already exists, reusing it"
else
aws iam create-role --role-name "$ROLE" \
--assume-role-policy-document file://trust-ec2.json >/dev/null
echo "Created role $ROLE"
fi
The trust policy file, trust-ec2.json, says which service may use the role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ec2.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
In Python, boto3 raises a specific exception you can catch, which avoids a second API call when the role is new:
import json
import boto3
iam = boto3.client("iam")
TRUST = {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole"}],
}
def ensure_role(name):
try:
role = iam.create_role(RoleName=name, AssumeRolePolicyDocument=json.dumps(TRUST))["Role"]
print(f"Created {role['Arn']}")
except iam.exceptions.EntityAlreadyExistsException:
role = iam.get_role(RoleName=name)["Role"]
print(f"Already there, reusing {role['Arn']}")
return role
ensure_role("app-role")
ensure_role("batch-role")
One caution with both: reusing the existing role keeps its trust policy and permissions, not the ones in your script. If those need to match, update them after the check.
Terraform "EntityAlreadyExists": import the role
Here's the role Ethan wrote, the one whose first apply failed:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_iam_role" "app" {
name = "app-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "ec2.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
}
Terraform tried to create app-role because its state file had no record of it. The fix is to tell Terraform the role already exists. With Terraform 1.5 or later, add an import block, in its own file such as imports.tf; for an IAM role, the ID is the role name:
import {
to = aws_iam_role.app
id = "app-role"
}
Then work through it in order:
- Run
terraform plan. It should say the role will be imported, not created. - Read any changes listed with the import: they're differences between the real role and your code.
- Run
terraform apply. - Run
terraform planagain and look for "No changes."
The plan shows an import, not a create:
Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
Run terraform plan once more. If it says "No changes," your code matches the real role. If it shows changes, the hand-made role differs from your code, for example a different trust policy; read them before applying, because applying makes the real role match your code. You can delete the import block afterwards or leave it; it does nothing once the role is in state.
On older Terraform, or for a one-off, the command-line version does the same job:
terraform import aws_iam_role.app app-role
Other IAM types import the same way, by name for users, groups and instance profiles and by ARN for policies: aws_iam_user, aws_iam_group, aws_iam_instance_profile and aws_iam_policy.
Stop it happening again: let Terraform pick the name
If nothing outside Terraform needs to know the exact name, use name_prefix instead of name. Terraform adds a unique suffix, so two environments, two Regions or a rebuilt state never fight over one name:
resource "aws_iam_role" "worker" {
name_prefix = "worker-"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "ec2.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
}
output "role_name" {
value = aws_iam_role.worker.name
}
The output then shows a name such as worker-93f10a839dfd0ff8bcea7d6ddb.
Jake: "So the import doesn't change the role, it just tells Terraform it's already there."
Ethan: "Exactly. Like adding a phone you already own to the shop's inventory sheet instead of buying another one."
CloudFormation and CDK: import, reference, or drop the name
CloudFormation hits this error when a template gives a role a fixed RoleName that's already taken. You have three choices.
1. Let CloudFormation import it automatically
When you create a new stack from a template that names the role, add --import-existing-resources, and CloudFormation adopts the existing role instead of failing. It works only when the name is written out in the template (not built with !Ref or !Sub), the resource has a DeletionPolicy of Retain or RetainExceptOnCreate, and the role doesn't already belong to another stack.
AWSTemplateFormatVersion: "2010-09-09"
Resources:
AppRole:
Type: AWS::IAM::Role
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
RoleName: app-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
aws cloudformation create-change-set --stack-name app-stack --change-set-name adopt-app-role \
--change-set-type CREATE --template-body file://import-role.yaml \
--capabilities CAPABILITY_NAMED_IAM --import-existing-resources
UpdateReplacePolicy: Retain isn't required for the import, but pair it with DeletionPolicy: together they keep the role safe both when the stack is deleted and when an update would replace it. Because the role has a custom name, the stack needs CAPABILITY_NAMED_IAM; our CAPABILITY_NAMED_IAM guide explains why.
2. Import it with an IMPORT change set
For an existing stack, or when you want to control exactly what's adopted, name the role in --resources-to-import. The identifier for an IAM role is its RoleName, and the JSON must be written inline as JSON, not YAML:
aws cloudformation create-change-set --stack-name app-stack --change-set-name import-app-role \
--change-set-type IMPORT --template-body file://import-role.yaml \
--capabilities CAPABILITY_NAMED_IAM \
--resources-to-import '[{"ResourceType":"AWS::IAM::Role","LogicalResourceId":"AppRole","ResourceIdentifier":{"RoleName":"app-role"}}]'
Review the change set, then run it with aws cloudformation execute-change-set --stack-name app-stack --change-set-name import-app-role. Our CloudFormation "already exists" guide walks through every import route, drift checks after the import, and the hard cases.
3. Drop the fixed name
If nothing outside the stack needs the exact name, remove RoleName altogether. CloudFormation then generates a unique ID and uses it as the role's name, so the template deploys to any Region or account any number of times, and plain CAPABILITY_IAM is enough.
CDK: reference the role that's already there
AWS CDK deploys through CloudFormation, so the same rules apply. To use an existing role instead of creating one, look it up by name. With mutable: false, CDK won't try to attach extra policies to a role it doesn't own:
import { App, Stack } from "aws-cdk-lib";
import * as iam from "aws-cdk-lib/aws-iam";
import * as lambda from "aws-cdk-lib/aws-lambda";
const app = new App();
const stack = new Stack(app, "AppStack");
const appRole = iam.Role.fromRoleName(stack, "AppRole", "app-role", { mutable: false });
new lambda.Function(stack, "Worker", {
runtime: lambda.Runtime.NODEJS_22_X,
handler: "index.handler",
code: lambda.Code.fromInline("exports.handler = async () => 'ok';"),
role: appRole,
});
app.synth();
The synthesized template contains only the Lambda function, pointing at arn:aws:iam::ACCOUNT:role/app-role; no AWS::IAM::Role is created, so there's nothing to collide. If your CDK code creates the role with a fixed roleName, removing that property has the same effect as dropping RoleName in a template.
Deleted the role and still get the error? The leftover instance profile
EC2 doesn't attach a role directly; it attaches an instance profile, a small container that holds the role. When you create an EC2 role in the console, the console quietly creates an instance profile with the same name. Deleting the role in the console removes both. Deleting it with the CLI or an SDK doesn't: you have to take the role out of the profile first, and the profile stays behind afterwards. Our instance profile guide explains the pair in detail.
That's how you end up with this, after the role is long gone:
An error occurred (EntityAlreadyExists) when calling the CreateInstanceProfile operation: Instance Profile app-role already exists.
Check whether the profile is empty, then delete it if nothing uses it:
aws iam get-instance-profile --instance-profile-name app-role --query "InstanceProfile.{Name:InstanceProfileName,Roles:Roles}" --output json
aws iam delete-instance-profile --instance-profile-name app-role
Or, if your code should own the old profile, import it like the role: in Terraform, the resource is aws_iam_instance_profile and the import ID is the profile name.
Delete an IAM role safely, in the right order
If the role really is an abandoned leftover, delete it fully. IAM refuses to delete a role that still has policies or instance profiles attached, with an error such as:
An error occurred (DeleteConflict) when calling the DeleteRole operation: Cannot delete entity, must remove roles from instance profile first.
This script does the steps in the order IAM needs: out of every instance profile, inline policies deleted, managed policies detached, then the role itself. Run it as bash delete-role.sh app-role:
#!/bin/bash
set -euo pipefail
ROLE=$1
for ip in $(aws iam list-instance-profiles-for-role --role-name "$ROLE" --query "InstanceProfiles[].InstanceProfileName" --output text); do
aws iam remove-role-from-instance-profile --instance-profile-name "$ip" --role-name "$ROLE"
echo "Removed from instance profile $ip"
done
for p in $(aws iam list-role-policies --role-name "$ROLE" --query "PolicyNames" --output text); do
aws iam delete-role-policy --role-name "$ROLE" --policy-name "$p"
echo "Deleted inline policy $p"
done
for arn in $(aws iam list-attached-role-policies --role-name "$ROLE" --query "AttachedPolicies[].PolicyArn" --output text); do
aws iam detach-role-policy --role-name "$ROLE" --policy-arn "$arn"
echo "Detached $arn"
done
aws iam delete-role --role-name "$ROLE"
echo "Deleted role $ROLE"
Before you run it, check RoleLastUsed one more time. Afterwards, delete the now-empty instance profile with aws iam delete-instance-profile if you won't reuse it, or the next CreateInstanceProfile fails as above. Your own permissions matter too: if you see "not authorized" instead, our iam:CreateRole permissions guide covers what your user needs.
Jake: "So deleting a role is like closing an account: you clear everything attached to it first."
Ethan: "Right, and you check nobody's still using it before you close it."
Keep it from happening again
- Don't hard-code names you don't need. Let CloudFormation generate them, or use
name_prefixin Terraform. - When you do need a fixed name, make it specific. Put the environment and Region in it, such as
app-role-prod-use1, so a second copy of the same code doesn't collide. - Give every role one owner. If Terraform manages it, don't also create or edit it in the console.
- Keep your Terraform state safe. A lost or reset state file is what turns "already exists" into a surprise; store it in a shared backend.
- Make scripts check first. A
get-rolebefore everycreate-rolecosts one API call and saves a failed run.
Troubleshooting by symptom
Terraform apply fails with EntityAlreadyExists on the first run
The role was made outside Terraform. Add an import block for it (id = the role name), run terraform plan to check, then apply.
It worked in one Region and fails in another
IAM is global, so the same role name from the same template collides. Remove the fixed name, or include the Region in it.
I changed the name's capital letters and it still fails
IAM names aren't case-sensitive for uniqueness. Choose a genuinely different name, or reuse the existing role.
The role is deleted but CreateInstanceProfile still fails
Deleting a role with the CLI leaves its instance profile behind. Check it with get-instance-profile, then delete-instance-profile.
delete-role fails with DeleteConflict
The role still has instance profiles or policies attached. Remove it from instance profiles, delete inline policies and detach managed policies first.
A redeployed CloudFormation stack fails on a role
The old stack probably kept the role with DeletionPolicy Retain. Import it with --import-existing-resources, or delete it if it's unused.
My script fails the second time it runs
It calls create-role unconditionally. Check with get-role first, or catch EntityAlreadyExistsException in boto3.
IAM EntityAlreadyExists: frequently asked questions
What does EntityAlreadyExists mean in AWS?
IAM refused to create a role, user, group, policy or instance profile because one with that name already exists in your account. It's HTTP 409. Reuse the existing one, import it into your tool, or delete it if it's unused.
How do I fix "Role with name already exists" in Terraform?
Import the existing role into Terraform state instead of creating it: add import { to = aws_iam_role.app, id = "app-role" } and run terraform apply, or run terraform import aws_iam_role.app app-role.
Are IAM roles Region specific?
No. IAM is global: a role exists once per account and can be used in every Region. That's why the same role name in two Regions collides, and why IAM ARNs have no Region in them.
Are IAM role names case-sensitive?
Not for uniqueness. If app-role exists, you can't create App-Role or APP-ROLE. The same goes for users, groups, policies and instance profiles.
How do I create an IAM role only if it doesn't exist?
Check first with aws iam get-role --role-name NAME and create only if that fails, or, in boto3, call create_role and catch iam.exceptions.EntityAlreadyExistsException.
How do I see who created an IAM role?
Run aws iam get-role to see CreateDate and RoleLastUsed, and aws cloudformation describe-stack-resources --physical-resource-id NAME to see if a stack owns it. CloudTrail's CreateRole event shows who made it, within its retention period.
Can I rename an IAM role?
No. update-role changes only a role's description and maximum session duration; there's no rename. Create a new role with the new name and the same policies, move everything over, then delete the old one.
How do I import an existing IAM role into CloudFormation?
Add the role to your template with its RoleName and DeletionPolicy: Retain, then create a change set with --import-existing-resources, or an IMPORT change set with --resources-to-import using RoleName as the identifier.
How do I use an existing IAM role in CDK?
Use iam.Role.fromRoleName(this, "AppRole", "app-role", { mutable: false }) and pass it wherever a role is expected. CDK then references the role instead of creating it.
What is the difference between an instance profile and an IAM role?
The role holds the permissions; the instance profile is the container EC2 attaches to a server to carry that role. The console makes both with the same name, but they're separate IAM objects.
Why does CreateInstanceProfile say the instance profile already exists?
An instance profile with that name is still there, often left over after its role was deleted with the CLI. Delete it with aws iam delete-instance-profile, or import it.
Why can't I delete an IAM role?
DeleteConflict means it still has attached managed policies, inline policies or instance profiles. Remove those first, then run delete-role.
Does deleting and recreating an IAM role break things?
It can. Services using the role fail while it's gone, and anything that recorded the old role's unique ID won't treat the new role as the same one. Importing is safer.
What HTTP status code is EntityAlreadyExists?
409 Conflict. The AWS CLI exits with code 254 when a service returns an error like this, which is what makes a create-only script stop.
Does the same name rule apply to IAM policies?
Yes. Customer managed policy names must be unique in the account, and CreatePolicy fails with EntityAlreadyExists for a duplicate. Inline policy names only need to be unique within their role, user or group.
How do I avoid IAM name conflicts in Terraform?
Use name_prefix instead of name so Terraform adds a unique suffix, or build names from the environment and Region. Keep state in a shared backend so Terraform never forgets what it created.
For readers preparing for an AWS certification
We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.
Exams that test this topic: DevOps Engineer – Professional (DOP-C02) • CloudOps Engineer – Associate (SOA-C03).
Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:
1. Why does creating a role fail with EntityAlreadyExists in a new Region?
IAM is global. A role with that name already exists in the account, whatever Region you deploy from.
2. A CloudFormation stack deployed in two Regions fails on IAM. What is the usual fix?
Let CloudFormation generate role names, or include the Region in explicit names, or create global IAM resources in one stack only.
3. Are IAM role names case-sensitive?
No for uniqueness: role names must be unique regardless of case within an account.
4. How do you adopt an existing role into a stack?
Use CloudFormation resource import, or reference it as a parameter instead of creating it.
5. Can you rename an IAM role?
No. Create a new role and move dependent resources to it.
6. Which tool finds roles that are no longer used?
Role last-used information in IAM and unused-access findings in IAM Access Analyzer.
Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.
Ethan imported app-role with a single import block, and the next plan said "No changes." Nothing was deleted, the EC2 server using the role never noticed, and the role now lives in code where it belongs. He also switched two other roles to name_prefix, so the staging copy of the shop's setup can never fight production for a name again. Jake asked whether he'd learned anything. "Look before you create," Ethan said, and typed get-role into the deploy script.
📌 If you keep one line from this page
IAM names are global and ignore case, so "already exists" means the name is taken somewhere in your account; look with get-role, then import it, reference it, or delete it on purpose.
Terraform: import block · CloudFormation: --import-existing-resources · CDK: Role.fromRoleName · leftover? delete-instance-profile.
Revision note. Written October 13, 2026, for every 409 on a name you thought was new. "Look before you leap," goes the old proverb; in IAM, look with get-role before you create.