Skip to content

Instantly share code, notes, and snippets.

@lzkill
Created December 21, 2021 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lzkill/bd6ec1c8eb3ba0a6b63fe4ae08caa683 to your computer and use it in GitHub Desktop.
Save lzkill/bd6ec1c8eb3ba0a6b63fe4ae08caa683 to your computer and use it in GitHub Desktop.
Create env vars on a GitLab project reading from a file
#!/usr/bin/env bash
set -Eeuo pipefail
trap cleanup SIGINT SIGTERM ERR EXIT
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd -P)
usage() {
cat <<EOF
Usage: $(basename "${BASH_SOURCE[0]}") [-h] [-v] [-u] [-e environment] -f env_file -t gitlab_target_url -T gitlab_access_token
Posts env vars to a target on GitLab (project, group or instance).
Available options:
-h, --help Print this help and exit
-v, --verbose Print script debug info
-u, --update Update vars
-e, --environment Gitlab environment
-f, --file Env file
-t, --target GitLab target url
-T, --token GitLab access token
EOF
exit
}
cleanup() {
trap - SIGINT SIGTERM ERR EXIT
# script cleanup here
}
setup_colors() {
if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
NOFORMAT='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' BLUE='\033[0;34m' PURPLE='\033[0;35m' CYAN='\033[0;36m' YELLOW='\033[1;33m'
else
NOFORMAT='' RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW=''
fi
}
msg() {
echo >&2 -e "${1-}"
}
die() {
local msg=$1
local code=${2-1} # default exit status 1
msg "$msg"
exit "$code"
}
parse_params() {
# default values of variables set from params
method='POST'
environment='*'
file=''
target=''
token=''
while :; do
case "${1-}" in
-h | --help) usage ;;
-v | --verbose) set -x ;;
--no-color) NO_COLOR=1 ;;
-u | --update) method='PUT' ;; # example flag
-e | --environment)
environment="${2-}"
shift
;;
-f | --file)
file="${2-}"
shift
;;
-t | --target)
target="${2-}"
shift
;;
-T | --token)
token="${2-}"
shift
;;
-?*) die "Unknown option: $1" ;;
*) break ;;
esac
shift
done
args=("$@")
# check required params and arguments
[[ -z "${file-}" ]] && die "Missing required parameter: file"
[[ -z "${target-}" ]] && die "Missing required parameter: target"
[[ -z "${token-}" ]] && die "Missing required parameter: token"
return 0
}
parse_params "$@"
setup_colors
# script logic here
while IFS='=' read -r key value
do
var_key="$key"
url="$target"
if [ "$method" == "PUT" ]; then
url+="/$var_key"
fi
# Removes leading and trailing spaces
value=$(echo $value)
curl --request $method --header "PRIVATE-TOKEN: $token" \
"$url" \
--form-string "key=$var_key" \
--form-string "value=$value" \
--form-string "environment_scope=$environment"
echo
done < "$file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment