1

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 jenkins@buildhost.example.com'

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

emmdee
  • 1,935
  • 9
  • 35
  • 56

1 Answers1

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.

Patrice M.
  • 213
  • 1
  • 7
  • 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 = '...'` – emmdee Dec 12 '18 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. – Patrice M. Dec 13 '18 at 04:21