Skip to content

Instantly share code, notes, and snippets.

@erickr
Last active July 20, 2022 11:16
Show Gist options
  • Save erickr/f273a487bbb15fc0be1fddd255254f10 to your computer and use it in GitHub Desktop.
Save erickr/f273a487bbb15fc0be1fddd255254f10 to your computer and use it in GitHub Desktop.
Publish a codemagic web build to an external host using scp/ssh
#!/usr/bin/env bash
# This will scp the web-build artifact + unzip it to a releasefolder.
# And symlink the releasefolder into the document root specified as target folder.
# It uses the codemagics build number to ensure a fresh folder is used for every deploy.
# Old releases will not be purged by this script.
# Example usage in the post-publish script
# $CM_BUILD_DIR/codemagic-publish-web.sh -b $BUILD_NUMBER -r releasefolder/releases -t public_html/current/public -h example@host -p web-web.zip
# Remember to add your ssh private key as an environment variable which ends with SSH_KEY. All variables with SSH_KEY suffix will be added to ssh agent automatically by codemagic.
while getopts b:r:t:h:p: flag
do
case "${flag}" in
b) buildNumber=${OPTARG};; # Passed from codemagics environment variables.
r) releaseFolder=${OPTARG};; # Folder to store the built web artifact and the unzipped release folders.
t) targetFolder=${OPTARG};; # Target where your host has its document root, this will be replaced with a symlink to the latest release.
h) host=${OPTARG};; # ssh-scp compatible host-definition such as user@host
p) package=${OPTARG};; # name of the built web artifact
*) exit;;
esac
done
echo "$CM_BUILD_OUTPUT_DIR";
echo "$buildNumber";
echo "$releaseFolder";
echo "$targetFolder";
echo "$host";
echo "$package";
remoteHomeDir=$(ssh "$host" -C pwd);
scp "$CM_BUILD_OUTPUT_DIR"/"$package" "$host":"$remoteHomeDir"/"$releaseFolder"/"$buildNumber".zip
ssh "$host" bash << EOF
unzip -o "$remoteHomeDir"/"$releaseFolder"/"$buildNumber".zip -d "$remoteHomeDir"/"$releaseFolder"/"$buildNumber"
ln -snf "$remoteHomeDir"/"$releaseFolder"/"$buildNumber"/web "$remoteHomeDir"/"$targetFolder"
EOF
@erickr
Copy link
Author

erickr commented Jul 20, 2022

it's a good practice to use set -e as a very first command in shell script. In this case if any command fails it won't continue to execute script and will finish with exit code 1 immediately.

Another helpful trick if you need need to run more commands on remote host is to use this:

ssh $host bash << EOF
  unzip -o $remoteHomeDir/$releaseFolder/$buildNumber.zip -d $remoteHomeDir/$releaseFolder/$buildNumber
  ln -snf $remoteHomeDir/$releaseFolder/$buildNumber/web $remoteHomeDir/$targetFolder
EOF

Thanks, both very good suggestions @mikhail-tokarev !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment