jenkinsjenkins-pipelinejenkins-shared-libraries

Jenkinsfile environment variable from shared library not working


I have a Bitbucket project with a growing number of repositories, each has a Jenkinsfile that pulls the same docker image to validate a file pushed to Bitbucket.

The issue is that for whatever reason I cannot use a 'latest' tag on my docker image so every file has a docker image with version number.

To get around this I found this article where a shared library is used to return a value to set an environment variable, to be used in the 'image' command in my Jenkinsfile. However, when Ivrun my pipeline the version number used on my docker image shows as null. So something isn't working and I'm unsure what.

This is the top part of my Jenkinsfile:

@Library(['toolbox','library']) _
pipeline {
    environment {
        IMAGE_VERSION = getImageVersion()
    }
    agent {
        docker {
            image "dockerhub.mycompany.net/docker-repo/validator:${env.IMAGE_VERSION}"
            args '-u root -v /var/run/docker.sock:/var/run/docker.sock'
        }
    }

This is the in the vars directory of my 'library' (This is a Folder level shared library)

getImageVersion.groovy:

def call() { return '1.0.25' }

But running the pipeline I see this output:

`

Error: No such object: dockerhub.mycompany.net/docker-repo/validator:null `

The Jenkins output shows that the library has been loaded. I'm unsure if the shared library is not returning the value or if I am using the environment variable incorrectly.

Does anyone have an idea the issue?


Solution

  • There is no well defined order in which different sections and directives are evaluated in a declarative pipeline, so I guess you've discovered that agent is evaluated before environment. Maybe there is a more "declarative" solution to it, but this should work:

    @Library(['toolbox','library']) _
    def imageVersion = getImageVersion()
    pipeline {
        agent {
            docker {
                image "dockerhub.mycompany.net/docker-repo/validator:${imageVersion}"
                args '-u root -v /var/run/docker.sock:/var/run/docker.sock'
            }
        }