Validate and debug the cloudformation template

PowerShell : Export Active Directory users
September 29, 2018
Event notification on s3 bucket to trigger lambda
October 2, 2018

Validate and debug the cloudformation template

When we write a cloudformation template to create infrastructure on AWS, we want some type of validation to check if the template is correct or not. Also if we want to create some auto deployment pipeline where infrastructure is created on the fly, there needs to be some mechanism which will validate a template with aws cli and if successful, executes it.

So how to validate the cloudformation template? How to debug cloudformation template?

1. AWS CLI
AWS CloudFormation first checks if the template is valid JSON or YAML. If it’s not valid, AWS CloudFormation returns a template validation error.

(If aws-cli is not installed, see here how to install aws cli)

Usage:
Template on Local machine:

aws cloudformation validate-template --template-body file://test-template.json

Template on S3:

aws cloudformation validate-template --template-url https://s3.amazonaws.com/s3-bucket-name/test-template.template

Common Errors:

  • 1. Error: A client error (ValidationError) occurred when calling the ValidateTemplate operation: Template format error: JSON not well-formed
    Resolution: Give the file full path with file://

    aws cloudformation validate-template --template-body file:///path/to/file/test.template
  • 2. A client error (ValidationError) occurred when calling the ValidateTemplate operation: Invalid template resource property ‘xxxxx’
    Resolution: Here you have to check proper position, syntax of the resource marked in the error message ex. including wrong elements/properties under main element

More info can be found here on AWS documentation.

2. cfn-python-lint
This python utility will validate CloudFormation yaml/json templates for the CloudFormation specification and additional checks. Includes checking valid values for resource properties and best practices.

Installation & more info can be found on this GitHub repo.

Usage:

cfn-lint template.yaml

Note:
The above two methods are the attempt to provide validation for CloudFormation templates properties and their values. The error message can sometimes misleading or if the template is big and have lots of (mappings, joins, splits, conditions) it might not able to catch exact error.

To preview how template changes impact running resources OR cloudformation equals to terraform plan:
If you want to see a preview or what changes/updates the cloudformation template will make, just before it executes, then use changesets. Please see this article on How to use changessets

Bitnami