Is there a way to set the agent label dynamically and not as plain string?
The job has 2 stages:
My (not working) attempt looks like this:
pipeline { agent { label 'master' } stages { stage('Stage1') { steps { script { env.node_name = "my_node_label" } echo "node_name: ${env.node_name}" } } stage('Stage2') { agent { label "${env.node_name}" } steps { echo "node_name: ${env.node_name}" } } } }
The first echo works fine and "my_node_label" is printed. The second stage fails to run on an agent labeled "my_node_label" and the console prints:
There are no nodes with the label ‘null’
Maybe it can help - if I just put "${env}" in the label field I can see that this is a java class as it prints:
There are no nodes with the label ‘org.jenkinsci.plugins.workflow.cps.EnvActionImpl@79c0ce06’
The Jenkins Agent is a Pod provisioned by Kubernetes, with multiple containers which run the specified Docker images. The main container must be from jenkins/jnlp-slave or a compatible image. It's better to build your own image including the Dockerfile content from jenkins/docker-slave.
agent. The agent section specifies where the entire Pipeline, or a specific stage, will execute in the Jenkins environment depending on where the agent section is placed. The section must be defined at the top-level inside the pipeline block, but stage-level usage is optional.
The environment directive specifies a sequence of key-value pairs which will be defined as environment variables for the all steps, or stage-specific steps, depending on where the environment directive is located within the Pipeline.
Basically, declarative and scripted pipelines differ in terms of the programmatic approach. One uses a declarative programming model and the second uses an imperative programming mode. Declarative pipelines break down stages into multiple steps, while in scripted pipelines there is no need for this.
Here is how I made it: mix scripted and declarative pipeline. First I've used scripted syntax to find, for example, the branch I'm on. Then define AGENT_LABEL variable. This var can be used anywhere along the declarative pipeline
def AGENT_LABEL = null node('master') { stage('Checkout and set agent'){ checkout scm ### Or just use any other approach to figure out agent label: read file, etc if (env.BRANCH_NAME == 'master') { AGENT_LABEL = "prod" } else { AGENT_LABEL = "dev" } } } pipeline { agent { label "${AGENT_LABEL}" } stages { stage('Normal build') { steps { echo "Running in ${AGENT_LABEL}" sh "hostname" } } stage ("Docker build") { agent{ dockerfile { dir 'Dockerfiles' label "${AGENT_LABEL}" } } steps{ sh "hostname" } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With