Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validate and lint CloudFormation templates
#!/bin/bash
read -r -d '' HELP <<END
Dependencies:
AWS CLI https://docs.aws.amazon.com/cli/latest/userguide/installing.html
cfn-nag https://github.com/stelligent/cfn_nag
validate_cf.sh
-h Show this output
-p (Optional) <AWS CLI profile name>
-t <template to validate>
END
profile="default"
template=""
while getopts "hp:t:" opt; do
case $opt in
h)
echo $HELP
exit 0
;;
p)
profile=$OPTARG
;;
t)
template=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
if [[ $template == "" ]]; then
echo "You must give a template with the -t option."
exit 1
fi
echo "Running the AWS CLI validator..."
aws --profile $profile cloudformation validate-template --template-body file://$template
echo
if [[ $template == *".json" ]]; then
echo "Using Python to parse JSON..."
# 1. The AWS CLI validator ignores some JSON requirements (like no trailing commas), but it's cleanest to keep
# them valid JSON in case you ever need to process them with another tool.
# 2. You can't do the YAML equivalent of this because it fails on the CF-specific !Ref and similar syntax.
# 3. We use Python because it's a dependency of the AWS CLI so we know it'll already be installed.
python - <<END
import json
with open('$template') as f:
json.load(f)
END
if [ $? -eq 0 ]; then
echo "JSON parsed successfully."
fi
echo
fi
echo "Running cfn-nag..."
cfn_nag_scan --input-path $template
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment