【问题标题】:Convert CloudFormation template (YAML) to Troposphere code将 CloudFormation 模板 (YAML) 转换为对流层代码
【发布时间】:2019-09-23 19:26:14
【问题描述】:

我有一个用 Yaml 编写的大型 CloudFormation 模板,我想开始使用 Troposphere。有什么简单的方法可以将 CF 模板转换为对流层代码?

我在这里注意到了这个脚本https://github.com/cloudtools/troposphere/blob/master/troposphere/template_generator.py 这会创建一个对流层 python 对象,但我不确定是否可以输出对流层代码。

【问题讨论】:

  • 我很好奇为什么@SamAnthony。我继承了大量对流层模板,我想知道为什么我们不直接使用 YAML!
  • @spinkus 我认为常规的 YAML CloudFormation 仍然是一个不错的选择。似乎对流层会检测到模板中的错误,而常规 YAML 不会。例如,在 YAML 模板实际“执行”之前,可能不会捕获参数名称中的输入错误,因为对流层可能会更早地检测到这一点。我还遇到过一种情况,Python/Troposphere for 循环消除了对包含许多重复元素的巨大 YAML 模板的需求。

标签: amazon-cloudformation aws-cdk troposphere


【解决方案1】:

您可以通过将 CF YAML 转换为 JSON 并运行 https://github.com/cloudtools/troposphere/blob/master/scripts/cfn2py 将 JSON 文件作为参数传入来实现。

【讨论】:

  • 我没有看到将文件名传递给脚本的方法
  • python cfn2py 文件名.py
【解决方案2】:

添加来自@OllieB 的好提示

使用 pip 或诗歌安装依赖项:

pip install 'troposphere[policy]'
pip install cfn-flip
poetry add -D 'troposphere[policy]'
poetry add -D cfn-flip

命令行转换是这样的:

cfn-flip -c -j template-vpc.yaml template-vpc.json
cfn2py template-vpc.json > template_vpc.py

警告:似乎cfn2py 脚本可能没有经过完全单元测试或其他什么,因为它可以生成一些不通过对流层验证的代码。我建议在输出 python 脚本的末尾添加一个简单的往返测试,例如

if __name__ == "__main__":

    template_py = json.loads(t.to_json())

    with open("template-vpc.json", "r") as json_fd:
        template_cfn = json.load(json_fd)

    assert template_py == template_cfn

另请参阅https://github.com/cloudtools/troposphere/issues/1879,了解从 CFN json 模式自动生成 pydantic 模型的示例。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2021-10-30
  • 2018-04-14
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2021-03-16
相关资源
最近更新 更多