Skip to content

Instantly share code, notes, and snippets.

@ysingh
Created March 30, 2020 15:27
Show Gist options
  • Save ysingh/a54d35acbc2e29ceaa5563015542b105 to your computer and use it in GitHub Desktop.
Save ysingh/a54d35acbc2e29ceaa5563015542b105 to your computer and use it in GitHub Desktop.
#!/bin/bash
function usage(){
path="$BASH_SOURCE"
cmd="$(basename $path)"
if [[ ${path:0:1} != / ]]; then
path="$(cd "$(dirname $path)"; pwd)/$cmd"
fi
if [[ ${1:-} == -q ]]; then
if [[ -n ${2:-} ]]; then
printf "${!2}"
fi
return
fi
example="email-confirmation-us-east-1:59"
cat<<\
USAGE
Generate env var exports based on the environment defined in an AWS ECS task-definition
Usage:
$cmd [-h]
$cmd --init
$cmd [-t] <task_definition_name>:<version>
Options:
-h, --help show this help
-i, --init output function wrapper (ideal for eval()ing in your shell rc/profile)
-t, --task name and version of task to get env vars from (default behavior even if flag omitted)
Examples:
1. Make wrapper function available via shell rc/profile.
in ~/.bash_profile or ~/.zprofile:
source $path --init
in bash/zsh:
$cmd $example
2. Execute script with task id to get export commands.
in bash/zsh:
$cmd $example
output:
export NODE_ENV="dev"
export CONTENTFUL_ENV="master"
...
3. Use eval to execute the export commands in the current shell.
in bash/zsh:
eval "\$($cmd $example)"
4. Source script with task id to execute the export commands in the current shell.
in bash/zsh:
source $path $example
or:
. $path $example
USAGE
return 1
}
function handle_usage_init_or_main(){
if [[ -z ${1:-} || $1 =~ -?-help || $1 == -h ]]; then
usage
elif [[ $1 =~ -?-init || $1 == -i ]]; then
init
else
if [[ $1 =~ -?-task || $1 == -t ]]; then
shift
fi
if [[ $1 == -- ]]; then
shift
fi
if [[ $0 == $BASH_SOURCE ]]; then
main "$@"
else
eval "$(main "$@")"
fi
fi
}
function init(){
printf 'function %s(){ source "%s" "$@"; }' "$(usage -q cmd)" "$(usage -q path)"
}
function main(){
aws ecs describe-task-definition --task-definition "$@" | \
jq -rf <(cat<<\
JQ_FILTER
def env:
.taskDefinition.containerDefinitions[].environment[]
;
def key:
map(select(.key == "name")) | .[].value
;
def val:
map(select(.key == "value")) | .[].value
;
env | to_entries | "export \(key)=\(val | tojson)"
JQ_FILTER
)
}
handle_usage_init_or_main "$@"
# vim: set et ts=2 sts=2 sw=2 :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment