amazon-web-services - 我可以强制 CloudFormation 删除非空的 S3 存储桶吗?

标签 amazon-web-services amazon-s3 aws-cli

有没有办法强制 CloudFormation 删除非空的 S3 存储桶?

最佳答案

您可以创建一个 lambda 函数 来清理您的存储桶并使用 CustomResource 从您的 CloudFormation 堆栈中调用您的 lambda。

下面是清理存储桶的 lambda 示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import boto3
from botocore.vendored import requests


def lambda_handler(event, context):
    try:
        bucket = event['ResourceProperties']['BucketName']

        if event['RequestType'] == 'Delete':
            s3 = boto3.resource('s3')
            bucket = s3.Bucket(bucket)
            for obj in bucket.objects.filter():
                s3.Object(bucket.name, obj.key).delete()

        sendResponseCfn(event, context, "SUCCESS")
    except Exception as e:
        print(e)
        sendResponseCfn(event, context, "FAILED")


def sendResponseCfn(event, context, responseStatus):
    response_body = {'Status': responseStatus,
                     'Reason': 'Log stream name: ' + context.log_stream_name,
                     'PhysicalResourceId': context.log_stream_name,
                     'StackId': event['StackId'],
                     'RequestId': event['RequestId'],
                     'LogicalResourceId': event['LogicalResourceId'],
                     'Data': json.loads("{}")}

    requests.put(event['ResponseURL'], data=json.dumps(response_body))

创建上面的 lambda 之后,只需将 CustomResource 放入您的 CloudFormation 堆栈中:
 ---
 AWSTemplateFormatVersion: '2010-09-09'

 Resources:

   myBucketResource:
     Type: AWS::S3::Bucket
     Properties:
       BucketName: my-test-bucket-cleaning-on-delete

   cleanupBucketOnDelete:
     Type: Custom::cleanupbucket
     Properties:
       ServiceToken: arn:aws:lambda:eu-west-1:123456789012:function:clean-bucket-lambda
       BucketName: !Ref myBucketResource

Remember to attach a role to your lambda that has permission to remove objects from your bucket.



此外请记住,您可以使用 lambda 函数 cli2cloudformation 创建一个接受 CLI 命令行的 lambda 函数。您可以从 here 下载并安装。使用它,您只需要创建一个如下所示的 CustomResource:
"removeBucket": {
        "Type": "Custom::cli2cloudformation",
        "Properties": {
          "ServiceToken": "arn:aws:lambda:eu-west-1:123456789000:function:custom-lambda-name",
          "CliCommandDelete": "aws s3 rb s3://bucket-name --force",
        }
}

关于amazon-web-services - 我可以强制 CloudFormation 删除非空的 S3 存储桶吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383470/

相关文章:

amazon-web-services - AWS S3 CLI 中的选择性文件下载

scala - java.lang.AssertionError : assertion failed: No plan for HiveTableRelation

aws-cloudformation - 从 CFN 模板在本地动态创建 Step Function 状态机

javascript - 如何在不通过服务器传递文件的情况下将文件上传到 amazon S3?

bash - 如何将同一个 AMI 同时复制到多个区域?

windows - 尽管使用双引号和转义符,Windows 上的 AWS CLI 仍无法工作

python - 如何显示带名称键的快照?

node.js - 亚马逊 s3 和 Node js 视频流和缩略图?

amazon-web-services - 将 AutoscalingGroup 的 EC2 实例动态添加/删除到 AWS Dashboard 指标小组件

amazon-web-services - 如何在 spacy 运行时下载 "en_core_web_sm"模型?