0

I am currently working on a shell script that is used to build docker images and restart containers running on the remote host. below is the stripped down version of the code.

#!/bin/bash -xe
# usages: ./deploy.sh [PROJECT_REPO] [DOCKER_IMAGE] [TARGET_HOST] [KEYPAIR_PATH]
PROJECT_REPO=$1
DOCKER_IMAGE=$2
TARGET_HOST=$3
KEYPAIR_PATH=$4
PROJECT_DIR=$(echo $PROJECT_REPO | cut -d'/' -f 2 | cut -d '.' -f 1)
CONTAINER=$PROJECT_DIR
USER="ubuntu"
git clone $PROJECT_REPO
cd $PROJECT_DIR

if docker build -t $DOCKER_IMAGE .; then
        docker push $DOCKER_IMAGE
        if ssh -o StrictHostKeyChecking=no -i $KEYPAIR_PATH  $USER@$TARGET_HOST -yes DOCKER_IMAGE=$DOCKER_IMAGE CONTAINER=$CONTAINER '\
        docker pull $DOCKER_IMAGE && \
        docker stop $CONTAINER
        docker rm $CONTAINER
        docker run -d --name=$CONTAINER  $DOCKER_IMAGE'; then
                echo "success"
        else
                echo "Failure"  
                exit 1
        fi
else
        echo "Error during building image"
        exit 1
fi

I am trying to make this script generalized so that it can be used with different projects by running the script with details of a project (repository URL, docker image), But when I tried to run the script then I am getting error with the docker commands due to the values of environment variables DOCKER_IMAGE and CONTAINER being empty on remote hosts.

1
  • Note: ssh -yes is equivalent to ssh -y -e -s and has nothing to do with the word "yes". This comment is for users who (like me) wondered what "yes" is in context of ssh. Apr 19, 2018 at 5:17

1 Answer 1

1

For this simple script, using double quotes instead of single will populate the variables from the parent shell.

Of course, if your script contains strings or other expressions which should not be interpolated by the parent shell on the host where you start this script, those need to be escaped or otherwise neutralized. But you don't seem to have any of those here.

if ssh -o StrictHostKeyChecking=no -i $KEYPAIR_PATH  $USER@$TARGET_HOST -yes "\
        docker pull $DOCKER_IMAGE && \
        docker stop $CONTAINER
        docker rm $CONTAINER
        docker run -d --name=$CONTAINER  $DOCKER_IMAGE"; then
                echo "success"

Maybe also look into using a here document (so you can use both single and double quotes in the embedded script) and perhaps understanding when to quote things. This will work fine as long as your variables don't contain irregular whitespace or wildcard characters, but it's uncanny.

1
  • Examples of mixing single and double quotes without here document, escaping quotes etc. Apr 19, 2018 at 5:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .