0
votes

If I used SAM to deploy a stack and later on decided to delete all resources associated with that stack, how would I be able to do that? Because using SAM, sam deploy --stack-name my_lambda_stack --image-repository $MY_AWS_ACCOUNT.dkr.ecr.us-west-2.amazonaws.com/mystack_images

A plain user supplied string is provided as a commandline argument.

But later on, in order to delete the stack with all associated resources using "aws cloudformation" CLI, aws cloudformation delete-stack --stack-name my_lambda_stack

Will not work because it is expecting a unique StackId although the man page is confusing as it is saying Stack Name.

My question is from the user supplied Stack Name, how do I retrieve the corresponding Stack Id using "aws cloudformation list-stacks" or "aws cloudformation describe-stacks"?

Do I have to write a script to parse the output one record at a time?

I understand "aws" CLI has a --query capability but I am at a loss how I could perform wildcard matching and return the matching Stack Id back to me using "aws cloudformation list-stacks --query ..." command.

Any hints would help.

thanks,

Yang cloudformation newbie

2

2 Answers

2
votes

sam deploy and the aws cloudformation delete-stack command you provided should work together without problems. Delete stack supports either the stack name or the unique id as input. Both should work.

Note that stacknames are restricted in their naming and underscores are not allowed. This makes me wonder if the stack is even deployed in the first place.

From the AWS docs:

A stack name can contain only alphanumeric characters (case-sensitive) and hyphens. It must start with an alphabetic character and can't be longer than 128 characters.

Regarding your question with the query syntax:

aws cloudformation describe-stacks --stack-name myteststack --query 'Stacks[*].StackId'

returns the stack id. Optionally add --output text to have the output as a simple string.

0
votes

I am answering my own question, this should work:

aws cloudformation list-stacks --query 'StackSummaries[?StackName==`my_lambda_stack`]'.StackId --output text > stackId.txt

But I haven't figured out a way to use --stack-status-filter to do negative filtering of those stacks that are DELETE_COMPLETE, so I don't double delete them.