Eyal Solomon
Eyal Solomon

Reputation: 618

Run shell script inside ssh session inside Jenkinsfile

I'm trying to run a complete script while the ssh session is live instead of single commands.

Here is my current code:

sh "ssh -tt -o StrictHostKeyChecking=no ubuntu@IPV4_DNS uptime"
sh "ssh -v ubuntu@IPV4_DNS docker pull X:${BUILD_NUMBER}"
sh "ssh -v ubuntu@IPV4_DNS docker rm -f test"
sh "ssh -v ubuntu@IPV4_DNS docker run --name=test -d -p 3000:3000X:${BUILD_NUMBER}"

The desired code is something like this, but the following doesn't work:*

sh "ssh -tt -o StrictHostKeyChecking=no ubuntu@IPV4_DNS uptime"
sh ''' ssh -v ubuntu@IPV4_DNS docker pull X:${BUILD_NUMBER}
       && docker rm -f test && docker run --name=test -d -p 3000:3000X:${BUILD_NUMBER} 
'''

Upvotes: 0

Views: 814

Answers (1)

tripleee
tripleee

Reputation: 189317

ssh something here && something else && another one

runs something here in the ssh session, and something else and another one locally. You want to add quotes to pass the entire command line to ssh.

sh "ssh -tt -o StrictHostKeyChecking=no ubuntu@IPV4_DNS uptime"
sh """ssh -v ubuntu@IPV4_DNS 'docker pull X:${BUILD_NUMBER} &&
    docker rm -f test &&
    docker run --name=test -d -p "3000:3000X:${BUILD_NUMBER}"'
"""

I switched to triple double quotes instead of triple single quotes, assuming you want Jenkins to expand ${BUILD_NUMBER} for you.

The original question asked about Bash, but for the record, you are running sh here, not Bash. If you wanted to use Bash features in a Jenkinsfile, you can add a shebang #!/usr/bin/env bash or similar as the very first line of the command. But that's not necessary here; all these commands are simple and completely POSIX. (Maybe see also Difference between sh and bash)

Upvotes: 2

Related Questions