Home > Net >  How to do I user an environmental variable as a parameter in Jenkins
How to do I user an environmental variable as a parameter in Jenkins

Time:10-22

I am trying to write a Jenkins pipeline that calls a Python script. I would like to use the userId of the Jenkins user as an argument when calling the pipeline script. At the moment this looks something like:

wrap([$class: 'BuildUser']) {
           String user = env.BUILD_USER_ID     
  }
                     
sh "sshpass -p ${password} ssh -o StrictHostKeyChecking=no ${user}@${NODE} python3 git_handler.py ${user} ${password} ${remoteRepository} ${localDirectory} ${branch}" 

However, I receive a message saying: "java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.ErrorStep.message expects class java.lang.String but received class groovy.lang.MissingPropertyException".

When I print the variable $(user) I receive the correct userId. Why can I not pass it as a parameter?

(The other four parameters I am taking as user input before building the pipeline, and they all work correctly).

CodePudding user response:

Define the String user = '' before the pipeline syntax starts.

and assign the value like user = env.BUILD_USER_ID and use that user env anywhere in the script.

eg.

String user = ''

pipeline {
  agent any 

  stages {

  }
}

CodePudding user response:

I have solved the problem.

Any variable declared in wrap([$class: 'BuildUser']) { } can only be used there.

I modified the code to:

 wrap([$class: 'BuildUser']) {
                     String user = env.BUILD_USER_ID 
                     sh "sshpass -p ${password} ssh -o StrictHostKeyChecking=no ${user}@${NODE} python3 git_handler.py ${user} ${password} ${remoteRepository} ${localDirectory} ${branch}" 
                    
                  }

And it now works as intended.

  • Related