AWS CloudFormation Template Flip
cfn-flip is a Python library and command-line tool for converting AWS CloudFormation templates between JSON and YAML formats, making use of YAML's short function syntax where possible. The library is currently at version 1.3.0, with the last release in 2021, suggesting a maintenance rather than active rapid development cadence for the core library, though the CLI usage is deprecated.
Warnings
- deprecated The command-line interface (CLI) of `cfn-flip` is officially deprecated. Users are advised to use `rain fmt` from the `aws-cloudformation/rain` project for CLI-based template formatting and conversion instead.
- gotcha Converting JSON templates to YAML using `cfn-flip`'s default shorthand syntax for intrinsic functions (e.g., `!Ref`, `!GetAtt`) can unexpectedly cause CloudFormation Change Sets to propose resource replacement instead of modification, even if no logical change occurred. This can lead to unintended downtime or data loss.
- gotcha When converting a CloudFormation template from YAML to JSON format using `cfn-flip`, any comments present in the original YAML template will be lost in the resulting JSON output, as JSON does not natively support comments.
- gotcha `cfn-flip` uses a YAML parser that is more strict than the AWS CloudFormation service itself. This means that `cfn-flip` might flag certain YAML syntax issues (e.g., using tabs instead of spaces for indentation) as errors, even though CloudFormation might accept them.
Install
-
pip install cfn-flip
Imports
- flip
from cfn_flip import flip
- to_yaml
from cfn_flip import to_yaml
- to_json
from cfn_flip import to_json
Quickstart
from cfn_flip import to_yaml, to_json
json_template = '''
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Example JSON template",
"Resources": {
"MyS3Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "my-unique-example-bucket"
}
}
}
}
'''
yaml_output = to_yaml(json_template)
print("--- JSON to YAML ---")
print(yaml_output)
yaml_template = '''
AWSTemplateFormatVersion: '2010-09-09'
Description: Example YAML template
Resources:
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Role: !GetAtt MyLambdaRole.Arn
Code:
S3Bucket: my-code-bucket
S3Key: my-code.zip
Runtime: python3.9
'''
json_output = to_json(yaml_template)
print("\n--- YAML to JSON ---")
print(json_output)