Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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