如何使用SAM Local命令删除含S3存储桶与CloudFormation栈的完整栈?
Great question! SAM Local is primarily built for local Lambda testing (like the sam local invoke command you used in the Hello World example), but it doesn't have a dedicated command to tear down your full deployed stack. Instead, we'll use AWS CLI commands paired with your SAM deployment context to clean everything up properly:
1. Delete the CloudFormation Stack
First, we'll remove the CloudFormation stack that SAM created during deployment. This will clean up most resources tied to your serverless app—including the Lambda function, IAM roles, and any other resources defined in your SAM template.
If you used the stack name MY-NEW-STACK from your example, run this command:
aws cloudformation delete-stack --stack-name MY-NEW-STACK
Wait a minute for CloudFormation to complete the deletion process (you can check status in the AWS Console or with aws cloudformation describe-stacks --stack-name MY-NEW-STACK).
2. Clean Up the S3 Bucket Used for Packaging
The S3 bucket you specified in sam package (replace BUCKET-NAME with your actual bucket name) isn't part of the CloudFormation stack—it's a standalone resource you created. So we need to delete it separately:
- First, empty the bucket (CloudFormation can't delete non-empty buckets, and neither can the
s3 rbcommand):
aws s3 rm s3://BUCKET-NAME --recursive
- Then delete the now-empty bucket:
aws s3 rb s3://BUCKET-NAME
A Quick Note on Template-defined S3 Buckets
If you added an S3 bucket directly in your SAM template (not just the packaging bucket), CloudFormation won't delete it by default even when you delete the stack—this is a safety measure to avoid accidental data loss. To make CloudFormation automatically delete the bucket (and its contents) when the stack is removed, add the DeletionPolicy: Delete property to your bucket resource in the template:
Resources: MyAppBucket: Type: AWS::S3::Bucket Properties: # Your bucket properties here DeletionPolicy: Delete
内容的提问来源于stack exchange,提问作者red888

