Njo*_*joi 7 amazon-s3 amazon-web-services aws-cloudformation
我正在尝试在 AWS CloudFormation 模板中传递逗号分隔的参数列表,并根据这些值创建多个 Amazon S3 存储桶。
我有一个要求,我将传递一个逗号分隔的国家/地区名称列表,然后 CloudFormation 模板将构建那么多 S3 存储桶(基于传入参数的国家/地区名称)。
例如,如果我传入fr,us,gb一个参数,堆栈应该创建fr_myprod_bucket, us_myprod_bucket, gb_myprod_bucket。
我知道 CloudFormation 中没有 for 循环,所以不确定如何实现?
使用计数宏!
Count 宏为 CloudFormation 资源提供模板范围的 Count 属性。它允许您指定同一类型的多个资源,而无需剪切和粘贴。
因此,以下内容:
AWSTemplateFormatVersion: "2010-09-09"
Transform: Count
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
Tags:
- Key: TestKey
Value: my bucket %d
Count: 3
Run Code Online (Sandbox Code Playgroud)
相当于:
AWSTemplateFormatVersion: "2010-09-09"
Resources:
Bucket1:
Type: AWS::S3::Bucket
Properties:
Tags:
- Key: TestKey
Value: my bucket 1
Bucket2:
Type: AWS::S3::Bucket
Properties:
Tags:
- Key: TestKey
Value: my bucket 2
Bucket3:
Type: AWS::S3::Bucket
Properties:
Tags:
- Key: TestKey
Value: my bucket 3
Run Code Online (Sandbox Code Playgroud)
现在可以使用Fn::ForEach. 详情请参阅公告和文档。
你可以做如下的事情:
AWSTemplateFormatVersion: 2010-09-09
Description: Create multiple Amazon S3 buckets using prefix from a comma delimited list
Transform: AWS::LanguageExtensions
Parameters:
CountryNames:
Description: Country prefix names
Default: "fr,gb,us"
Type: CommaDelimitedList
Resources:
'Fn::ForEach::S3Buckets':
- ParamName
- !Ref CountryNames
- 'Bucket${ParamName}':
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub '${ParamName}-my-prod-bucket-${AWS::Region}-${AWS::AccountId}'
## Add more configuration parameters for the buckets here...
Run Code Online (Sandbox Code Playgroud)
您是对的 - AWS CloudFormation 中没有循环的概念。
AWS CloudFormation 是一种声明性语言。它描述了期望的输出,但没有说明应该如何实现结果。
要执行您描述的逻辑,您需要创建一个AWS Lambda 支持的自定义资源。CloudFormation 将调用提供的 Lambda 函数,然后该函数可以进行任何所需的 API 调用。
模板只是创建这些存储桶,那么使用 CloudFormation 实际上没有任何好处。只需运行直接执行此操作的程序或脚本即可。
https://palletsprojects.com/p/jinja/是将 for 循环添加到 CloudFormation 模板的另一种选择。您需要在将 Jinja 模板传递给 CloudFormation 之前呈现它,因为 CloudFormation 本身目前无法处理 Jinja 模板。
{% for country in ["fr", "us", "gb"] %}
{{country}}_myprod_bucket:
Type: AWS::S3::Bucket
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
渲染 Jinja 片段会产生:
fr_myprod_bucket:
Type: AWS::S3::Bucket
us_myprod_bucket:
Type: AWS::S3::Bucket
gb_myprod_bucket:
Type: AWS::S3::Bucket
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15570 次 |
| 最近记录: |