Is it possible to get a dynamic docker image for an agent?

Hi there :wave:

I have a pipeline that uses a docker image.
I can specify the docker image name by hand, but I would like to get the right image name automatically, i.e. the docker image label is the branch name…
This way, I wouldn’t have to write one pipeline per branch, all the branches would use the same, as the docker image name would be deducted from the branch name.
I tried:

pipeline {
    environment {
        BRANCH_NAME = "${GIT_BRANCH.split('/').size() > 1 ? GIT_BRANCH.split('/')[1..-1].join('/') : GIT_BRANCH}"
        DOCKER_IMAGE_NAME = "my_repo/my_image_name:$BRANCH_NAME"
    }
    agent {
        docker {
            image "${env.DOCKER_IMAGE_NAME}"
            label 'ubuntu'
        }
    }
[...]
}

But that gives me null as the value of ${env.DOCKER_IMAGE_NAME}.

What did I do wrong, or is it even possible?

Thanks.

As far as I understand from the declarative Pipeline docs in my Jenkins:

BRANCH_NAME

For a multibranch project, this will be set to the name of the branch being built, for example in case you wish to deploy to production from master but not from feature branches; if corresponding to some kind of change request, the name is generally arbitrary (refer to CHANGE_ID and CHANGE_TARGET).

1 Like

I’m pretty sure environment is run after an agent is picked, because you can actualy do sh() statements in environment.

But yes, you have access to groovy, so for an existing env variable it should be fine.

You could also make a function at the top of your pipeline

def getBranchName() {
   return "${GIT_BRANCH.split('/').size() > 1 ? GIT_BRANCH.split('/')[1..-1].join('/') : GIT_BRANCH}"
}

pipeline {
    environment {
        BRANCH_NAME = getBranchName()
    }
    agent {
        docker {
            image "my_repo/my_image_name:${getBranchName()}"
            label 'ubuntu'
        }
    }
[...]
}

Hypothetically

1 Like

Thanks a lot, folks :pray:
Gavin’s solution worked perfectly, I’ll try Mark’s solution tomorrow morning.
Time to hit the bed.

I assume with the function for image. I totally missed that when i was rushing copy and pasting

Yes indeed. :wink:

def getBranchName() {
   return "${GIT_BRANCH.split('/').size() > 1 ? GIT_BRANCH.split('/')[1..-1].join('/') : GIT_BRANCH}"
}
pipeline {
    environment {
        BRANCH_NAME = getBranchName()
    }
    agent {
        docker {
            alwaysPull true
            image "gounthar/jenkinsci-docker-android-base:${BRANCH_NAME}"
            label 'ubuntu'
        }
    }

@MarkEWaite solution is also working for me, and it’s simpler:

pipeline {
    agent {
        docker {
            alwaysPull true
            image "gounthar/jenkinsci-docker-android-base:${BRANCH_NAME}"
            label 'ubuntu'
        }
    }