Can a Jenkins Pipeline write/configure a separate Jenkins job? - docker

I've got a Jenkins pipeline that builds docker images and tags them with the git hash. I also have another parameterized Jenkins pipeline that takes in a couple of string/choice parameters for deployment of the docker images. I'd love for the build pipeline to append some strings to the choice parameters in the deployment pipeline, so that when a user runs the deployment pipeline, he/she is just presented with a list of recently successfully built docker images to choose from.
Anyone know how to do this?

One way would be for your first job to set an environment variable with the list of recent built image tabs (one per line).
See declarative pipeline environment directive.
Then, following "Dynamic Parameter in Jenkinsfile?", you can use an external function like:
#!/bin/groovy
def envs = loadEnvs();
properties([
parameters([
choice(choices: envs, description: 'Please select an image tag', name: 'Env')
])
])
That should be enough to build a choice parameter list.
"Pipeline: How to manage user inputs " (May 10th, 2017, two weeks ago) shows an alternative command, but not valid in the Declarative Pipeline syntax:
You have to use the input step to achieve it.
It will give you something like this :
stage 'promotion'
def userInput = input(
id: 'userInput', message: 'Let\'s promote?', parameters: [
[$class: 'TextParameterDefinition', defaultValue: 'uat', description: 'Environment', name: 'env'],
[$class: 'TextParameterDefinition', defaultValue: 'uat1', description: 'Target', name: 'target']
])
echo ("Env: "+userInput['env'])
echo ("Target: "+userInput['target'])

Related

How to get build number as a parameter for downstream job from upstream job with declarative pipeline code

I have Two jobs like one is CI jod & another one is CD. I want CI build number should use on CD number.. Can you please help me with declarative pipeline script to get build number as a parameter. here CI job is calling CD job.
Jenkins already provides a simple means to access the number of the current build using env.BUILD_NUMBER. So if you wanted to pass the build number of CI to the downstream job CD, you could do
build([
job : 'CD',
parameters: [
string(name: 'MAIN_BUILD_NUMBER', value: "${env.BUILD_NUMBER}")
]
])
Then in the CD job, declare a parameter like this:
parameters {
string(defaultValue: null, description: 'Build No', name: 'MAIN_BUILD_NUMBER')
}
You should then be able to use ${env.MAIN_BUILD_NUMBER} anywhere in your CD jobs' Jenkinsfile.

Parametrize Jenkins Pipeline for different jobs

I want to use the same pipeline from scm, and build them in few jobs with different test tags to run(passed as simple String parameter)
I found that i can do this with:
parameters {
string(name: 'param', defaultValue: 'Hello', description: 'How should I greet the world?')
}
I thought that i can change default value for each job there:
Parametrize build
But it is overriden by code from pipeline everytime.
Is there a way to pass this parameter( or maybe pass parameter directly in job in different way)?
Or i have to create diferent pipeline files for each value of this parameter?
Thanks
Kamil
I would suggest you to remove
parameters {
string(name: 'param', defaultValue: 'Hello', description: 'How should I greet the world?')
}
from the pipeline script and to use This project is parameterized when creating pipeline jobs instead. This way the pipeline script is same for all jobs, but your jobs can have different parameters.

How to retrieve job name in parameterized Jenkins Pipeline Project

