Forked from tennox/gitlab-ci_script-from-variable.yml
Created
November 23, 2021 05:58
-
-
Save maprangzth/da6c4d8a6caf6136858652d32a6be436 to your computer and use it in GitHub Desktop.
Use code from GitLab environment variable safely in bash and remote SSH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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