Skip to content

Instantly share code, notes, and snippets.

@tennox
Last active November 23, 2021 05:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tennox/cd8d4b901775f379d74287fa85f924c3 to your computer and use it in GitHub Desktop.
Save tennox/cd8d4b901775f379d74287fa85f924c3 to your computer and use it in GitHub Desktop.
Use code from GitLab environment variable safely in bash and remote SSH
.ssh_deploy_template: &ssh_deploy_template
# TEMPLATE - see https://docs.gitlab.com/ee/ci/yaml/README.html#anchors
# ...
# Here's the magic to get the code from the GitLab variable into a bash variable and then even executed on an SSH session
script:
# Put gitlab variable into shell variable to improve quote handling
- CMD=$SCRIPT_CMD
# Print for debugging
- echo -e "Executing:\n$CMD"
- CMD="set -e; cd $SSH_DIR; $CMD" # 'set -e' = stop on error
# redirect variable to stdin of ssh bash (the -x causes bash to print each command)
- ssh -p $SSH_PORT $USERNAME@$SSH_HOST "bash -x" <<< "$CMD"
deploy to server:
<<: *ssh_deploy_template # Merge the contents of the 'ssh_deploy_template' alias
# ...
variables:
SSH_DIR: '/srv/app/'
SCRIPT_CMD: |
echo "Double quotes are safe"
echo 'Single quotes are safe'
echo Code executions are safe - `whoami`@`hostname` $$(date)
# the '$$' is needed as otherwise GitLab itself tries variable substitution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment