Export build parameters into shared library - jenkins

This is an example of my Jenkinsfile:
properties([
parameters([
booleanParam(defaultValue: false, name: 'BuildAll', description: ''),
// lots of params here, some of them are Active Choice Plugin params...
])
])
pipeline {
agent any
stages {
stage ('Initialize') {
// code...
}
}
}
Now, is it posslible to export those parameters (that are enclosed inside "properties" section) into shared library?
Jenkins shared library: https://www.jenkins.io/doc/book/pipeline/shared-libraries/
I have lots of params and many similar projects and I would like simply to define parameters on one place and include them everywhere (DRY).

create deriveJobParams.groovy in vars folder with following code in shared library project.
def call() {
properties([
parameters([
booleanParam(defaultValue: false, name: 'BuildAll', description: ''),
[$class: 'ChoiceParameter', choiceType: 'PT_CHECKBOX',
description: 'Choose environment category.',
name: 'ENVIRONMENT',
script: [
$class: 'GroovyScript',
script: [sandbox: true, script: 'return ["QA", "DEV", "PROD"]']
]
]
])
])
}
In job Jenkinsfile, import the share library and call deriveJobParams()
#Library('my-library#branch or tag') _
// call deriveJobParams at beginning
deriveJobParams()
pipeline {
stages {
}
}

Related

How to add radio buttons in Jenkins using groovy when building a job using "Build with parameters"?

I am trying to add radio buttons in Jenkins instead of checkboxes when running Build with Parameters. In my existing code, I am getting checkboxes. What changes should I make in my existing code to get the radio buttons. Below is my groovy code:
def call(Map config = [:]) {
paramsList = []
paramsList << booleanParam(name: 'deployToDev', defaultValue: false, description: 'Set to true to deploy to Dev K8s Environment')
paramsList << booleanParam(name: 'deployToTest', defaultValue: false, description: 'Set to true to deploy to Test K8s Environment')
paramsList << booleanParam(name: 'deployToStage', defaultValue: false, description: 'Set to true to deploy to Stage K8s Environment')
properties([parameters(paramsList)])
}
Please find the below screenshot:
You can achieve that easily using the Extended Choice Parameter which has a built in support for all kinds of selection options including radio buttons.
You can use it as follows:
def call(Map config = [:]) {
paramsList = []
// You can also set the default value using the 'defaultValue' option
paramsList << extendedChoice(name: 'DeployTo', description: 'Select the environment to deploy to', type: 'PT_RADIO', value: 'Dev,Test,Stage', visibleItemCount: 5)
properties([parameters(paramsList)])
}
The result will look like:
You can also use the Active Choices plugin, which is a bit more complicated but has more configuration options, it will also allow you to generate the values from a groovy script.
For example:
properties([parameters(
[[$class: 'ChoiceParameter', name: 'DeployTo', choiceType: 'PT_RADIO', description: 'Select the environment to deploy to', script: [$class: 'GroovyScript', script: [classpath: [], sandbox: false, script: "return ['Dev','Test','Stage']"]]]]
)])

Jenkins "Git Parameter" plugin with "useRepository" option

