反复部署的AWS CloudFormation栈删除耗时久,如何快速删除?
我们采用AWS SAM进行部署,对应的template.yaml内容如下:
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > template Sample SAM Template for template Parameters: Prefix: Type: String Default: '__PREFIX__' DbSecretName: Type: String Globals: Function: Runtime: nodejs18.x Timeout: 10 MemorySize: 128 Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: FunctionName: !Sub '${Prefix}-hello-world' CodeUri: ../src/app Handler: app.lambdaHandler Architectures: - x86_64 Environment: Variables: DB_SECRET_NAME: !Ref DbSecretName Role: !GetAtt HelloWorldFunctionRole.Arn Metadata: BuildMethod: esbuild BuildProperties: Minify: true Target: 'es2022' Sourcemap: true EntryPoints: - app.ts HelloWorldFunctionRole: Type: AWS::IAM::Role Properties: RoleName: !Sub '${Prefix}-hello-world-role' AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole Policies: - PolicyName: AllowSecretsManagerAccess PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: secretsmanager:GetSecretValue Resource: '*' # Resource: !Sub 'arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:${DbSecretName}/*' - PolicyName: AllowEC2CreateNetworkInterface PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: ec2:CreateNetworkInterface Resource: '*' - PolicyName: AllowEC2DescribeNetworkInterfaces PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: ec2:DescribeNetworkInterfaces Resource: '*' - PolicyName: AllowEC2DeleteNetworkInterface PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: ec2:DeleteNetworkInterface Resource: '*'
手动删除该部署后的栈时,栈会处于DELETE_IN_PROGRESS状态,等待时间长达1小时。已确认未涉及VPC,新创建的栈可正常删除,但反复创建删除的栈删除耗时极久,求快速删除栈的方法及技术见解。
反复创建删除栈后出现删除延迟,核心原因是Lambda关联资源残留或清理队列阻塞,比如未彻底清理的版本/别名、IAM角色依赖残留、CloudWatch日志订阅等,以下是具体解决方法:
提前清理Lambda版本与关联资源
反复部署会生成大量Lambda版本,这些版本会在删除栈时被逐一清理,导致延迟。先手动清理非$LATEST版本:aws lambda list-versions-by-function --function-name <your-prefix>-hello-world --query 'Versions[?Version!=\`$LATEST\`].Version' --output text | xargs -I {} aws lambda delete-function --function-name <your-prefix>-hello-world --qualifier {}同时检查Lambda函数的事件源映射、层关联、日志订阅,手动清理后再触发栈删除。
优化SAM模板的清理规则
在Lambda函数和IAM角色中添加DeletionPolicy: Delete,确保CloudFormation删除栈时直接清理资源,避免依赖等待;同时给Lambda配置AutoPublishAlias,自动管理版本,减少零散版本生成:HelloWorldFunction: Type: AWS::Serverless::Function Properties: ... AutoPublishAlias: live DeletionPolicy: DeleteHelloWorldFunctionRole: Type: AWS::IAM::Role Properties: ... DeletionPolicy: Delete强制清理卡住的资源
查看CloudFormation栈的"事件"标签,定位卡住的资源(通常是Lambda函数或IAM角色),手动删除该资源后,重新触发栈删除。如果仍无效果,使用CLI强制删除栈:aws cloudformation delete-stack --stack-name <your-stack-name> --region <your-region>排查CloudWatch日志组依赖
Lambda的CloudWatch日志组如果被其他服务引用(比如CloudWatch Insights订阅、第三方监控),会导致日志组无法快速删除,进而阻塞栈删除。进入CloudWatch日志组页面,检查并清理所有订阅过滤器后再删除栈。
内容的提问来源于stack exchange,提问作者kyoshida

