In a declarative jenkins pipeline - can I set the agent label dynamically?

前端 未结 6 1049
-上瘾入骨i
-上瘾入骨i 2020-12-01 14:18

Is there a way to set the agent label dynamically and not as plain string?

The job has 2 stages:

  1. First stage - Runs on a \"master\" agent, always. At t
6条回答
  •  情书的邮戳
    2020-12-01 14:26

    Here is how I made it: mix scripted and declarative pipeline. First I've used scripted syntax to find, for example, 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"
                }
            }
        }
    }
    

提交回复
热议问题