Home > Mobile >  Jenkins scripted pipeline environment variable
Jenkins scripted pipeline environment variable

Time:10-29

I'm using the Jenkins scripted pipeline and since the last update I get a new warning, which I want to silence, here is an MWE:

// FROM https://jenkins.io/doc/pipeline/examples/#parallel-multiple-nodes

def labels = []

if (Host == 'true') {
    labels.add('<host-slavename>')
}

def builders = [:]

for (x in labels) {
    def label = x

    builders[label] = {
        ansiColor('xterm') {
            node(label) {
                stage('cleanup') {
                    deleteDir()
                }
                stage('build') {
                    def timestamp = sh (script: 'echo -n `(date  %Y%m%d%H%M%S)`', returnStdout: true)

                    withCredentials([string(credentialsId: 'TEST_PASSWORD', variable: 'PASSWORD')]){

                        sh """
                            logger \
                            TEST_1 "${PASSWORD}" TEST_2 \
                            TEST_3 $timestamp TEST_4
                        """

                        sh '''
                            logger \
                            TEST_1 "$PASSWORD" TEST_2 \
                            TEST_3 $timestamp TEST_4
                        '''
                        
                    }
                }
            }
        }
    }
}

parallel builders

the first sh block returns

Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
         Affected argument(s) used the following variable(s): [PASSWORD]
         See https://jenkins.io/redirect/groovy-string-interpolation for details.
  logger TEST_1 **** TEST_2 TEST_3 20211029074911 TEST_4

which at least prints the timestamp and the password (it's censored, but works), but raises the warning.

the second sh block returns

  logger TEST_1 **** TEST_2 TEST_3 TEST_4

So no warning, but also no timestamp.

Is there a way to write a scripted pipeline that shows no warning, but still the timestamp?

CodePudding user response:

The warning occurs when you use Groovy string interpolation in the first sh step like "${PASSWORD}" for the reasons explained in Interpolation of Sensitive Environment Variables.

That's why you should always let the shell resolve environment variables as you correctly do in the 2nd sh step.

To use non-environment variables like timestamp, convert them to environment variables by wrapping the sh step in withEnv step:

withEnv(["timestamp=$timestamp"]) {
    sh '''
        logger \
        TEST_1 "$PASSWORD" TEST_2 \
        TEST_3 $timestamp TEST_4
    '''
}

This limits the scope of the environment variable to the withEnv block.

Alternatively you could add a member to the env map:

env.timestamp = sh (script: 'echo -n `(date  %Y%m%d%H%M%S)`', returnStdout: true)

sh '''
    logger \
    TEST_1 "$PASSWORD" TEST_2 \
    TEST_3 $timestamp TEST_4
'''
  • Related