2

I would like to make my long "ssh" command reusable as a simple variable throughout my pipeline. To do this, it would be nice to declare my hostname in a var, then use that var in another var declaration to build the final command:

environment { BUILDHOST = 'buildhost.example.com' SSHCMD = 'ssh -o StrictHostKeyChecking=no jenkins@${env.BUILDHOST}' } 

So conceptually in something like this:

pipeline { agent any environment { BUILDHOST = 'buildhost01.example.com' SSHCMD = 'ssh -o StrictHostKeyChecking=no jenkins@${env.BUILDHOST}' } stages { stage('SSH Testing') { steps { sshagent ( ['jenkins_ssh']) { sh ''' $SSHCMD uname -a ''' } } } stage('Example Test') { steps { sshagent ( ['jenkins_ssh']) { sh ''' $SSHCMD /run/something.sh ''' } } } } } 

It works fine when I declare the var without any substitutions: SSHCMD = 'ssh -o StrictHostKeyChecking=no [email protected]'

but I can't seem to nest together the variables. Any way to do this?

1 Answer 1

0

This should work. However, you need to use double-quotes for String interpolation:

pipeline { agent any environment { BUILDHOST = 'buildhost01.example.com' SSHCMD = "ssh -o StrictHostKeyChecking=no jenkins@${env.BUILDHOST}" // <<< double-quotes } stages { stage('SSH Testing') { steps { sshagent ( ['jenkins_ssh']) { sh """ // <<< double-quotes $SSHCMD uname -a """ } } } stage('Example Test') { steps { sshagent ( ['jenkins_ssh']) { sh """ // <<< double-quotes $SSHCMD /run/something.sh """ } } } } } 

See also this answer.

2
  • Works. I didn't try the exact snippet you showed here because I wanted double quotes around the declaration of SSHCMD since it interpolates the variable (just for safety). Works fine like that so I'm sticking with it. ex... SSHCMD = "..." instead of SSHCMD = '...' Commented Dec 12, 2018 at 20:49
  • Yes, sorry I forgot that top one which was your specific ask. I have edited y answer for completeness. Thanks for accepting. Commented Dec 13, 2018 at 4:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.