Jenkins assign input to environment variable

Viewed 382

Trying to assign user input from 1 stage to use in another stage , thought to do it with env variables but cant figure it out

code so far :

environment {
    access_key =''
}
stages {
        stage('User input for Auth'){
            input {
                message 'enter access_key'
                parameters {
                    string 'access_key_input'
                    string 'secret_key_input'
                }
            }
            environment {
                access_key = sh(script:"echo ${access_key_input}", returnStdout: true).trim()
            }
            steps{
                sh "echo ${env.access_key}"
            }
        }
        stage("Build") {
            steps { 
                sh "echo ${env.access_key}"
               }
       }
}

logs :

+ echo XXX

+ echo XXX
XXX

+ echo null
null
1 Answers

You can assign the input to a global variable and then access that wherever you want.

def INPUT_PARAMS = null

pipeline {
    agent {
        node {
            label 'any'
        }
    }

    options {
        timestamps()
    }

    stages {
        stage('User input for Auth') {
            steps{
                script {
                    INPUT_PARAMS = input message: "enter access_key", parameters: [
                            string(description: 'Access key', defaultValue: '', name: 'access_key_input'),
                            string(description: 'Secret access key', defaultValue: '', name: 'secret_key_input') 
                        ]
                }
                sh "echo ${INPUT_PARAMS.access_key_input}"
            }
        }

        stage("Build") {
            steps { 
                sh "echo ${INPUT_PARAMS.access_key_input}"
            }
        }
    }
}

Input request

Input requested

Output

Started by user Praveen Premaratne
Replayed #152
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on devops-jenkins in /home/jenkins/workspace/Test
[Pipeline] {
[Pipeline] timestamps
[Pipeline] {
[Pipeline] stage
[Pipeline] { (User input for Auth)
[Pipeline] script
[Pipeline] {
[Pipeline] input
[2021-07-15T22:35:33.625Z] Input requested
[2021-07-15T22:35:43.540Z] Approved by Praveen Premaratne
[Pipeline] }
[Pipeline] // script
[Pipeline] sh
[2021-07-15T22:35:43.886Z] + echo a
[2021-07-15T22:35:43.886Z] a
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] sh
[2021-07-15T22:35:44.230Z] + echo a
[2021-07-15T22:35:44.230Z] a
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // timestamps
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Related