You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SAM Local命令删除含S3存储桶与CloudFormation栈的完整栈?

How to Destroy an AWS SAM-deployed Stack (Including Lambda, CloudFormation Stack, and S3 Bucket)

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 rb command):
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:32:05