How to read GitHub payload in groovy Jenkinsfile? - jenkins

I have a web hook configured in my GitHub org that triggers a Jenkins pipeline every time a new repo is created. What I am trying to do is get some of the values from the payload which triggers the job and use them in a script within the pipeline.
One such example would be the repo name, for instance the payload looks something like this:
{
"action": "created",
"repository": {
"name": "my-new-repo"
[...]
}
[...]
}
I tried assigning the repository["name"] value to a variable in the Jenkinsfile but that did not seem to work:
pipeline{
environment {
REPO_NAME = $.repository.name
}
[...]
}
Also tried it with quotes and some other ways in formatting but still could not get it to be assigned to the REPO_NAME variable.

Here is an example of how to Read different attributes from the Webhook request.
pipeline {
agent any
triggers {
GenericTrigger(
genericVariables: [
[key: 'REPO_NAME', value: '$.repository.name', defaultValue: 'null'],
[key: 'PR_TYPE', value: '$.pullrequest.type', defaultValue: 'null']
],
causeString: 'Triggered By Github',
token: '12345678',
tokenCredentialId: '',
printContributedVariables: true,
printPostContent: true,
silentResponse: false
)
}
stages {
stage('ProcessWebHook') {
steps {
script {
echo "Received a Webhook Request from Guthub."
echo "RepoName: $REPO_NAME"
}
}
}
}
}

Related

Dynamically filling parameters from a file in a Jenkins pipeline

TL;DR:
I would like to use ActiveChoice parameters in a Multibranch Pipeline where choices are defined in a YAML file in the same repository as the pipeline.
Context:
I have config.yaml with the following contents:
CLUSTER:
dev: 'Cluster1'
test: 'Cluster2'
production: 'Cluster3'
And my Jenkinsfile looks like:
pipeline {
agent {
dockerfile {
args '-u root'
}
}
stages {
stage('Parameters') {
steps {
script {
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select the Environemnt from the Dropdown List',
filterLength: 1,
filterable: false,
name: 'Env',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script:
"return['Could not get The environemnts']"
],
script: [
classpath: [],
sandbox: true,
script:
'''
// Here I would like to read the keys from config.yaml
return list
'''
]
]
]
])
])
}
}
}
stage("Loading pre-defined configs") {
steps{
script{
conf = readYaml file: "config.yaml";
}
}
}
stage("Gather Config Parameter") {
options {
timeout(time: 1, unit: 'HOURS')
}
input {
message "Please submit config parameter"
parameters {
choice(name: 'ENV', choices: ['dev', 'test', 'production'])
}
}
steps{
// Validation of input params goes here
script {
env.CLUSTER = conf.CLUSTER[ENV]
}
}
}
}
}
I added the last 2 stages just to show what I currently have working, but it's a bit ugly as a solution:
The job has to be built without parameters, so I don't have an easy track of the values I used for each job.
I can't just built it with parameters and just leave, I have to wait for the agent to start the job, reach the stage, and then it will finally ask for input.
Choices are hardcoded.
The issue I'm currently facing is that config.yaml doesn't exist in the 'Parameters' stage since (as I understand) the repository hasn't been cloned yet. I also tried using
def yamlFile = readTrusted("config.yaml")
within the groovy code but it didn't work either.
I think one solution could be to try to do a cURL to the file, but I would need Git credentials and I'm not sure that I'm going to have them at that stage.
Do you have any other ideas on how I could handle this situation?

how to fail the jenkins build if any test cases are failed using findText plugin

I have a stage in Jenkins as follows, How do I mark the build to fail or unstable if there is a test case failure? I generated the script pipeline for textfinder plugin but it is not working. "findText alsoCheckConsoleOutput: true, regexp: 'There are test failures.', unstableIfFound: true" not sure where to place the textFinder regex.
pipeline {
agent none
tools {
maven 'maven_3_6_0'
}
options {
timestamps ()
buildDiscarder(logRotator(numToKeepStr:'5'))
}
environment {
JAVA_HOME = "/Users/jenkins/jdk-11.0.2.jdk/Contents/Home/"
imageTag = ""
}
parameters {
choice(name: 'buildEnv', choices: ['dev', 'test', 'preprod', 'production', 'prodg'], description: 'Environment for Image build')
choice(name: 'ENVIRONMENT', choices: ['dev', 'test', 'preprod', 'production', 'prodg'], description: 'Environment for Deploy')
}
stages {
stage("Tests") {
agent { label "xxxx_Slave"}
steps {
checkout([$class: 'GitSCM', branches: [[name: 'yyyyyyyyyyz']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'zzzzzzzzzzz', url: 'abcdefgh.git']]])
sh'''
cd dashboard
mvn -f pom.xml surefire-report:report -X -Dsurefire.suiteXmlFiles=src/test/resources/smoke_test.xml site -DgenerateReports=false
'''
}
}
}
}
All I did to make this request possible is as below:
added a post block of code below the steps block code.
post {
Success {
findText alsoCheckConsoleOutput: true, refexp: 'There are test failures.', unstableIfFound: true
}
}

Use Jenkins WORKSPACE environment variable in Jenkins declarative pipeline parameter

