logo hsb.horse
← Back to snippets index

Snippets

Generate parameter.json from a CloudFormation Template

A snippet that combines aws cloudformation validate-template and jq to automatically generate a parameters.json with environment variable overrides.

Published: Updated:

Retrieve the parameter list from a template using aws cloudformation validate-template, then use jq to override default values with environment variables and write the result to parameters.json.

Terminal window
aws cloudformation validate-template \
--template-body "file://path/to/template" \
--query "Parameters[].{ParameterKey:ParameterKey,ParameterValue:DefaultValue}" \
| jq 'sort_by(.ParameterKey)' \
| jq 'map(
.ParameterValue = (env[.ParameterKey] // .ParameterValue)
)' > "parameters.json"

Each jq Step

StepProcessing
sort_by(.ParameterKey)Sort alphabetically by key name (stabilizes diffs)
env[.ParameterKey]Retrieve the environment variable with the same name. Returns null if undefined
// .ParameterValueFall back to the default value when null

Pattern: Fetch Existing Values from a Deployed Stack

To generate the file based on the values currently set in the stack rather than the template defaults, use describe-stacks.

Terminal window
aws cloudformation describe-stacks \
--stack-name "your-stack-name" \
--query "Stacks[0].Parameters[].{ParameterKey:ParameterKey,ParameterValue:ParameterValue}" \
| jq 'sort_by(.ParameterKey)' \
| jq 'map(
.ParameterValue = (env[.ParameterKey] // .ParameterValue)
)' > "parameters.json"

Exclude Parameters with a null DefaultValue

To exclude parameters that have no default value set in the template:

Terminal window
aws cloudformation validate-template \
--template-body "file://path/to/template" \
--query "Parameters[].{ParameterKey:ParameterKey,ParameterValue:DefaultValue}" \
| jq '[.[] | select(.ParameterValue != null)]' \
| jq 'sort_by(.ParameterKey)' \
| jq 'map(
.ParameterValue = (env[.ParameterKey] // .ParameterValue)
)' > "parameters.json"

Shell Script Version

#!/usr/bin/env bash
set -euo pipefail
TEMPLATE="${1:?Usage: $0 <template-path> [output-path]}"
OUTPUT="${2:-parameters.json}"
aws cloudformation validate-template \
--template-body "file://${TEMPLATE}" \
--query "Parameters[].{ParameterKey:ParameterKey,ParameterValue:DefaultValue}" \
| jq 'sort_by(.ParameterKey)' \
| jq 'map(
.ParameterValue = (env[.ParameterKey] // .ParameterValue)
)' > "${OUTPUT}"
echo "Generated: ${OUTPUT}"
Terminal window
# Example usage
Env1=value1 Env2=value2 ./generate-params.sh path/to/template.yaml