Jenkins Pipeline build job parameter Syntax - jenkins

I was wondering if anyone can explain the following Jenkins groovy syntax for build job and parameter. I could not find any documentation to explain it.
There's this + syntax at the end of the parameter block with a function, I am wondering if there function is supposed to return value to replace the original parameters? Or just add to them?
Function
def some_function(a, b) {
build job: SomeJob,
parameters: [
string(name: 'p1', value: "..."),
...
] + some_other_function()
}
def some_other_function() {
...
return some_value
}

The operator + here is to append an element to a list in Groovy. If you write println([1] + 2) in Groovy you will get [1, 2]. You may try this on https://www.jdoodle.com/execute-groovy-online/.
And back to your original question, it's just to add the return value of some_other_function() to the parameters list. It's useful when you need to decide the parameters dynamically based on the job context. For example
def some_other_function() {
return string(name: 'tag', value: 'master' == env.GIT_BRANCH ? 'release':'dev')
}

Related

Using env variables in a Jenkinsfile function?

I'm triggering one Jenkins job from the other, all via Jenkinsfiles.
stage("Trigger another job")
{
build([job:"Job2", wait:true, propagate:true, parameters: [string(name:'branch_my',value:"${env.ghprbActualCommit}")]])
}
Note that parameter branch_my is sent to Job2. However, the pipeline Job2 needs to work even when branch_my is NOT defined, for example when it is triggered manually.
Jenkinsfile for Job2 looks like:
pipeline
{
// ...
steps
{
customBranches()
// etc...
}
}
def customBranches()
{
if ( env.branch_my != null)
{
sh "switch_to ${env.branch_my}"
}
}
However, the customBranches() if statement never evaluates to true. When I do
sh "echo 'Env branch_my is: ${env.branch_my} '"
I get Env branch_my is: some_value , which is OK, and if statement should evaluate to true - but it does not.
I tried adding ${} like so: if ( ${env.branch_my} != null), but that failed completely: No such DSL method "$" found.
What's wrong with my customBranches()?
Problem isn't the Jenkinsfile syntax, but the Jenkins job configuration: it must be labeled as "parametrized" in the GUI and a string parameter branch_my needs to be defined:
Note, the parameters can be added via the Jenkinsfile itself:
parameters { string(name: 'branch_my', defaultValue: 'master', description: '') }
However, this just adds the parameter to the GUI, so you end up with the same thing.

Active Choices Reactive Parameter does not gets selected when the Reference parameter is set from a parent job

