Your stack is too large, two teams share one template, or a logical ID needs a new name. The obvious edit, removing the resource from one template and adding it to another, deletes the resource or fails because the name already exists. This guide moves ownership and leaves the physical resource untouched.
Pick the method
| Situation | Method |
|---|---|
| Resource type supports refactoring, no property changes | Stack refactor |
| Rename a logical ID in the same stack | Stack refactor with a mapping |
| Type or stack not eligible for refactoring, but importable | Retain, remove, import |
| Type supports neither | Leave it, and reference it by parameter or SSM |
| Resource isn't in any stack | Import only |
Refactoring reorganises and nothing else. It can't create, delete or reconfigure resources, or add or change parameters, conditions or mappings. Make those changes in ordinary stack updates before or after.
Check eligibility
Only types with a provisioning type of FULLY_MUTABLE can be refactored, and there is also a published exclusion list. At the time of writing it includes Auto Scaling groups, launch templates, Elastic IPs, Route 53 record sets and custom resources. Check every type in the stack:
STACK=platform-monolith
for T in $(aws cloudformation list-stack-resources --stack-name $STACK \
--query 'StackResourceSummaries[].ResourceType' --output text | tr '\t' '\n' | sort -u); do
P=$(aws cloudformation describe-type --type RESOURCE --type-name "$T" \
--query ProvisioningType --output text 2>/dev/null || echo UNKNOWN)
printf '%-18s %s\n' "$P" "$T"
done
Other blockers to find now:
- Stack policies. Stacks with any stack policy attached aren't supported, whatever it allows.
- Pseudo parameters. A moved resource that uses
AWS::StackName, or another pseudo parameter that differs between the stacks, is rejected. The value would change. - Emptying a stack. A refactor can't leave a stack without resources. Keep or add a simple one first.
- Stack count. The CLI accepts at most five stacks per refactor.
aws cloudformation get-stack-policy --stack-name $STACK
aws cloudformation get-template --stack-name $STACK --template-stage Original \
--query TemplateBody --output text > original.yaml
grep -nE 'AWS::StackName|AWS::StackId' original.yaml
Protect the data first
Caution
Put
DeletionPolicy: RetainandUpdateReplacePolicy: Retainon every stateful resource, and deploy that as a separate update, before any move. It's what saves you if a later step goes wrong. Take a backup as well: RDS snapshot, DynamoDB backup, S3 versioning.
OrdersTable:
Type: AWS::DynamoDB::Table
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
TableName: orders
Then clear drift. Moving a drifted resource carries the mismatch to the new stack, and the next update there may "fix" production.
ID=$(aws cloudformation detect-stack-drift --stack-name $STACK \
--query StackDriftDetectionId --output text)
aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id $ID
aws cloudformation describe-stack-resource-drifts --stack-name $STACK \
--stack-resource-drift-status-filters MODIFIED DELETED
Freeze the pipelines for all stacks involved. Deploying an old template mid-move would remove or recreate what you moved.
Method 1: stack refactor
Write the target templates
Create the complete desired template for each stack. Keep resource properties the same. Where a resource that stays behind used !Ref or !GetAtt on one that moved, replace the reference with an export and import:
# data.yaml
Outputs:
OrdersTableName:
Value: !Ref OrdersTable
Export:
Name: orders-table-name
# app.yaml
Environment:
Variables:
TABLE: !ImportValue orders-table-name
Watch for a circular import. If each stack imports from the other, split the resources differently.
Create the refactor and read the plan
REF=$(aws cloudformation create-stack-refactor \
--description "Split data tier from platform-monolith" \
--stack-definitions \
StackName=platform-monolith,TemplateBody@=file://app.yaml \
StackName=platform-data,TemplateBody@=file://data.yaml \
--enable-stack-creation \
--query StackRefactorId --output text)
aws cloudformation describe-stack-refactor --stack-refactor-id $REF
Continue only when Status is CREATE_COMPLETE and ExecutionStatus is AVAILABLE. On CREATE_FAILED, StatusReason names the problem, usually an unsupported type or a changed property. --enable-stack-creation lets it create platform-data.
When CloudFormation can't match a resource, such as a rename, supply a mapping and create the refactor again with --resource-mappings file://mapping.json:
[
{
"Source": {"StackName": "platform-monolith", "LogicalResourceId": "Table1"},
"Destination": {"StackName": "platform-data", "LogicalResourceId": "OrdersTable"}
}
]
Review every action before you execute:
aws cloudformation list-stack-refactor-actions --stack-refactor-id $REF \
--query 'StackRefactorActions[].{action:Action,entity:Entity,id:PhysicalResourceId,detect:Detection,from:ResourceMapping.Source.LogicalResourceId,to:ResourceMapping.Destination.LogicalResourceId}' \
--output table
You should see only MOVE for resources, and CREATE only for a new stack. Check that each physical ID lands on the logical ID you expect. Two similar queues matched the wrong way round is the mistake to catch here.
Execute and verify
aws cloudformation execute-stack-refactor --stack-refactor-id $REF
aws cloudformation describe-stack-refactor --stack-refactor-id $REF \
--query '{status:ExecutionStatus,reason:ExecutionStatusReason}'
aws cloudformation list-stack-resources --stack-name platform-data \
--query 'StackResourceSummaries[].[LogicalResourceId,PhysicalResourceId,ResourceStatus]' --output table
OBSOLETE before execution means the refactor no longer applies; create a new one. Moves also rewrite the aws:cloudformation:* tags on resources. IAM policies, backup selections, dashboards or cost reports keyed on aws:cloudformation:stack-name will change behaviour, so search for them first.
Method 2: retain, remove, import
Use this when the refactor is blocked. The resource is briefly unmanaged, but it keeps running.
- Confirm the deployed template, not your local file, has the retain policy:
aws cloudformation get-template --stack-name $STACK --template-stage Processed \
--query TemplateBody --output text > processed.yaml
grep -n 'DeletionPolicy' processed.yaml
- Remove the resource from the source through a change set. Replace references to it with literal values or parameters. The change set must show
Removefor that resource and nothing that replaces anything else.
aws cloudformation create-change-set --stack-name $STACK --change-set-name drop-orders \
--template-body file://source-without-orders.yaml --capabilities CAPABILITY_NAMED_IAM
aws cloudformation describe-change-set --stack-name $STACK --change-set-name drop-orders \
--query 'Changes[].ResourceChange.{a:Action,id:LogicalResourceId,repl:Replacement,pa:PolicyAction}' --output table
Warning
Check that
PolicyActionisRetainfor the removed resource before you execute. If it'sDeleteor empty, stop.
- Find the identifier the type needs, then import into the destination:
aws cloudformation get-template-summary --template-body file://data.yaml \
--query 'ResourceIdentifierSummaries'
cat > import.json <<'EOF'
[{"ResourceType":"AWS::DynamoDB::Table","LogicalResourceId":"OrdersTable",
"ResourceIdentifier":{"TableName":"orders"}}]
EOF
aws cloudformation create-change-set --stack-name platform-data \
--change-set-name import-orders --change-set-type IMPORT \
--resources-to-import file://import.json --template-body file://data.yaml
aws cloudformation describe-change-set --stack-name platform-data --change-set-name import-orders
aws cloudformation execute-change-set --stack-name platform-data --change-set-name import-orders
aws cloudformation wait stack-import-complete --stack-name platform-data
Import doesn't check that your template matches the live configuration. A wrong property imports cleanly and is applied on the next update that touches it. Run drift detection straight after and fix the template until it's clean.
Failures and fixes
| Symptom | Cause | Fix |
|---|---|---|
Refactor CREATE_FAILED, unsupported resource | Type is excluded | Leave it in place or use import |
| Refactor rejects a resource modification | Property, or resolved value, differs | Copy properties exactly; check parameter values |
| Source update fails: export in use | Another stack imports the value | Keep the export until consumers have moved |
| Import fails: every resource needs a deletion policy | Missing on the imported resource | Add DeletionPolicy to it |
| Import fails: resource already belongs to a stack | Source stack still owns it | Finish the removal first |
| Import rejected with other changes present | New or changed resources in the template | Import alone, then update |
Prevent it next time
- Split stacks by lifecycle: network, data, then compute. Data stacks change least and should be hardest to delete.
- Share values through SSM parameters instead of exports where you expect to move things. An export in use locks the producing stack.
- Set retain policies on stateful types from the first deployment, and enforce it with a CloudFormation Guard rule or a Hook.
- Enable termination protection on data stacks with
aws cloudformation update-termination-protection --enable-termination-protection --stack-name platform-data. - Merge the new templates into the pipelines before you unfreeze them, and check the first change set shows no changes.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get