Reputation: 3646
I have a script with 2 ssh
commands. The SSH scripts uses SSH to log into a remote server and deletes docker images.
ssh [email protected] 'set -x &&
echo "Stop docker images" ;
sudo docker stop $(sudo docker ps -a -q) ;
sudo docker rmi -f $(sudo docker images -q) ;
sudo docker rm -f $(sudo docker ps -a -q)'
Note use of ;
to separate commands (we don't care if one or more of the commands fail).
The 2nd ssh
command uses SSH to log into the same server, grab a docker compose file and run docker.
ssh [email protected] 'set -x &&
export AWS_CONFIG_FILE=/somelocation/myaws.conf &&
aws s3 cp s3://com.somebucket.somewhere/docker-compose/docker-compose.yml . --region us-east-1 &&
echo "Get ECR login credentials and do a docker compose up" &&
sudo $(aws ecr get-login --region us-east-1) &&
sudo /usr/local/bin/docker-compose up -d'
Note use of &&
to separate commands (this time we do care if one or more of the commands fail as we grab the exit code i.e exitCode=$?
).
I don't like the fact I have to split this into 2 so my question is can these 2 sections of bash commands be combined into a single SSH call (with both ;
and &&
combinations)?
Upvotes: 1
Views: 243
Reputation: 21522
Although it is possible to pass a set of commands as a simple single-quoted string, I wouldn't recommend that, because:
I find it better to keep the scripts in separate files, then pass them to ssh
as standard input:
cat script.sh | ssh -T user@host -- bash -s -
Execution of several scripts is done in the same way. Just concatenate more scripts:
cat a.sh b.sh | ssh -T user@host -- bash -s -
If you still want to use a string, use a here document instead:
ssh -T user@host -- <<'END_OF_COMMANDS'
# put your script here
END_OF_COMMANDS
Note the -T
option. You don't need pseudo-terminal allocation for non-interactive scripts.
Upvotes: 2
Reputation: 32544
ssh [email protected] 'set -x;
echo "Stop docker images" ;
sudo docker stop $(sudo docker ps -a -q) ;
sudo docker rmi -f $(sudo docker images -q) ;
sudo docker rm -f $(sudo docker ps -a -q) ;
export AWS_CONFIG_FILE=/somelocation/myaws.conf &&
aws s3 cp s3://com.somebucket.somewhere/docker-compose/docker-compose.yml . --region us-east-1 &&
echo "Get ECR login credentials and do a docker compose up" &&
sudo $(aws ecr get-login --region us-east-1) &&
sudo /usr/local/bin/docker-compose up -d'
Upvotes: 0