bin/infra
#!/bin/bash
AWS_KEYS=(AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION)
EXTERNAL_KEYS=(DEV_SENDGRID_API_KEY)
DEV_ECR_REPO="public.ecr.aws/a5f0m6q3/syncm8_dev"
DEVBOX_VERSION=$(cat DEVBOX_VERSION)
# Read value for specified key fron dev.env
# args:
# 1: Name of key to read
# 2: Name of variable to set "$key=$value"
getKeyValFromDevEnv(){
local key=$1
local _res=$2
local value=$(cat dev.env | grep $key)
eval $_res="'$value'"
}
# Set all the values for aws keys
# Only available inside the subshell
addAWSToEnv(){
for key in ${AWS_KEYS[@]}; do
getKeyValFromDevEnv $key keyValPair
export $keyValPair
done
}
# Authenticate docker with aws ecr
dockerLogin(){
addAWSToEnv
local command="aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws"
bin/util logAndRun $command
}
# Push dev image to aws ecr
# Must be authenticated with ecr
dockerPush(){
bin/util logAndRun "docker push $DEV_ECR_REPO:$DEVBOX_VERSION"
}
# Pull image from aws ecr
dockerPull(){
dockerLogin
bin/util logAndRun "docker pull $DEV_ECR_REPO:$DEVBOX_VERSION"
}
# Build dev image
dockerBuild(){
bin/util logAndRun "docker build --target dev --pull --rm -t $DEV_ECR_REPO:$DEVBOX_VERSION - < Dockerfile"
}
# Pulls secrets from AWS Parameter Store
pullEnv(){
# load aws env for authentication to parameter store
addAWSToEnv
# create new file
echo "" > new.dev.env
# copy aws keys from dev.env to new.dev.env
for key in ${AWS_KEYS[@]}; do
getKeyValFromDevEnv $key keyValPair
echo $keyValPair >> new.dev.env
done
# acquire keys from aws parameter store
for ac in ${EXTERNAL_KEYS[@]}; do
ret=$(aws ssm get-parameter --name $ac)
value=$(echo $ret | perl -nle'print $& while m{"Value":.*?[^\\]",}g'| cut -d \" -f4)
key=$(echo $ac| cut -d _ -f2-)
echo $key=$value >> new.dev.env
done
# replace contents of dev.env with new.dev.env
mv new.dev.env dev.env
}
runPrivileged(){
addAWSToEnv
eval $*
}
# Print help message
printHelp(){
echo "Usage: bin/infra COMMAND
Command Runner for syncm8 infra commands.
Commands:
build Build dev image.
login Authenticate docker with aws ecr.
priv Run command with aws authentication enabled.
pull Pull image from aws ecr.
pull-env Pulls secrets from AWS Parameter Store
push Push dev image to aws ecr.
N.b. Must be authenticated with ecr."
}
op=$1
restArgs="${@:2}"
case $op in
build)
dockerBuild
;;
login)
dockerLogin
;;
pull)
dockerPull
;;
pull-env)
pullEnv
;;
push)
dockerPush
;;
priv)
runPrivileged $restArgs
;;
*)
printHelp
;;
esac