I'm using "Git Parameter" plugin to allow users to pick branch\tag for configured repositories.
This plugin has "useRepository" option to allow linking with the configured repos in the "Pipeline script from SCM" option:
This assumes that i need to preconfigure some repos in the Jenkins pipeline (in the Jenkins UI) to be able to use "Git Parameter" plugin in the pipelines.
But i want to dynamically predefine list of repos from the pipeline code itself, without any configuration in the "Pipeline script from SCM" section.
Unfortunately this doesn't work.
I'm tried to add "checkout" block with "GitSCM" class before calling "gitParameter" but with no success.
Code example:
def app_components = [
BACKEND : ["NAME": "backend", "GIT": "ssh://git#xxx.local/_git/backend"],
FRONTEND : ["NAME": "frontend", "GIT": "ssh://git#xxx.local/_git/fronend"]
]
pipeline {
agent any
stages {
stage('Test') {
steps {
script {
dynamicParameters = []
app_components.eachWithIndex { name, components, index ->
checkout([
$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'CleanCheckout']],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'XXX', url: components.GIT]]
])
dynamicParameters << gitParameter(name: 'BRANCH_' + name, defaultValue: 'develop', quickFilterEnabled: true, type: 'PT_BRANCH_TAG', listSize: '10', useRepository: components.GIT)
}
def userInput = input(
id: 'userInput', message: 'Test message:?',
parameters: dynamicParameters
)
println(userInput);
}
}
}
}
Git parameters text fields are always empty:
Could you advice some solution in this scenario?
Play around with adding
gitParameter branchFilter: 'origin/(.*)',

How to add a build selector as a parameter?

