Reputation: 351
I have a pipeline and it's run for three different branches(dev
/uat
/master
). Some parameters change for each branch hence they are hardcoded for each environment resulting in three Jenkinsfile
s (one for each environment).
My second solution is to have three different properties file based on environment. A single Jenkins job will trigger the Jenkins jobs but based on branch name (which I will pick up from GitHub webhook trigger).
My Jenkinsfile
has an environment variable whose assignment looks like below:
myJenkinsJob.jenkinsfile
serviceAccountName = sh(returnStdout: true, script: "awk -F= '{$1 ~ /serviceAccountName/ ; gsub($1"=","") ; print}' dev.properties").trim()
dev.properties
file looks like this:
[email protected]
This evaluates to the value mentioned in the properties file. [email protected]
.
Does anyone has any better/easier alternative? Some plugin which can read the parameters passed in file without going through all sh
commands for assignments in environment/parameters block?
Upvotes: 1
Views: 4804
Reputation: 1781
You can use one Jenkinsfile for all branches and add an init stage to setup your variables according the branch name, using the BRANCH_NAME
environment variable :
stage ('Init') {
steps {
script {
switch(env.BRANCH_NAME) {
case 'dev':
serviceAccountName = '[email protected]'
break
case 'uat':
serviceAccountName = '[email protected]'
break
case 'master':
serviceAccountName = '[email protected]'
break
default:
error('Unexpected branch name')
}
}
}
}
If you want to use a properties file you can use the readFile syntax or use a YAML and use the readYaml which can be easier to parse the retrieved value.
Example :
dev.yml
file can look like this :
service-account-name: [email protected]
And then using readYaml
in your pipeline :
def devData = readYaml file: 'dev.yml'
def serviceAccountName = devData.service-account-name
For all the environment variables Jenkins supplies see the page https://your.jenkins.host:port/env-vars.html
.
Upvotes: 4