Devops Tutorial 29 - Parameterize jenkins pipeline jobs (part 1)
What you will Learn:
Parameterize pipeline jobs (using pipeline syntax)
Parameterize pipeline jobs (using pipeline syntax)
Let us see how to pass different parameters to the same job. Let us create a new pipeline job
Under the pipeline section, we can see ‘Pipeline Syntax’ link as shown below
Open this link in a new window. Click ‘Snippet Generator’ option as shown below. We can use this option to generate pipeline script snippet
Click ‘Sample Step’ dropdown that you see above, you would see ‘properties: Set job properties’ as one of the dropdown option
Select this option
Select the checkbox ‘This project is parameterized’
Click ‘Add Parameter’ dropdown. You would see various parameter types as shown below
Select ‘Choice Parameter’, below section comes up
We will put a choice of selecting branches. Now in one of our previous repositories, we had created 2 branches (main, feature_1), see below
So let us enter the below details in Name, Choices and Description field
At the bottom of above section, we would see ‘Generate Pipeline Script’ button
Click it, the snippet gets generated
Copy this snippet and paste it in pipeline job
We will now add simple stage in the script as shown below
Next, the choice parameter name that we have defined is ‘branches’
Users can access the parameters at runtime using interpolation. So in line#8, we are printing a message and this message will also have the branch name that the user will select
Note: params is a built-in object
Next, we will checkout the branch selected by the user by using same parameter. To do that, copy the git url as shown below
Paste it as shown below in line#9 along with the parameter name
git url: 'https://github.com/W2AGit/JenkinsPipelineAsACode', branch: "${params.branches}"
Below is entire code:
properties([parameters([choice(choices: ['master', 'feature_1'], description: 'Select desired branch to build', name: 'branches')])])
node{
stage('checkout from github') {
echo "checking-out from branch ${params.branches}"
git url: 'https://github.com/W2AGit/JenkinsPipelineAsACode', branch: "${params.branches}"
}
}
Apply and Save
Click ‘Build Now’ (first time you will not see ‘Build with parameters’).
We see an error as shown below “Couldn't find any revision to build. Verify the repository and branch configuration for this job.”
In the next article we will see how to resolve this error.
Thank you for reading!