Skip to content

Instantly share code, notes, and snippets.

@charlesmarshall
Created September 3, 2014 10:22
Show Gist options
  • Save charlesmarshall/2768693b9631b087e263 to your computer and use it in GitHub Desktop.
Save charlesmarshall/2768693b9631b087e263 to your computer and use it in GitHub Desktop.
Bash script to parse elements of etcd into -e docker params
#!/bin/bash
# create global ENVS associated array
declare -A ENVS
# string for the -e vars
environmentVariables=""
##
# set a a bunch of test data
generateTestEnvData(){
echo "Setting test data"
etcdctl set /env/test/foo bar 1> /dev/null
etcdctl set /env/test/bar foo 1> /dev/null
}
##
# Take a key value array and add that into the $environmentVariables string
# $1 = array of data
generateDockerEnvString(){
echo "generating the docker environment string"
for i in ${!ENVS[@]]}; do
val=${ENVS[$i]}
key="$(echo $i | tr '[:lower:]' '[:upper:]' )"
echo "---> $key = $val"
environmentVariables="${environmentVariables}-e $key=$val "
done
echo "environment string: $environmentVariables"
}
##
# fetch the data from the segment of etcd specified and convert into a key value array
# presumes the segment is under /env/
# $1 = segment to use on etcd
environmentDataFromEtcd(){
# if no arg passed, return erro
if [[ -z $1 ]]; then
echo "No arugment passed, returning."
return 1
fi
# check the env segment exists
local notFound=$(etcdctl ls /env/$1 | grep 'Key not found' | wc -l)
# return error if not found
if [[ "$notFound" -gt "1" ]]; then
echo "Environment segment not set, returning."
return 2
fi
echo "fetching data from etcd"
# loop over the env vars and fetch the data
for i in `etcdctl ls /env/$1`; do
key=$(echo $i | sed -r "s#/env/$1/##gi" | tr '[:lower:]' '[:upper:]')
echo "===> $i becomes $key"
# fetch the env var
val=$(etcdctl get ${i});
if [ -z $val ]; then
echo "Could not retrive $i, possibly a directory, ignoring"
else
ENVS[$key]=${val};
echo "====> $key = ${ENVS[$key]}"
fi
done
echo "fetched"
}
# create some test data
generateTestEnvData
# fetch from a test area in the etcd env vars
environmentDataFromEtcd "test"
generateDockerEnvString
# output the result:
echo ""
echo "RESULT: ${environmentVariables}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment