gpt4 book ai didi

amazon-web-services - 如何在CloudFormation中创建可变计数资源?

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

我需要创建可变计数 S3 存储桶,其名称来自参数。例如。我有带有 S3 存储桶名称的数组。def BucketNames = [“第一个存储桶”,“第二个存储桶”,...,“第一个存储桶”]。有可能做到吗?也许使用嵌套堆栈。

最佳答案

您可以使用自定义资源来执行此操作:

此模板将创建自定义资源:

    AWSTemplateFormatVersion: '2010-09-09'
Description: create buckets from parameters
Parameters:
BucketList:
Description: comma delimited list of bucket names
Type: CommaDelimitedList
Default: athos,porthos,aramis
Resources:
BucketCreatorLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Code: ./bucketor/
Runtime: python3.8
Role: !GetAtt 'LambdaExecutionRole.Arn'
CustomBucketCreator:
Type: AWS::CloudFormation::CustomResource
Properties:
loglevel: info
Buckets: !Ref 'BucketList'
RoleArn: !GetAtt 'LambdaExecutionRole.Arn'
ServiceToken: !GetAtt 'BucketCreatorLambda.Arn'
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
Path: /
Policies:
- PolicyName: BucketPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:CreateBucket
Resource: arn:aws:s3:::*
Outputs:
BucketsCreated:
Description: names of buckets created
Value: !GetAtt 'CustomBucketCreator.BucketNames'

以及 lambda 的 python 脚本:

    # python file named index.py located ./bucketor/ with respect to cloudformation file
from crhelper import CfnResource
import logging
import boto3

logger = logging.getLogger(__name__)
# Initialise the helper, all inputs are optional, this example shows the defaults
helper = CfnResource(json_logging=True, log_level='DEBUG',
boto_level='CRITICAL', sleep_on_delete=120)

s3 = boto3.client("s3")

try:
# Init code goes here
pass
except Exception as e:
logger.error(e, exc_info=True)
helper.init_failure(e)


@helper.create
def create(event, context):
bucket_names = []
buckets = event["ResourceProperties"]["Buckets"]
for bucket in buckets:
bucket_names.append(s3.create_bucket(Bucket=bucket)["Bucket"])
helper.Data.update({"BucketNames": ",".join(bucket_names)})


def handler(event, context):
global logger
helper(event, context)

@helper.create将为您创建存储桶。您还需要编写适当的 @helper.delete@helper.update 装饰器,如果不这样做,自定义资源将需要手动删除

关于amazon-web-services - 如何在CloudFormation中创建可变计数资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63359362/

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