首页 > 解决方案 > Jenkins 中的条件代理

问题描述

我正在尝试在通过分支定义的 Jenkins 中设置条件代理,例如:

cloud = myconditional()
    pipeline {
    agent {
        kubernetes {
            cloud cloud
        }
    }

并且,该函数myconditional在库中定义/vars/myconditional.groovy

def call() {
    def cloud = "clusterB"
    echo "Branch ${env.GIT_BRANCH}"
    if ("${env.GIT_BRANCH}" != "master") {
       echo "use clusterA"
       cloud = "clusterA"
    }else{
        echo "use clusterB"
    }
    return cloud
...

但我明白了Branch null

其他使用方式scm

def getGitBranchName() {
    return scm.branches[0].name
}

def call() {
    def cloud = "clusterB"
    def branch = getGitBranchName()
    echo "Branch ${branch}"
    if (branch != "master") {
       echo "use clusterA"
       cloud = "clusterA"
    }else{
        echo "use clusterB"
    }
    return cloud

但我明白org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method hudson.plugins.git.BranchSpec getName了:而且我无权更改 Jenkins 配置。

我尝试打印环境变量,但我得到了这个:

def call() {
    sh 'env > env.txt'
    sh 'cat env.txt'
    ....

我有:org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing

我的问题是,我如何才能将实际的分支从管道中取出{}?

非常感谢

标签: gitjenkins

解决方案


如果您使用的是 Jenkins Multibranch Pipeline,则可以使用以下变量获取分支名称。

env.BRANCH_NAME

您可以使用以下条件:

if ("${BRANCH_NAME}" != "master" ) {
     ...
} else {
     ...
}

推荐阅读