gpt4 book ai didi

amazon-web-services - 如果存储桶存在,如何强制 CloudFormation 创建一个具有相似名称的新存储桶?

转载 作者:行者123 更新时间:2023-12-03 07:33:20 25 4
gpt4 key购买 nike

有人可以帮助我如何制作一个模板,其中 cloudformation 自动创建一个具有相似名称的新存储桶。例如,如果我的存储桶的名称是 myownbucket,cloudformation 是否可以自动创建一个名为 myownbucket1 的新存储桶(如果已经有一个名为 myownbucket 的存储桶)。谢谢

最佳答案

要通过 cloudformation 在 AWS 资源管理中创建或更新现有存储桶,您需要在 cfn.yaml/json 中拥有自定义资源

  S3Checking:
Type: 'Custom::CheckS3Bucket'
Properties:
ServiceToken: !GetAtt CustomResourceS3Function.Arn
Bucket: !Ref NotifyBucket

CustomResourceS3Function 看起来像这样

 CustomResourceLambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Handler: index.lambda_handler
Role: !GetAtt LambdaIAMRole.Arn
Code:
ZipFile: |
from __future__ import print_function
import json
import boto3
import cfnresponse

SUCCESS = "SUCCESS"
FAILED = "FAILED"

print('Loading function')
s3 = boto3.resource('s3')

def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
responseData={}
try:
print("Request Type:",event['RequestType'])
bucket_name=event['ResourceProperties']['Bucket']
bucket=event['ResourceProperties']['Bucket']
update_delete_buckets(bucket_name)
responseData={'Bucket':Bucket}
print("Sending response to custom resource")
responseStatus = 'SUCCESS'
except Exception as e:
print('Failed to process:', e)
responseStatus = 'FAILED'
responseData = {'Failure': 'Something bad happened.'}
cfnresponse.send(event, context, responseStatus, responseData)

def update_delete_buckets(bucket):
bucket_obj = s3.Bucket(bucket)
if bucket_obj.creation_date:
print("The bucket exists")
else:
print("The bucket does not exist")
s3.create_bucket(Bucket=bucket)

Runtime: python3.9
Timeout: 50

关于amazon-web-services - 如果存储桶存在,如何强制 CloudFormation 创建一个具有相似名称的新存储桶?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74098718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com