Is there a way to use Jenkins WORKSPACE environment variable in Jenkins declarative pipeline parameters?
Below attempt failed.
pipeline {
parameters {
extendedChoice description: 'Template in project',
multiSelectDelimiter: ',', name: 'TEMPLATE',
propertyFile: env.WORKSPACE + '/templates.properties',
quoteValue: false, saveJSONParameterToFile: false, type: 'PT_MULTI_LEVEL_SINGLE_SELECT',
value: 'Project,Template', visibleItemCount: 6
...
}
stages {
...
}
propertyFile: '${WORKSPACE}/templates.properties' didn't work either.
The environment variable can be accessed in various place in Jenkinsfile like:
def workspace
node {
workspace = env.WORKSPACE
}
pipeline {
agent any;
parameters {
string(name: 'JENKINS_WORKSPACE', defaultValue: workspace, description: 'Jenkins WORKSPACE')
}
stages {
stage('access env variable') {
steps {
// in groovy
echo "${env.WORKSPACE}"
//in shell
sh 'echo $WORKSPACE'
// in groovy script
script {
print env.WORKSPACE
}
}
}
}
}
The only way that worked is putting absolute path to Jenkins master workspace where properties file is located.
pipeline {
parameters {
extendedChoice description: 'Template in project',
multiSelectDelimiter: ',', name: 'TEMPLATE',
propertyFile: 'absolute_path_to_master_workspace/templates.properties',
quoteValue: false, saveJSONParameterToFile: false, type: 'PT_MULTI_LEVEL_SINGLE_SELECT',
value: 'Project,Template', visibleItemCount: 6
...
}
stages {
...
}
It seems that environment variables are not available during pipeline parameters definition before the pipeline actually triggered.

Extended Choice Parameter implementation

I'm setting up a new job in which we are required to select Multiple values. Need to select Service1 and Service2...
Went through link How to pass multi select value parameter in Jenkins file(Groovy)
However, I am not sure how to pass values in my Jenkinsfile
A snippet of Jenkinsfile
stage('parallel'){
parallel(
"service1": {stage('service1-deployment') {
if (params.ServiceName == 'Service1' || params.ServiceName == 'ALL'){
b = build(job: 'job name', parameters: [string(name: 'ENVIRONMENT', value: TARGET_ENVIRONMENT),string(name: 'IMAGE_TAG', value: value)], propagate: false).result
if(b=='FAILURE'){
echo "job failed"
currentBuild.result = 'UNSTABLE'
}
}
}
},
"service2": {stage('service2t') {
if (params.ServiceName == 'service2' || params.ServiceName == 'ALL'){
b = build(job: 'Job name', parameters: [string(name: 'ENVIRONMENT', value: TARGET_ENVIRONMENT),string(name: 'IMAGE_TAG', value: value)], propagate: false).result
if(b=='FAILURE'){
echo "job failed"
currentBuild.result = 'UNSTABLE'
}
}
}
},
I see that you're using declarative pipeline syntax for your job.
So, if the accepted answer for that question with booleanParam is useful for you, then you can use it inside parameters section (see the official documentation for more details):
pipeline {
agent any
parameters {
booleanParam(defaultValue: false, name: 'ALL', description: 'Process all'),
booleanParam(defaultValue: false, name: 'OPTION_1', description: 'Process option 1'),
booleanParam(defaultValue: false, name: 'OPTION_2', description: 'Process options 2'),
}
stages {
stage('Example') {
steps {
echo "All: ${params.ALL}"
echo "Option 1: ${params.OPTION_1}"
echo "Option 2: ${params.OPTION_2}"
}
}
}
}
However, if you want to use extended choice parameter with multiselect input, you need to use scripted pipeline syntax, see this example (already mentioned here).

Jenkins Date Parameter Plugin - How to use it in a Declarative Pipeline

What is the syntax for using the Date Parameter Plugin in a declarative pipeline.
So far I have tried this:
pipeline {
agent {
node {
label 'grange-jenkins-slave'
}
}
options { disableConcurrentBuilds() }
parameters {
date(name: 'EffectiveDate',
dateFormat: 'MMddyyy',
defaultValue: 'LocalDate.now();',
description: 'Effective Date',
trim: true)
file(name:'algo.xlsx', description:'Your algorithm file')
choice(name: 'currency',
choices: ['USD'],
description: 'Select a currency')
}
stages {
stage('genRates') {
steps {
script {
echo "test"
}
}
}
}
}
The error I get is WorkflowScript: 11: Invalid parameter type "date". Valid parameter types: [booleanParam, choice, credentials, file, text, password, run, string] # line 11, column 3.
you can define parameter as class DateParameterDefinition.
example:
properties([parameters([
string(name: 'somestring', defaultValue: 'somevalue'),
[$class: 'DateParameterDefinition',
name: 'somedate',
dateFormat: 'yyyyMMdd',
defaultValue: 'LocalDate.now()']
])])
pipeline {
...
}
I did not use date parameter plugin as I didn't find any example how to use it. I resolved this in a different way.
import java.text.SimpleDateFormat
def sdf = new SimpleDateFormat("yyyyMMdd")
def dateDefaultValue = sdf.format(new Date())
pipeline {
parameters {
string(name: 'SOMEDATE', defaultValue: "${dateDefaultValue}", description: 'Default value is current date in the format YYYYmmdd', trim: true)
}
.....
.....
}

Resources