Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(cloudformation): replace IAM roles and managed policies on create-only changes (#1950)
iot-rocket510cd50f0f07
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d2d43b34..5851871d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **CloudFormation — IAM roles and managed policies are replaced** — a `Path` change on `AWS::IAM::Role` and a `Path` or `Description` change on `AWS::IAM::ManagedPolicy` replace the resource under a new generated name, a named role refuses it as a custom-named replacement, a named policy fails with the IAM duplicate-name error as on AWS, also when only its `Path` changes, generated policy names get the suffix other generated names have, and both ARNs include the `Path`.- **CloudFormation — stack updates replace resources** — a change to a property the change set reports as `RequiresRecreation: Always` now creates a new resource under a new generated name, points its dependents at it and deletes the old one after the update succeeds (a rollback deletes the new one instead). With an explicit, unchanged name the update fails with the AWS message naming the physical id; this now also covers `AWS::Lambda::Function`. A named SQS queue or SNS topic fails with AWS's already-exists error instead and keeps its messages or subscriptions.- **CloudFormation — `IMPORT` change sets execute** — existing SQS queues, SSM parameters, S3 buckets, DynamoDB tables, IAM roles, log groups, Lambda functions, IoT policies, IoT CA certificates and Cognito user pools are adopted into a new or existing stack without being changed (`IMPORT_IN_PROGRESS` to `IMPORT_COMPLETE`, or a rollback when a resource is gone), and an import that changes `Outputs` or stack tags is refused, as on AWS.- **CloudFormation — `Capabilities` check without `AUTH`** — `CFN_ENFORCE_CAPABILITIES=1` refuses a template whose IAM resources or macros the request does not acknowledge also without `AUTH=true`, as AWS always does.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex b301938d..fcc25351 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -735,6 +735,11 @@ _CUSTOM_NAME_REPLACEMENT = {"name": "InstanceProfileName","requires_replacement": lambda old, new: old.get("Path", "/") != new.get("Path", "/"),},+ "AWS::IAM::Role": {"name": "RoleName"},+ "AWS::IAM::ManagedPolicy": {+ "name": "ManagedPolicyName",+ "exists": "A policy called {name} already exists. Duplicate names are not allowed.",+ },"AWS::IoT::ProvisioningTemplate": {"name": "TemplateName","requires_replacement": lambda old, new: (@@ -2349,7 +2354,7 @@ def _lambda_url_delete(physical_id, props):def _iam_role_create(logical_id, props, stack_name):name = props.get("RoleName") or _physical_name(stack_name, logical_id, max_len=64)- arn = f"arn:aws:iam::{get_account_id()}:role/{name}"+ arn = f"arn:aws:iam::{get_account_id()}:role{props.get('Path', '/')}{name}"role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()assume_doc = props.get("AssumeRolePolicyDocument", {})if isinstance(assume_doc, dict):@@ -2398,9 +2403,8 @@ def _iam_role_create(logical_id, props, stack_name):def _iam_role_update(physical_id, old_props, new_props, stack_name, logical_id=None):"""Update a role in place, keeping its ARN and RoleId.- RoleName is create-only (a change replaces the role; AWS sanctions the- rename); Path also requires replacement, which AWS refuses for an- explicitly-named role. Everything else — assume-role document, inline+ RoleName and Path are create-only: ``_update_resource`` replaces the+ role before this runs. Everything else — assume-role document, inlinePolicies, ManagedPolicyArns, Description, MaxSessionDuration, Tags —updates in place, so policies attached from outside the template survive(the create fallback used to rebuild the record and drop them).@@ -2417,15 +2421,6 @@ def _iam_role_update(physical_id, old_props, new_props, stack_name, logical_id=Nif replaced is not None:return replaced- if new_props.get("Path", "/") != old_props.get("Path", "/"):- if old_props.get("RoleName"):- raise ValueError(- "CloudFormation cannot update a stack when a custom-named "- f"resource requires replacing. Rename {name} and update the "- "stack again."- )- return _iam_role_create(logical_id or physical_id, new_props, stack_name)-assume_doc = new_props.get("AssumeRolePolicyDocument", {})if isinstance(assume_doc, dict):assume_doc = json.dumps(assume_doc)@@ -7036,9 +7031,9 @@ def _codebuild_project_delete(physical_id, props):# --- IAM ManagedPolicy provisioner ---def _iam_managed_policy_create(logical_id, props, stack_name):- name = props.get("ManagedPolicyName", f"{stack_name}-{logical_id}")+ name = props.get("ManagedPolicyName") or _physical_name(stack_name, logical_id, max_len=128)path = props.get("Path", "/")- arn = f"arn:aws:iam::{get_account_id()}:policy/{name}"+ arn = f"arn:aws:iam::{get_account_id()}:policy{path}{name}"record = _iam.store_policy(arn, name, path, props.get("PolicyDocument", {}),description=props.get("Description", ""))_attach_policy_to_entities(arn, props)@@ -7066,28 +7061,9 @@ def _iam_managed_policy_update(physical_id, old_props, new_props, stack_name, loversion at the five-version cap first, like the CFN handler), and theRoles / Users / Groups lists reconcile through attach/detach. Thecreate-only properties (ManagedPolicyName, Path, Description) replace the- policy; under an unchanged custom name that replacement is refused, as- real CloudFormation refuses it."""- name = new_props.get("ManagedPolicyName", f"{stack_name}-{logical_id or physical_id}")+ policy in ``_update_resource`` before this runs."""record = _iam._policies.get(physical_id)- replaced = _rename_replacement(- physical_id, old_props, new_props, stack_name, logical_id,- name, record.get("PolicyName") if record else None,- _iam_managed_policy_create, _iam_managed_policy_delete,- )- if replaced is not None:- return replaced-- if (new_props.get("Path", "/") != old_props.get("Path", "/")- or new_props.get("Description", "") != old_props.get("Description", "")):- # Path and Description are create-only too, but the name didn't- # change, so the replacement cannot move to a new ARN.- if old_props.get("ManagedPolicyName"):- raise ValueError(- "CloudFormation cannot update a stack when a custom-named "- f"resource requires replacing. Rename {name} and update the "- "stack again."- )+ if record is None:return _iam_managed_policy_create(logical_id or physical_id, new_props, stack_name)if new_props.get("PolicyDocument") != old_props.get("PolicyDocument"):@@ -12789,6 +12765,8 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"SecurityGroups", "SpotPrice", "UserData",),"AWS::IAM::InstanceProfile": ("InstanceProfileName", "Path"),+ "AWS::IAM::Role": ("RoleName", "Path"),+ "AWS::IAM::ManagedPolicy": ("ManagedPolicyName", "Description", "Path"),"AWS::IoT::ProvisioningTemplate": ("TemplateName", "TemplateType"),"AWS::ElasticLoadBalancingV2::LoadBalancer": ("Name", "Scheme", "Type"),"AWS::ElasticLoadBalancingV2::TargetGroup": (diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 652f9cdc..293ee4b3 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -23492,6 +23492,106 @@ def test_cfn_iam_managed_policy_delete_detaches_entities(cfn, iam):_cfn_policy_test_roles_cleanup(iam, [role])+def _cfn_iam_replacement_template(role_name="", path="/", policy_name="", description="one",+ policy_path="/"):+ """A managed policy and a role it is attached to, named or generated."""+ policy = {"Description": description, "Path": policy_path, "PolicyDocument": {+ "Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]}}+ role = {"Path": path, "ManagedPolicyArns": [{"Ref": "Pol"}], "AssumeRolePolicyDocument": {+ "Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "sts:AssumeRole",+ "Principal": {"Service": "lambda.amazonaws.com"}}]}}+ if policy_name:+ policy["ManagedPolicyName"] = policy_name+ if role_name:+ role["RoleName"] = role_name+ return json.dumps({+ "Resources": {"Pol": {"Type": "AWS::IAM::ManagedPolicy", "Properties": policy},+ "R": {"Type": "AWS::IAM::Role", "Properties": role}},+ "Outputs": {"Role": {"Value": {"Ref": "R"}}, "Policy": {"Value": {"Ref": "Pol"}}},+ })+++def test_cfn_iam_create_only_changes_under_generated_names_replace(cfn, iam):+ """A managed policy Description change and a role Path change replace+ them under new generated names: the role attaches the new policy, and+ the old policy and role are deleted."""+ stack_name = f"cfn-iam-repl-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_iam_replacement_template(),+ Capabilities=["CAPABILITY_IAM"])+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ old_role, old_policy = _output(stack, "Role"), _output(stack, "Policy")++ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_iam_replacement_template(+ description="two"), Capabilities=["CAPABILITY_IAM"])+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ policy = _output(stack, "Policy")+ assert policy != old_policy+ assert iam.get_policy(PolicyArn=policy)["Policy"]["Description"] == "two"+ assert [p["PolicyArn"] for p in iam.list_attached_role_policies(+ RoleName=old_role)["AttachedPolicies"]] == [policy]+ with pytest.raises(ClientError):+ iam.get_policy(PolicyArn=old_policy)++ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_iam_replacement_template(+ path="/moved/", description="two"), Capabilities=["CAPABILITY_IAM"])+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ role = _output(stack, "Role")+ assert role != old_role+ described = iam.get_role(RoleName=role)["Role"]+ assert described["Path"] == "/moved/"+ assert described["Arn"].endswith(f":role/moved/{role}")+ with pytest.raises(ClientError):+ iam.get_role(RoleName=old_role)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_iam_create_only_changes_under_custom_names_fail(cfn, iam):+ """Under explicit names a role Path change is refused as a custom-named+ replacement, and a managed policy Description or Path change fails on+ the policy name the replacement would reuse; both keep what they had."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name, role, policy = f"cfn-iam-named-{uid}", f"cfn-iam-role-{uid}", f"cfn-iam-pol-{uid}"+ template = _cfn_iam_replacement_template+ cfn.create_stack(StackName=stack_name, TemplateBody=template(role, "/", policy),+ Capabilities=["CAPABILITY_NAMED_IAM"])+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ policy_arn = _output(stack, "Policy")++ cfn.update_stack(StackName=stack_name, TemplateBody=template(role, "/moved/", policy),+ Capabilities=["CAPABILITY_NAMED_IAM"])+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert (f"requires replacing. Rename {role} and update the stack again."+ in _stack_event_reasons(cfn, stack_name))+ assert iam.get_role(RoleName=role)["Role"]["Path"] == "/"++ cfn.update_stack(StackName=stack_name, TemplateBody=template(role, "/", policy, "two"),+ Capabilities=["CAPABILITY_NAMED_IAM"])+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert (f"A policy called {policy} already exists. Duplicate names are not allowed."+ in _stack_event_reasons(cfn, stack_name))+ assert iam.get_policy(PolicyArn=policy_arn)["Policy"]["Description"] == "one"++ cfn.update_stack(StackName=stack_name, TemplateBody=template(+ role, "/", policy, policy_path="/moved/"), Capabilities=["CAPABILITY_NAMED_IAM"])+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert _output(stack, "Policy") == policy_arn+ assert [p["Arn"] for p in _all_pages(iam, "list_policies", "Policies", Scope="Local")+ if p["PolicyName"] == policy] == [policy_arn]+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++def _cfn_instance_profile_template(uid, profile_props):def role(name):return {"Type": "AWS::IAM::Role", "Properties": {