Q:

Conditional agent in Jenkins

I'm trying to set a conditional agent in Jenkins defined through the branch such as:
cloud = myconditional()
    pipeline {
    agent {
        kubernetes {
            cloud cloud
        }
    }

and, the function myconditional is defined in a library /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
...

But I get Branch null.
Other way using 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

But I get: org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method hudson.plugins.git.BranchSpec getName and i don't have permissions to change the Jenkins configuration.
I try to print the environment vars but I get this:
def call() {
    sh 'env > env.txt'
    sh 'cat env.txt'
    ....

I have got: org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing
My question is, how can i get the actual branch out of the pipeline{}?
Thanks a lot

A:

If you are using Jenkins Multibranch Pipeline, you can obtain the branch name by using the following variable.

env.BRANCH_NAME

You can use the following conditional:
if ("${BRANCH_NAME}" != "master" ) {
     ...
} else {
     ...
}

