Search code examples
jenkinsgroovy

How to retrieve Jenkins environment from Groovy script?


I am setting a Jenkins. I am programming with my pipeline using Global Pipeline Libraries to be able to increase reusability. Scripts are object oriented and in Groovy. Information about the concept can be found there

I don't manage to retrieve the Jenkins specific environment using my library script. I would like for instance to access:

  • Build_ID
  • Build_Number
  • JOB_Name
  • Workspace_path

I tryied to use env.WORKSPACE but it is returning a NULL. I manage to retrieve it directly in the pipeline but this is not my goal.

I am using Jenkins 2.303.1.


Solution

  • Depending on how you write your scripts, you might need to inject the Jenkins environment. For example, if you go for a more object oriented way

    // vars/whatever.groovy
    import ...
    
    @Field
    def myTool = new MyTool(this)
    
    // src/.../MyTool.groovy
    import ...
    
    class MyTool {
        private final jenkins
    
        MyTool(jenkins) {
            this.jenkins = jenkins
        }
    
        def echoBuildNumber() {
            this.jenkins.echo(this.jenkins.env.BUILD_NUMBER)
        }
    }
    
    // Jenkinsfile
    @Library(...)
    node {
        echo env.BUILD_NUMBER             // echoes build number
        whatever.myTool.echoBuildNumber() // echoes build number
    }