有没有办法强制 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/