SomeBdyElse
SomeBdyElse

Reputation: 437

How to set branch-specific configuration in a Multibranch Pipeline

I have a Jenkins Multibranch Pipeline set up to build and deploy some code. Dependant on the branch, I would like to deploy the code to different machines and directories.

For any branch:
TARGET_HOST=user@ourtestingmachine
TARGET_HOST_KEY="… some key …"
TARGET_DIRECTORY="project/`encode $BRANCH_NAME`/"

For master, additionally:
TARGET_HOST=user@productionserver
TARGET_HOST_KEY="… some other key …"
TARGET_DIRECTORY="target_direcotory"

Where shall I store my TARGET_HOST configuration? I would like to avoid to version these settings together with our source code, as these settings might change independently.

My first try was to set environment variables in the configuration part of the Job, but could not find any settings within the Jenkins interface.

Ideas I considered so far:

Upvotes: 2

Views: 3477

Answers (1)

elou
elou

Reputation: 1282

You may use groovy code in your Jenkinsfile. Your Jenkinsfile may look like this:

def TARGET_HOST=""
def TARGET_HOST_KEY=""
def TARGET_DIRECTORY=""
node ('master') {
    stage('detect branch') {
        println("now parsing branch name:"+BRANCH_NAME)
        def branch=BRANCH_NAME
        // extract the information you need with regex
        def m=BRANCH_NAME=~ "branches/sprints/([0-9]{4})/(.*)"
        assert m instanceof java.util.regex.Matcher                                       
        if (!m) {    
            // no information match the regex, should be production
            m=BRANCH_NAME=~ "production"
            if (!m) {                                                         
                throw new RuntimeException("This branch is neather production nor recognized sprint.")
            }               
            TARGET_HOST="user@productionserver"
            TARGET_HOST_KEY="… some other key …"
            TARGET_DIRECTORY="target_direcotory"
        }
        else {
            // sprint branch matched
            TARGET_HOST="user@ourtestingmachine"
            TARGET_HOST_KEY="… some key …"
            TARGET_DIRECTORY="project-$m"
        }
    }
}

If you do not want to have this code in each Jenkinsfile, you may use a .groovy file which will be imported by the Jenkinsfile like this:

def func
stage('load script') {
    // Funktionen werden geladen
    checkout(..)
    func = load './jenkins/lib/build-functions.groovy'
}
func.setEnv(BRANCH_NAME)

Regards.

Upvotes: 1

Related Questions