Skip to content

Instantly share code, notes, and snippets.

@tooky
Created October 31, 2024 11:14
Show Gist options
  • Save tooky/10c0aa57e42eaa5a4d5e8ba312cfbf68 to your computer and use it in GitHub Desktop.
Save tooky/10c0aa57e42eaa5a4d5e8ba312cfbf68 to your computer and use it in GitHub Desktop.
Kosli nodeploy script
#!/usr/bin/env bash
set -Eeu
SCRIPT_NAME=nodeploy.sh
SCRIPT_DIR=$(dirname "$(readlink -f $0)")
export KOSLI_ORG="kosli"
REASON=""
ACTION=""
ENVIRONMENT=""
die()
{
echo "Error: $1" >&2
exit 1
}
print_help()
{
cat <<EOF
Usage: $SCRIPT_NAME [-h] [-r "reason"] {on|off|assert*} [<ENVIRONMENT: prod-aws>]
You must have the kosli CLI and JQ installed.
Options are:
-h Print this help menu
-r "<reason>" Give a reason for stopping deployments. Mandatory for 'on' command
EOF
}
check_arguments()
{
while getopts "hr:" opt; do
case $opt in
h)
print_help
exit 1
;;
r)
REASON="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
# Remove options from command line
shift $((OPTIND-1))
ACTION=${1:-assert};
ENVIRONMENT=${2:-prod-aws}
if [ -z "${REASON}" -a "${ACTION}" = "on" ]; then
die "A reason (-r) must be given"
fi
}
create_flow()
{
local ENVIRONMENT=$1; shift
local flow_name
flow_name="${ENVIRONMENT}-nodeploy"
kosli create flow "${flow_name}" \
--use-empty-template \
--description="Change Freezes for ${ENVIRONMENT}" \
> /dev/null 2>&1
echo "${flow_name}"
}
begin_trail()
{
local flow_name=$1; shift
local trail_name=$1; shift
kosli begin trail "${trail_name}" --flow="${flow_name}"
}
attest() {
local flow_name=$1; shift
local trail_name=$1; shift
local name=$1; shift
local reason=$1; shift
kosli attest generic --name "${name}" --flow "${flow_name}" --trail "${trail_name}" --description "${reason}"
}
get_nodeploy_tag()
{
local ENVIRONMENT=$1; shift
kosli get env "${ENVIRONMENT}" --output json | jq -r .tags.nodeploy
}
main()
{
check_arguments "$@"
case ${ACTION} in
on)
echo "Setting nodeploy for ${ENVIRONMENT}"
local trail_name
local now
now=$(date +"%Y-%m-%dT%H.%M.%S")
trail_name="${now}"
kosli tag env "${ENVIRONMENT}" --set nodeploy="${trail_name}"
flow_name=$(create_flow "${ENVIRONMENT}")
begin_trail "${flow_name}" "${trail_name}"
attest "${flow_name}" "${trail_name}" "nodeploy-on" "${REASON}"
;;
off)
echo "Removing nodeploy for ${ENVIRONMENT}"
local trail_name
trail_name=$(get_nodeploy_tag "${ENVIRONMENT}")
if [ "${trail_name}" == "null" ] ; then
echo "No nodeploy tag found for ${ENVIRONMENT}"
exit 1
else
kosli tag env "${ENVIRONMENT}" --unset nodeploy
flow_name=$(create_flow "${ENVIRONMENT}")
attest "${flow_name}" "${trail_name}" "nodeploy-off" "${REASON}"
fi
;;
assert)
echo -n "Checking nodeploy for ${ENVIRONMENT}: "
local nodeploy
nodeploy=$(get_nodeploy_tag "${ENVIRONMENT}")
if [ "${nodeploy}" == "null" ] ; then
echo "ok."
else
echo "nodeploy='${nodeploy}'"
exit 1
fi
;;
*)
print_help
exit 1
;;
esac
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment