8

I have a large sized CloudFormation template written in Yaml, I want to start using Troposphere instead. Is there any easy way to convert the CF template to Troposphere code?

I have noticed this script here https://github.com/cloudtools/troposphere/blob/master/troposphere/template_generator.py This creates a Troposphere python object, but I am not sure if its possible to output it Troposphere code.

shantanuo
  • 31,689
  • 78
  • 245
  • 403
Sam Anthony
  • 1,669
  • 2
  • 22
  • 39
  • 2
    I'm curious why @SamAnthony. I have inherited large set of Troposphere templates and I'm wondering why we don't just use YAML instead! – spinkus Sep 12 '19 at 00:58
  • 2
    @spinkus I think regular YAML CloudFormation is still a decent option. It appears that the Troposphere will detected mistakes in the template which regular YAML would not. Example a typing mistake in a parameter name might not be caught until the YAML template is actually "executed" where as Troposphere may have detected this sooner. I also had one situation where a Python/Troposphere for loop eliminated the need to a huge YAML template with many repeated elements. – Sam Anthony Sep 15 '19 at 22:27

3 Answers3

6

You can do it by converting the CF YAML to JSON and running the https://github.com/cloudtools/troposphere/blob/master/scripts/cfn2py passing the JSON file in as an argument.

OllieB
  • 81
  • 2
1

Adding to the good tip from @OllieB

Install dependencies using pip or poetry:

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

The command line conversion is something like:

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

WARNING: it appears that the cfn2py script might not be fully unit tested or something, because it can generate some code that does not pass troposphere validations. I recommend adding a simple round-trip test to the end of the output python script, e.g.

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

See also https://github.com/cloudtools/troposphere/issues/1879 for an example of auto-generation of pydantic models from CFN json schemas.

Darren Weber
  • 1,537
  • 19
  • 20
0
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)

This snippet shall give you a template object from Troposphere library. You can then make modifications using Troposphere api.

Gaurav Singh Faujdar
  • 1,662
  • 1
  • 9
  • 13