I have two jobs:
Build job
Deployment job
I copy the artifacts (jars) generated in the first job to the second job and deploy them to an environment.
properties([
parameters(
[
string(
name: 'buildnumber',
description: 'Buildnumber to deploy'
),
choice(
name: 'env',
choices: ['qa', 'stage', 'prod'],
description: 'Environment where the app should be deployed'
)
]
)
])
node{
stage('Copy artifacts'){
copyArtifacts(projectName: 'my-demo-build-job/master', selector: specific(params.buildnumber))
}
stage('Deploy'){
sh 'Deploying to the specified environment '
}
}
With this I have to manually check the latest/successful builds and put that as a parameter. Is there a way so that we can get a dropdown with all the successful build sorted by build number as a selector from the other job?
You can use the Extended Choice Parameter Plugin for achieving what you want with the help of a groovy script.
You will need to define an extended choice parameter of type Single Select, as a Source for Value choose Groovy Script, and as a groovy script use something like the following:
def job = jenkins.model.Jenkins.instance.getItemByFullName('my-demo-build-job/master')
return job.builds.findResults{
it.result == hudson.model.Result.SUCCESS ? it.getNumber().toInteger() : null
}
This script will go over all the build of the configured job and filter out only the successful builds - which will be returned as the select-list options for the parameter.
The configuration in the pipeline will look like:
properties([
parameters([
extendedChoice(name: 'buildnumber', type: 'PT_SINGLE_SELECT', description: 'Buildnumber to deploy', visibleItemCount: 10, groovyScript:
'''def job = jenkins.model.Jenkins.instance.getItemByFullName('my-demo-build-job/master')
return job.builds.findResults { it.result == hudson.model.Result.SUCCESS ? it.getNumber().toInteger() : null }''',
choice(name: 'env', choices: ['qa', 'stage', 'prod'], description: 'Environment where the app should be deployed'),
])
])

Accessing jenkins env params from inside a GroovyScript in properties

I have a jenkins job:
properties([
parameters([
[$class: 'ChoiceParameter', choiceType: 'PT_CHECKBOX', description: '''The name of the image to be used.''', filterLength: 1, filterable: true, name: 'OS', randomName: 'choice-parameter-15413073438404172', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: true, script: ''], script: [classpath: [], sandbox: true, script: '''templates = [
"BB-Win7-x32-SP1",
"BB-Win7-x64-SP1",
"BB-Win10-x64-RS1",
"BB-Win10-x64-RS2",
"BB-Win10-x32-RS5"]
return templates''']]]])
])
....
....
Which is working and generates the checkbox property for the GUI as expected.
Now, I want to generate those options dynamically, based on a file in my workspace. For this, I need the workspace environment variable inside the groovy script. How can I do that?
Jenkins needs to figure out all the parameters before it runs a pipeline. So your problem, basically, boils down to "How can I run an (arbitrary) groovy script before I run a pipeline?"
There are two options for this:
As I mentioned, ActiveChoice plugin allows you to define a parameter that returns a script. Jenkins will then run the script (don't forget to approve it) in order to show you your "Build with parameters" page. Debugging this is notoriously hard, but this can go to great lengths.
Alternatively, you may want to run a scripted pipeline before you run the Declarative (main) one, as outlined e.g. in this answer. This may look a bit like this:
def my_choices_list = []
node('master') {
stage('prepare choices') {
// read the file contents
def my_choices = sh script: "cat ${WORKSPACE}/file.txt", returnStdout:true
// make a list out of it - I haven't tested this!
my_choices_list = my_choices.trim().split("\n")
}
}
pipeline {
parameters {
choiceParam('OPTION', my_choices_list)

Append to Job properties

My job parameters defined in job-dsl.groovy are overwritten by those defined in pipeline.
I am using job-dsl-plugin and Jenkins pipeline to generate Jenkins job for each git branch. Sine my code is stored in gitLab they require gitLab integration. I am providing that using gitlab-plugin. The problem is with the 'gitLabConnection' it looks like it can be only applied from inside the Jenkins pipeline.
So if in job-dsl I would do:
branches.each { branch ->
String safeBranchName = branch.name.replaceAll('/', '-')
if (safeBranchName ==~ "^release.*")
{
return
}
def branch_folder = "${basePath}/${safeBranchName}"
folder branch_folder
pipelineJob("$branch_folder/build") {
logRotator {
numToKeep 20
}
parameters {
stringParam("BRANCH_NAME", "${safeBranchName}", "")
stringParam("PROJECT_NAME", "${basePath}", "")
{
}
And then in my Jenkins pipeline I would add the 'gitLabConnection'
node('node_A') {
properties([
gitLabConnection('gitlab.internal')
])
stage('clean up') {
deleteDir()
}
///(...)
I have to do it like:
node('node_A') {
properties([
gitLabConnection('gitlab.internal'),
parameters([
string(name: 'BRANCH_NAME', defaultValue: BRANCH_NAME, description: ''),
string(name: 'PROJECT_NAME', defaultValue: PROJECT_NAME, description: '')
])
])
stage('clean up') {
deleteDir()
}
///(...)
So that my BRANCH_NAME and PROJECT_NAME are not overwritten.
Is there another way to tackle this ?
Is it possible to append the 'gitLabConnection('gitlab.internal')' to the properties in the Jenkins pipeline ?
Unfortunately it doesn't seem like there is a way to do this yet. There's some discussion about this at https://issues.jenkins-ci.org/browse/JENKINS-43758 and I may end up opening a feature request to allow people to "append to properties"
There are 2 ways for solving this. The first one uses only Jenkins pipeline code, but if you choose this path the initial job run will most likely fail. This initial fail will happen, because at the time of first job run, the pipeline creates Jenkins job parameters. Once the parameters are created, job will work.
Option '1' - using Jenkins pipeline Only.
In 'Pipeline Syntax'/'Snippet Generator' check:
'This project is parameterised'.
Add parameter(s) you need, and hit 'Generate Pipeline Script'. In my case I get:
properties([
gitLabConnection(gitLabConnection: 'my_gitlab_connection', jobCredentialId: '', useAlternativeCredential: false),
[$class: 'JobRestrictionProperty'],
parameters([
string(defaultValue: 'test', description: 'test', name: 'test', trim: false)
]),
throttleJobProperty(categories: [], limitOneJobWithMatchingParams: false, maxConcurrentPerNode: 0, maxConcurrentTotal: 0, paramsToUseForLimit: '', throttleEnabled: false, throttleOption: 'project')
])
Option '2' - It's more complicated but, also far more powerfull. The one I finally took, because of the issues described above.
Use Jenkins job DSL plugin - https://github.com/jenkinsci/job-dsl-plugin
Gitlab plugin works quite well with it https://github.com/jenkinsci/gitlab-plugin#declarative-pipeline-jobs

Resources