Reputation: 437
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:
Download the target settings from a trusted server (Partially suggested in this comment: Jenkins Multibranch Pipelines - Configuring properties in branches?)
Use two jobs: A first job to pull the Jenkinsfile from a git repository, set the environment variables and then call a second job to checkout, build and deploy the actual project.
Upvotes: 2
Views: 3477
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