I have a parameterized pipeline project with active choices parameter, where choice list is dynamically populated by groovy script. I need to retrieve and use current job name in the script. The following line works for me in Freestyle Projects:
def jobName = this.binding.jenkinsProject.name
However when I try to use it in Pipeline Project I get:
No such property: jenkinsProject for class: groovy.lang.Binding
In Retrieving Jenkins job name using groovy script in Active Choice Reactive Parameter it's stated that this has been resolved in Active Choices plugin v1.4. I'm using version 2.2.1 and the issue still persists. Is this property not available in Pipeline Project? Is there a workaround or an alternative?
If you trying to get the current build job name inside running job
There is a builtin env variable for it:
JOB_BASE_NAME
You can see list of available env variable in your Jenkins at
http://{hostname}/job/{jobname}/pipeline-syntax/globals
Jest replace hostname with your Jenkins address and jobname with some job you have in your Jenkins.
My Jenkins
Jenkins version: 2.176.2
Active Choices Plug-in: 2.2.1
Worked with pipeline job.
If you trying to do it in the parameters script I'm not sure that possible.
I faced the same issue and came up with a solution.
You can use Jenkins pipeline currentBuild variable, more about its properties - open page jenkins-server-url/jenkins/pipeline-syntax/globals on your Jenkins server
String currentJobParentFolderName = currentBuild.fullProjectName.split('/')[0]
String currentJobName = currentBuild.projectName
String paramValue = getParamValue(currentJobName)
properties([
buildDiscarder(logRotator(daysToKeepStr: '10')),
disableResume(),
parameters([
[$class: 'CascadeChoiceParameter',
name: 'PARAM',
choiceType: 'PT_SINGLE_SELECT',
description: 'param1',
filterLength: 1,
filterable: false,
randomName: 'choice-parameter-99999999999',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
'return ["Failed to get values"]'
],
script: [
classpath: [],
sandbox: false,
script:
"""return ['$paramValue']"""
]
]
]
])
])
timestamps {
job's main logic
}
private static def getParamValue(String jobName) {
Map paramValMapping = [
'jobName1': 'value1',
'jobName2': 'value2',
]
String paramValue = paramValMapping.get(jobName)
if (!paramValue) {
throw new Exception("Failed to get value")
}
return paramValue
}
currentBuild.fullProjectName - job name including upper level folders (I needed exactly this)
currentBuild.projectName - just a job name
Unfortunately I didn't manage to place all this logic inside of CascadeChoiceParameter script section.
Also I needed only one value, but this approach can be used for a list of values as well, just don't forget about quotes for string values.
Pay attention that such script changes may require script approve from Jenkins admin in jenkins/scriptApproval for EACH incoming value paramValue
So for everyone who's still looking for a solution to this problem, there are actually three ways you could go about solving this.
The reason why the jenkinsProject variable is not available in Pipeline jobs is due to an issue with the active choices plugin itself. You can read more about this in the following ticket: https://issues.jenkins.io/browse/JENKINS-29407. There's a separate feature branch in the Active Choices project on GitHub that (kinda) solves this issue: https://github.com/jenkinsci/active-choices-plugin/tree/pipeline-support. It wasn't merged into master (and it looks like it never will be), because adding this to Pipeline jobs breaks this functionality for the Freestyle jobs. What you can do is you can compile the plugin from the source yourself and install it on your Jenkins. Pipeline jobs will have the binding variables available in their active choice parameters, however Freestyle jobs will no longer have them. Only use this if the following two options are for some reason not possible in your case.
You can use the properties{} step to configure job parameters from the pipeline run. During pipeline run you could simply use the JOB_BASE_NAME environment variable as an expression of the GString that you'd pass as a script text. The only disadvantage here is that the parameters will only become available after the first build. So if you have a new job you'd need to trigger it once before it becomes parameterized.
You could just use the input() step. Your job won't be parametrized, but users will be able to provide their input to the build during its run. It's not very convenient if you need it to be triggered by some other job or an external webhook, but for cases where the job is expected to only be triggered manually it's probably the best option.

How to create a mask with parameters from the pipeline source code automatically in Jenkins?

I have some pipelines in Jenkins (storeed on github) and they successfully work when run.
All of these pipelines have the own set of parameters written in this way:
pipeline {
agent any
environment {
...
}
parameters {
booleanParam(name: 'TEST', defaultValue: false, description: 'Run task in test mode')
choice(name: 'TASK', choices: ['REFRESH', 'BUILD'], description: 'Pick task')
}
...
}
However the mask is not automatically reflected on the Jenkins server unless I manually use the option in Configure General -> This project is parameterised and add all the variable singularly (duplication of work).
Is there any way to make Jenkins able to build the mask form the coded committed on Github (or any Git server)?

Trigger deployment job from Multibranch pipeline Jenkinsfile

So, we are currently using Multibranch pipeline to run our Continuous Integration process and the last stage is publish the deployable artifact in our JFrog Artifactory "dev" repository and this works!
My problem is that, if I want to automatically trigger a new Jenkins job to take that deployable artifact and deploy it into an integration server and run functional tests then I imagine I would do something like this at the end of my Jenkinfile:
stage("trigger artifact deployment") {
build job: deploymentPipeline,
parameters: [[$class: 'StringParameterValue', name: 'deployableArtifactId', value: "${name}-${version}"],
[$class: 'StringParameterValue', name: 'projectName', value: name],
[$class: 'StringParameterValue', name: 'projectVersion', value: version]],
...
wait: false
}
This approach works! However and because it's a Multibranch pipeline, I would have to hardcode the Jenkins job I want to trigger which I really rather not do but I don't know what else to try as I don't think there would be another way to get the info I need to find the artifact to deploy (ID, version, name, etc.), right?
If you just published it to artifactory, why do you need to find it again? I would add Artifactory properties to the file on upload to enable easier retrieval again.
https://www.jfrog.com/confluence/display/RTF/Properties

Resources