I have 2 Jenkins Job, say ParentJob and ChildJob.
The ParentJob has a Active Choice Parameter, say ENV, with the below groovy script:
return[
'A','B','C',
]
The ChildJob also has a similar Active Choice Parameter, say ENV, with the same groovy script. Additionally, there is also an Active Choices Reactive Parameter, say ENV_URL with ENV as the Reference Parameter and with following groovy script:
if(ENV.equals("A")){
return ["https://a.com"]
}else if(ENV.equals("B")){
return ["https://b.com"]
} else {
return ["https://c.com"]
Now, I'm calling ChildJob from my ParentJob using a pipeline script. When I set ENV as "A" in my ParentJob, which internally calls ChildJob,
ParentJob pipeline code:
pipeline {
agent {
node {
}
}
stages {
stage('ChildJob') {
steps {
script {
JOB_NAME="ChildJob"
def myJob=build job: "${JOB_NAME}", parameters: [
string(name: 'ENV', value:"${ENV}")
]
}
The Active Choices Parameter for ENV in the ChildJob is set to A
However, the Active Choice Reactive Parameter ENV_URL is empty and IS NOT SET with the value "http://a.com"
Basically, would want the Active Choices Reactive Parameter to set a value based on the Reference Parameter which is set from a Parent job.
Any suggestions on how this can be achieved?
I don't think this is possible. The best option for you is to Pass the parameter from the parent Job.
JOB_NAME="ChildJob"
URL = getURLByEnv("$ENV") // Retrive the URL based on the Same logic in your child job.
build job: '$JOB_NAME', parameters:[
string(name: 'ENV', value: "$ENV"),
string(name: 'url', value: "$URL")
]

How do I reassign parameters in a Jenkins pipeline script?

I'm new to Jenkins and groovy scripting. I'm trying to reassign the parameters in the Jenkins script.
I tried the following
def reasignParams() {
if(params.B == '') {
params.B = params.A
}
}
pipeline{
parameters {
string(name: 'A', defaultValue: '1.1', description: "Master Value")
string(name: 'B', defaultValue: '', description: "Slave value")
}
}
After running the above Jenkins pipeline script (groovy), I ran into the following error
java.lang.UnsupportedOperationException
The alternative that I thought to this is as below
def reasignParams() {
if(params.B == '') {
def temp = params.A
# use temp variable instead of params.B; But this is inconvenient
}
}
I would like to learn if there is a way to reassign parameters in the Jenkins pipeline script? Any help would be greatly appreciated, Thanks in advance!
The params object in Jenkins Pipeline does not support write operations on its member variables. You can only initially assign them in the parameters directive (think of it like a constructor in that sense). If you want to reassign parameter values, then you do indeed need to make a deep copy like the following:
newParams = [:]
newParams.A = params.A

run 2 jobs with same jenkinsfile and different parameters

I want to configure 2 jobs in Jenkins that use the same jenkinsfile but the only difference is the parameters to these jobs.
for example:
create 2 jobs named: A and B that each one of them gets param of X.
in A the job get X as 1 and in B the X is 2.
I want to create it in this way instead of one job that has multi-checkbox because the jobs are independent and I don't want to leave any option to make mistakes.
How can I achieve that only via jenkinsfile?
I read about load jenkinsfile within other jenkinsfile but can't find a way to pass parameters.
How can I achieve this?
If you use Build with Parameters you can reference these declared parameters in the Jenkinsfile with this syntax ${PARAM}.
You could also declare a Choice Parameter named CHOICE in a declaritive pipeline it would look like this:
pipeline {
agent any
parameters {
choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')
}
stages {
stage('Example') {
steps {
echo "Choice: ${params.CHOICE}"
}
}
}
}
You would not need 2 jobs this way. It is the same job but it runs with different configurations for CHOICE.
This example is directly taken from the official docs:
https://www.jenkins.io/doc/book/pipeline/syntax/#parameters
my solution was:
in Jenkins file to set
environment {
X= getX(env.JOB_NAME)
Y= getY(env.JOB_NAME)
}
and create the following functions in the end of pipeline:
def getX(jobName)
{
if (jobName.contains("X1"))
{
return "X1";
}
else return "X2";
}
def getY(jobName)
{
if (jobName.contains("BLA"))
{
return "BLA1";
}
return "BLA2";
}

String interpolation and concatenation for Jenkinsfile

I am trying to setup a Jenkinsfile that gets a job to call other jobs, based on the parameters passed into itself.
Instead of having multiple when conditions, I'm thinking that it would be smarter (and manageable for future scaling) if the names of the jobs being called would ideally be concatenating a common prefix with the parameter being passed in, for example:
CICD_api-gateway
CICD_front-end
CICD_customer-service
I'm having difficulty mixing string interpolation with string concatenation to achieve this:
build job: 'CICD_"${params.SERVICE_NAME}"', wait : false
In Linux, we are able to use eval to achieve this. I'm not sure what the equivalent is in Jenkinsfile syntax.
The full code below:
pipeline {
agent any
parameters { string(name: 'SERVICE_NAME', defaultValue: '', description: 'Service being deployed.') }
stages {
stage('Build Trigger'){
steps{
echo "CICD_${params.SERVICE_NAME}"
build job: 'CICD_"${params.SERVICE_NAME}"', wait : false
}
}
}
}
Change it to be a Gstring from the beginning, no need for the single quotes:
build job: "CICD_${params.SERVICE_NAME}", wait : false

Resources