Skip to content

CloudFormation: DeleteStack never detaches a role from an instance profile, so the stack ends DELETE_FAILED and can never converge #581

Closed

Description

@scttfrdmn

Verified against ghcr.io/scttfrdmn/substrate:0.92.0 (/health reports v0.92.0), not read from the changelog.

What happens

A stack holding an AWS::IAM::Role and an AWS::IAM::InstanceProfile that references it deletes inverted from both directions: the role reaches DELETE_COMPLETE while still attached, and the profile that references it fails.

create: CREATE_COMPLETE
profile roles after create: ['probe-role-1']
delete: DELETE_FAILED
   ProbeRole    DELETE_COMPLETE
   ProbeProfile DELETE_FAILED   DeleteConflict: Cannot delete entity, must detach all roles first.
role:    gone (NoSuchEntity)
profile: STILL EXISTS

Retrying DeleteStack does not help — it returns DELETE_FAILED again and the profile still exists, so the stack can never converge. There is no RetainResources escape either, since the resource that fails is the one still present.

Real CloudFormation calls RemoveRoleFromInstanceProfile as part of deleting an AWS::IAM::InstanceProfile, and orders the two resources by the Ref dependency, so this stack deletes cleanly.

There are two distinct defects here

1. DeleteRole does not enforce the instance-profile constraint

Reproduced with direct IAM calls, no CloudFormation involved:

DeleteRole on an attached role: SUCCEEDED   (real IAM raises DeleteConflict)
profile now lists roles: ['direct-role']
DeleteInstanceProfile: refused — DeleteConflict

Real IAM refuses DeleteRole with DeleteConflict while the role is in any instance profile. Substrate allows it, which leaves the profile holding a dangling reference to a role that no longer exists — and DeleteInstanceProfile then refuses because of that reference. RemoveRoleFromInstanceProfile for the deleted role does still succeed, so it is recoverable by hand:

RemoveRoleFromInstanceProfile: succeeded
DeleteInstanceProfile: succeeded -> recoverable

but nothing in the CloudFormation path performs that call, so the stack cannot recover itself.

2. AWS::IAM::InstanceProfile deletion does not detach its roles

Even with defect 1 fixed, deleting the profile has to remove its roles first. Real CloudFormation does this; substrate issues a bare DeleteInstanceProfile, which IAM correctly refuses.

Fixing 1 alone would flip the symptom rather than fix it: the role delete would then be the one to fail, and the stack would still end DELETE_FAILED.

Reproducer

import time, boto3, botocore

kw = dict(endpoint_url="http://localhost:4566", region_name="us-east-1",
          aws_access_key_id="test", aws_secret_access_key="test")
cfn, iam = boto3.client("cloudformation", **kw), boto3.client("iam", **kw)

TEMPLATE = """
AWSTemplateFormatVersion: '2010-09-09'
Resources:
  ProbeRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: probe-role-1
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal: {Service: ec2.amazonaws.com}
            Action: sts:AssumeRole
  ProbeProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName: probe-profile-1
      Roles: [!Ref ProbeRole]
"""

cfn.create_stack(StackName="probe-ip", TemplateBody=TEMPLATE,
                 Capabilities=["CAPABILITY_NAMED_IAM"])
time.sleep(3)
cfn.delete_stack(StackName="probe-ip")
time.sleep(3)

print(cfn.describe_stacks(StackName="probe-ip")["Stacks"][0]["StackStatus"])
for r in cfn.describe_stack_resources(StackName="probe-ip")["StackResources"]:
    print(" ", r["LogicalResourceId"], r["ResourceStatus"], r.get("ResourceStatusReason", ""))
iam.get_instance_profile(InstanceProfileName="probe-profile-1")  # succeeds; it should be gone

The direct-IAM half:

TRUST = ('{"Version":"2012-10-17","Statement":[{"Effect":"Allow",'
         '"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}')
iam.create_role(RoleName="direct-role", AssumeRolePolicyDocument=TRUST)
iam.create_instance_profile(InstanceProfileName="direct-profile")
iam.add_role_to_instance_profile(InstanceProfileName="direct-profile", RoleName="direct-role")
iam.delete_role(RoleName="direct-role")  # real IAM: DeleteConflict. substrate: 200

Why it matters downstream

Found in parsl-ephemeral-provider, whose detached mode deploys a bastion from a CloudFormation template carrying exactly this role + instance-profile pair. Two consequences:

The second point is the one I would weight: an emulator that is more permissive than IAM on an ordering constraint silently certifies broken cleanup code.

Relationship to #560

Independent, but they compound. #560 means a stack's resources take their logical IDs as physical names; this issue means those names survive teardown. Together, any template deployed twice collides on a name the first stack promised to delete. Both need to land before the downstream project can move its pin off 0.88.0.

Activity

  1. scttfrdmn commented on Aug 6, 2026

    @scttfrdmn
    OwnerAuthor

    Both defects reproduce on main (97718ff), including the inversion, and the stack cannot converge.

    Via CloudFormation. create → CREATE_COMPLETE, profile roles ['probe-role-1']. delete → DELETE_FAILED, with ProbeRole DELETE_COMPLETE and ProbeProfile DELETE_FAILED DeleteConflict. Afterwards get-role → NoSuchEntity but the profile still exists. A second DeleteStack returns DELETE_FAILED again and the profile is still there — so there is no retry path, and no RetainResources escape either, because the resource that fails is the one still present.

    Defect 1 in isolation, no CloudFormation involved. Direct IAM calls: DeleteRole on a role held by an instance profile succeeded. The profile then lists a role that no longer exists, and DeleteInstanceProfile refuses it with DeleteConflict. Recoverable by hand (RemoveRoleFromInstanceProfile, then delete), but nothing in the CFN delete path makes that call.

    The DeleteRole reference documents exactly what is missing: "Before attempting to delete a role, remove the following attached items: … Instance profile (RemoveRoleFromInstanceProfile)". DeleteConflict — "attempted to delete a resource that has attached subordinate entities" — is HTTP 409, and substrate already returns that code and status for the attached-policies case two blocks up in deleteRole (emulator/iam_plugin.go:489), so this is filling in a case the same function already handles for a sibling constraint. listInstanceProfiles (iam_plugin.go:2626) already does the instance_profile: sweep DeleteRole needs.

    Design note on the second half. cfnDeleteRequestFunc returns exactly one request per resource, deliberately, "so every entry stays a data declaration" (emulator/cfn_delete.go:11-27). Rather than weaken that contract for one type, the profile's detach lands as an optional pre-step — a cfnDeletePreSteps map consulted by deleteOneResource before the main request and dispatched through the existing dispatchResourceDelete, so absent-resource tolerance and event recording are unchanged. The profile's pre-step emits one RemoveRoleFromInstanceProfile per role in its declared Roles.

    On ordering: AWS::IAM::Role is priority 1 and AWS::IAM::InstanceProfile is 2, and the delete sweep sorts descending, so the profile is already deleted before the role — which is why the pre-step is sufficient on its own. But the probe shows the role reaching DELETE_COMPLETE regardless, so the test will assert the dispatch order rather than trust the priority table.

    As the issue says, fixing either defect alone flips the symptom instead of fixing it, so both land in one PR. Milestoned into v0.94.0.

  2. added this to the v0.94.0 milestone on Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions