Looking up the Cloudformation stack for a resource

I have an AWS account with a few dozen Cloudformation stacks deployed. Among other resources are some Route 53 hosted zones, and I was pretty sure that I’d created these manually. I wanted to get them imported into a stack, and then make some changes, but first I needed to be sure that they weren’t part of a stack already. There are enough stacks in this account that manual inspection isn’t a good option.

Turns out that a good way to do this is with the AWS CLI, and I’d like to thank Nik Rahmel on Stack Overflow for the pointer. You can use the describe-stack-resources command and pass the PhysicalResourceId of the resource instead of the StackName. Here’s an example of querying a Route 53 hosted zone:

1
aws cloudformation describe-stack-resources --physical-resource-id Z99999999AAAAAAAAAAAA

If the resource isn’t part of a stack, you’ll get a response like this:

1
An error occurred (ValidationError) when calling the DescribeStackResources operation: Stack for Z99999999AAAAAAAAAAAAdoes not exist

If the resource is part of a stack, you’ll get an array of JSON objects describing al the resources in the stack; the StackName will be one of the returned elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"StackResources": [
{
"StackName": "YourStackName",
"StackId": "arn:aws:cloudformation:us-east-1:111122223333:stack/YourStackName/XXXX",
"LogicalResourceId": "CDKMetadata",
"PhysicalResourceId": "XXXX",
"ResourceType": "AWS::CDK::Metadata",
"Timestamp": "2024-07-03T15:09:13.054000+00:00",
"ResourceStatus": "UPDATE_COMPLETE",
"DriftInformation": {
"StackResourceDriftStatus": "NOT_CHECKED"
}
},
{
...
}
]
}

There’s at least one gotcha I’ve noticed. The result is the same whether a) the resource exists but is not in a stack, and b) the resource doesn’t exist at all.