簡體   English   中英

將 CloudFormation 模板 (YAML) 轉換為對流層代碼

[英]Convert CloudFormation template (YAML) to Troposphere code

我有一個用 Yaml 編寫的大型 CloudFormation 模板,我想開始使用 Troposphere。 有什么簡單的方法可以將 CF 模板轉換為對流層代碼嗎?

我在這里注意到這個腳本https://github.com/cloudtools/troposphere/blob/master/troposphere/template_generator.py這創建了一個對流層 python object,但我不確定它是否有可能到 output 它對流層代碼。

您可以通過將 CF YAML 轉換為 JSON 並運行https://github.com/cloudtools/troposphere/blob/master/scripts/cfn2py將 JSON 文件作為參數傳遞來實現。

添加來自@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 模型的示例。

from troposphere.template_generator import TemplateGenerator
import yaml

with open("aws/cloudformation/template.yaml") as f:
    source_content = yaml.load(f, Loader=yaml.BaseLoader)
    template = TemplateGenerator(source_content)

此代碼段將為您提供來自 Troposphere 庫的模板 object。 然后您可以使用對流層 api 進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM