Skip to content

Instantly share code, notes, and snippets.

@epequeno
Last active January 8, 2019 17:46
Show Gist options
  • Save epequeno/71e7c980d8b08736611d54013c33ade7 to your computer and use it in GitHub Desktop.
Save epequeno/71e7c980d8b08736611d54013c33ade7 to your computer and use it in GitHub Desktop.
ST3 cloudformation build system

Requirements:

create a shell script that does the actual validation

$ cat ~/my_aws_stuff/bin/validate.sh 
#!/bin/bash
 
template_file=$1
 
# path to aws executable
aws='/path/to/your/aws'
 
# bucket to upload to if file is too big
# this needs to already be created, this script will NOT create a bucket for you.
s3_bucket='your_s3_bucket'
 
echo "Checking JSON with jq"
if jq '.' "${template_file}" > /dev/null 2>&1; then
  echo "JSON OK"
else
  echo -e "Bad JSON\n"
  # if the json doesn't validate with jq we shouldn't try to pass it
  # on to awscli
  exit 1
fi
echo
 
# template body must be < 51,200 bytes
# http://docs.aws.amazon.com/cli/latest/reference/cloudformation/validate-template.html#options
echo "Checking template against AWS"
 
file_size=$(du -b "${template_file}" | awk '{print $1}')
validate_template="${aws} cloudformation validate-template"
 
if [ "$file_size" -ge 51200 ]; then
  # file is small enough to send directly
  validate_body="--template-body=file:///\"${template_file}\" > /dev/null && echo \"Template OK\""
  eval "${validate_template} ${validate_body}"
else
  # if the file is too large, we'll upload it to s3 then validate from there.
  template_url="$(${aws} s3 cp "${template_file}" s3://"${s3_bucket}" | awk '{gsub("s3://", "https://s3.amazonaws.com/")}END{print $NF}')"
  echo "uploaded template to S3: ${template_url}"
  validate_url="--template-url=${template_url} > /dev/null && echo \"Template OK\""
  eval "${validate_template} ${validate_url}"
fi

make sure the script is executable and available in your $PATH

$ ls -l /usr/local/bin/*val*
lrwxrwxrwx 1 root root 33 Feb 25 19:32 /usr/local/bin/validate -> /home/you/my_aws_stuff/bin/validate.sh*

create a file which can tell ST to use these files

$ cat ~/.config/sublime-text-3/Packages/User/cloudformation.sublime-build 
{
  "cmd": ["validate", "$file"]
}

from the tab with the CF template, use Ctrl+B to run the build system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment