From 434c50264b4afa48579d23f7136413929420e1d8 Mon Sep 17 00:00:00 2001 From: Nils <34674720+nils-kt@users.noreply.github.com> Date: Thu, 22 Aug 2024 20:44:37 +0200 Subject: [PATCH] Improve shell script robustness and error handling - Added `set -euo pipefail` to ensure the script exits on errors, undefined variables, or failed pipelines. - Enhanced error handling for SSH agent start and key addition, with clear error messages. - Replaced `echo` with `printf` for more reliable and formatted output. - Introduced optional legacy RSA hostkey handling based on input parameters. - Improved overall script readability with clearer variable names and structured conditionals. --- entrypoint.sh | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index b854a54..3eff722 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,25 +1,41 @@ #!/bin/sh +# Exit the script on any error, undefined variable, or in a pipeline. +set -euo pipefail + +# Check if the remote path is empty. if [ -z "$(echo "$INPUT_REMOTE_PATH" | awk '{$1=$1};1')" ]; then - echo "The remote_path can not be empty. see: github.com/Burnett01/rsync-deployments/issues/44" + printf "Error: The remote_path cannot be empty. See: github.com/Burnett01/rsync-deployments/issues/44\n" exit 1 fi -# Start the SSH agent and load key. -source agent-start "$GITHUB_ACTION" -echo "$INPUT_REMOTE_KEY" | SSH_PASS="$INPUT_REMOTE_KEY_PASS" agent-add +# Start the SSH agent and load the key. +if ! source agent-start "$GITHUB_ACTION"; then + printf "Error: SSH agent could not be started.\n" + exit 1 +fi -# Add strict errors. -set -eu +if ! echo "$INPUT_REMOTE_KEY" | SSH_PASS="$INPUT_REMOTE_KEY_PASS" agent-add; then + printf "Error: SSH key could not be added.\n" + exit 1 +fi -# Variables. -LEGACY_RSA_HOSTKEYS="-o HostKeyAlgorithms=+ssh-rsa -o PubkeyAcceptedKeyTypes=+ssh-rsa" -LEGACY_RSA_HOSTKEYS=$([ "$INPUT_LEGACY_ALLOW_RSA_HOSTKEYS" = "true" ] && echo "$LEGACY_RSA_HOSTKEYS" || echo "") +# Optionally add Legacy RSA Hostkeys. +LEGACY_RSA_HOSTKEYS="" +if [ "$INPUT_LEGACY_ALLOW_RSA_HOSTKEYS" = "true" ]; then + LEGACY_RSA_HOSTKEYS="-o HostKeyAlgorithms=+ssh-rsa -o PubkeyAcceptedKeyTypes=+ssh-rsa" +fi +# Define variables. SWITCHES="$INPUT_SWITCHES" RSH="ssh -o StrictHostKeyChecking=no $LEGACY_RSA_HOSTKEYS -p $INPUT_REMOTE_PORT $INPUT_RSH" LOCAL_PATH="$GITHUB_WORKSPACE/$INPUT_PATH" DSN="$INPUT_REMOTE_USER@$INPUT_REMOTE_HOST" -# Deploy. -sh -c "rsync $SWITCHES -e '$RSH' $LOCAL_PATH $DSN:$INPUT_REMOTE_PATH" +# Perform deployment. +if ! sh -c "rsync $SWITCHES -e '$RSH' $LOCAL_PATH $DSN:$INPUT_REMOTE_PATH"; then + printf "Error: Deployment failed.\n" + exit 1 +fi + +printf "Deployment completed successfully.\n"