gpt4 book ai didi

aws-cloudformation - 如何使用 pyplate 宏配置大量资源

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

在这个学习练习中,我想使用 PyPlate除了 TestBucket 之外,用于配置 BucketABucketBBucketC 存储桶的脚本。

想象一下,BucketNames 参数可以由此模板的用户设置,例如,该用户将使用 UUID 指定一百个存储桶名称。

AWSTemplateFormatVersion: "2010-09-09"
Transform: [PyPlate]
Description: A stack that provisions a bunch of s3 buckets based on param names
Parameters:
BucketNames:
Type: CommaDelimitedList
Description: All bucket names that should be created
Default: BucketA,BucketB,BucketC
Resources:
TestBucket:
Type: "AWS::S3::Bucket"

#!PyPlate
output = []
bucket_names = params['BucketNames']
for name in bucket_names:
output.append('"' + name + '": {"Type": "AWS::S3::Bucket"}')

上面的内容在部署时响应模板格式错误:YAML 格式不正确。 (第 15 行,第 3 列)

最佳答案

尽管接受的答案在功能上是正确的,但还有更好的方法来解决这个问题。本质上,PyPlate 代码递归地读取堆栈中的所有键值对,并将这些值替换为其 Python 计算值(即它们与 #!PyPlate 正则表达式匹配)。所以我们需要有一个与PyPlate代码相对应的 key 。

以下是 PyPlate 和 Explode 的组合如何解决上述问题。

AWSTemplateFormatVersion: "2010-09-09"
Transform: [PyPlate, Explode]
Description: A stack that provisions a bunch of s3 buckets based on param names
Parameters:
BucketNames:
Type: CommaDelimitedList
Description: All bucket names that should be created
Default: BucketA,BucketB,BucketC
Mappings: {}
Resources:
MacroWrapper:
ExplodeMap: |
#!PyPlate
param = "BucketNames"
mapNamespace = param + "Map"
template["Mappings"][mapNamespace] = {}
for bucket in params[param]:
template["Mappings"][mapNamespace][bucket] = {
"ResourceName": bucket
}
output = mapNamespace
Type: "AWS::S3::Bucket"

TestBucket:
Type: "AWS::S3::Bucket"

这种方法非常强大,因为:

  1. 您可以将资源附加到现有模板,因为您不会篡改整个 Resources block
  2. 您不需要按照 Explode 的要求依赖硬编码的映射。您可以在 Cloudformation 中驱动动态逻辑。
  3. 大多数 Cloudformation props/KV 仍保留在 YAML 部分中,并且有极少的 Python 部分增强了 CFT 功能。

请注意宏顺序 - PyPlate 需要在 Explode 之前执行,这就是为什么顺序是 [PyPlate, Explode]。执行是顺序的。

如果我们浏览 PyPlate 的源代码,它可以让我们控制更多与模板相关的变量,即

  • params(堆栈参数)
  • 模板(整个模板)
  • account_id
  • 地区

在本例中我使用了 template 变量。

希望这有帮助

关于aws-cloudformation - 如何使用 pyplate 宏配置大量资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60758345/

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