I m trying to define a agent in a jenkinsfile once, but use it in multiple stages without needing to fully declare it for each stage. As can be seen, I am using a stage to figure out which docker image to use and then setting a global to use in the agent statement, which works fine and if I put the agent statement in each stage it works as desired. This however, seems ineffcient and not very maintainable if I need to modify the agent s args statement or similar. I want to do something similar to below:
def imageURI = ""
def myagent = docker {
image "$imageURI"
args "--user 1000:1000 --name ${env.BUILD_NUMBER}_${env.jobName}"
}
pipeline {
agent none
stages {
stage ("Once use agent") {
agent {
docker {
image "python:3.5-apline"
}
}
steps {
script {
imageURI = sh "command to get image URI"
}
}
stage ("Build" ) {
agent = myagent
steps {
sh "build code"
}
stage ( "Run Unit Test" ) {
parallel {
stage ( "UT 1" ) {
agent = myagent
steps {
sh "run unit test 1"
}
}
stage ( "UT 2" ) {
agent = myagent
steps {
sh "run unit test 2"
}
}
}
}
}
}
Using suggestion from comment, I m getting farther. But now the agent s image string is getting evaluated before it s set. With below, I would need some way to set the image variable or a way to defer the variable s evaluation
def imageURI = ""
pipeline {
agent {
docker {
image "$imageURI"
args "--user 1000:1000 --name ${env.BUILD_NUMBER}_${env.jobName}"
}
}
stages {
stage ("Once use agent") {
agent {
docker {
image "python:3.5-apline"
}
}
steps {
script {
imageURI = sh "command to get image URI"
}
}
stage ("Build" ) {
steps {
sh "build code"
}
stage ( "Run Unit Test" ) {
parallel {
stage ( "UT 1" ) {
steps {
sh "run unit test 1"
}
}
stage ( "UT 2" ) {
steps {
sh "run unit test 2"
}
}
}
}
}
}