jenkins pipelines: shell script cannot get the upd

2019-07-30 14:39发布

问题:

In Jenkins, I want to get a user input and pass to a shell script for further use.
I tried to set as environment variable, but the shell script failed to get the latest value and the old value is echo.

pipeline {
    agent none
    environment{
        myVar='something_default'
    }

    stages {
        stage('First stage') {
            agent none
            steps{
                echo "update myVar by user input"
                script {
                    test = input message: 'Hello',
                    ok: 'Proceed?',
                    parameters: [
                        string(name: 'input', defaultValue: 'update it!', description: '')
                    ]
                    myVar = "${test['input']}"

                }
                echo "${myVar}"  // value is updated
            }
        }
        stage('stage 2') {
            agent any
            steps{
                echo "${myVar}" // try to see can myVar pass between stage and it output expected value
                sh("./someShell.sh") // the script just contain a echo e.g. echo "myVar is ${myVar}"
                                     // it echo the old value. i.e.something_default

            }
        }
    }
}

回答1:

You need to pass the variables between your stages as environment variables, e.g. like this:

stage("As user for input") {
    steps {
        env.DO_SOMETING = input (...)
        env.MY_VAR = ...
    }
}
stage("Do something") {
    when { environment name: 'DO_SOMETING', value: 'yes' }
    steps {
        echo "DO_SOMETING has the value ${env.DO_SOMETHING}"
        echo "MY_VAR has the value ${env.MY_VAR}"
    }
}


回答2:

The environment variables that we set in the pipeline Script will be accessible only within the script. So, even if you declare your variable as global, it will not work inside a shell script.

Only option I can think off is, pass as it as argument to the shell script

 sh("./someShell.sh ${myVar}")

EDIT: Updated Answer based on OP's query on Shell script for parsing input

LINE="[fristPara:100, secondPaa:abc]"
LINE=$(echo $LINE | sed 's/\[//g')
LINE=$(echo $LINE | sed 's/\]//g')
while read -d, -r pair; do
  IFS=':' read -r key val <<<"$pair"
  echo "$key = $val"
done <<<"$LINE,

"



回答3:

You have to declare the variable on a global scope so that both places refer to the same instance.

def myVal

pipeline { ... }