How to represent the Notifications Endpoint section of the Jenkins job configuration in a Jenkinsfile (in the form of a groovy script) ? I have installed the Notification plugin but I am not sure how I would use that.
In my jenkins pipeline I did the following:
pipeline {
// ..
stages {
stage('Notify') {
script {
def build = currentBuild // global variable in pipeline -> https://opensource.triology.de/jenkins/pipeline-syntax/globals#currentBuild
def targetUrl = "http://some-url?{some-query-params}"
def buildUrl = build.absoluteUrl
def buildNumber = build.number
def buildStatus = build.currentResult
httpRequest url: targetUrl, contentType: 'APPLICATION_JSON', httpMode: 'POST', responseHandle: 'NONE', timeout: 30, requestBody: """
{
"name": "${args.serviceName}",
"build": {
"full_url": "${buildUrl}",
"number": "${buildNumber}",
"phase": "FINISHED",
"status": "${buildStatus}"
}
}
"""
}
}
Related
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"
}
}
}
}
}
UPDATE
I have a simple pipeline where I want to receive in parameters multiple choices from a file.
In my file I have
#Test1,Accounts
#Test2,Services
#Test3,Accesses
and I want to have all of "#Test1", "#Test2" and "#Test3" in checkboxes as parameters so I would run only the tests selected.
But I'm not understanding what I'm doing wrong.
Pipeline
def code = """tests = getChoices()
return tests
def getChoices() {
def filecontent = readFile "/var/jenkins_home/test.txt"
def stringList = []
for (line in filecontent.readLines()) {stringList.add(line.split(",")[0].toString())}
List modifiedList = stringList.collect{'"' + it + '"'}
return modifiedList
}""".stripIndent()
properties([
parameters([
[$class : 'CascadeChoiceParameter',
choiceType : 'PT_CHECKBOX',
description : 'Select a choice',
filterLength : 1,
filterable : false,
name : 'choice1',
referencedParameters: 'role',
script : [$class : 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox : true,
script : 'return ["ERROR"]'
],
script : [
classpath: [],
sandbox : true,
script : code
]
]
]
])
])
pipeline {
agent {
docker { image 'node:latest' }
}
stages {
stage('Tags') {
steps {
getChoices()
}
}
}
}
def getChoices() {
def filecontent = readFile "/var/jenkins_home/test.txt"
def stringList = []
for (line in filecontent.readLines()) {
stringList.add(line.split(',')[0].toString())
}
List modifiedList = stringList.collect { '"' + it + '"' }
echo "$modifiedList"
return modifiedList
}
With this approach I know I can use multi-select checkboxes because I tried to substitute
def code = """ tests = ["Test1", "Test2", "Test3"]
return tests""".stripIndent()
and I get the output that I wanted.
But when I run my pipeline I get build SUCCESS but always get fallbackScript in my Build parameters checkbox. Can anyone help me out understand what is causing fallbackScript to run always? Thanks :)
If you want to auto-populate build parameters you have to return a list of parameters from your function. When you execute the pipeline the build with parameters will be populated. Note in this was only from the second execution of the pipeline the new parameters will be available. Refer following.
pipeline {
agent any
parameters{
choice(name: 'TESTES', choices: tests() , description: 'example')
}
stages {
stage('Hello') {
steps {
echo 'Hello World'
}
}
}
}
def tests() {
return ["Test01", "Test2", "Test4"]
}
If you want to get user input each time you execute a build you should move your choice parameter into a stage. Please refer to the following.
pipeline {
agent any
stages {
stage('Get Parameters') {
steps {
script{
def choice = input message: 'Please select', ok: 'Next',
parameters: [choice(name: 'PRODUCT', choices: tests(), description: 'Please select the test')]
echo '$choice'
}
}
}
}
}
def tests() {
return ["Test01", "Test2", "Test4"]
}
Update 02
Following is how to read from a file and dynamically create the choice list.
pipeline {
agent any
stages {
stage('Get Parameters') {
steps {
script{
sh'''
echo "#Test1,Accounts" >> test.txt
echo "#Test2,Services" >> test.txt
'''
def choice = input message: 'Please select', ok: 'Next',
parameters: [choice(name: 'PRODUCT', choices: getChoices(), description: 'Please select the test')]
}
}
}
}
}
def getChoices() {
def filecontent = readFile "test.txt"
def choices = []
for(line in filecontent.readLines()) {
echo "$line"
choices.add(line.split(',')[0].split('#')[1])
}
return choices
}
I am using httprequest plugin on jenkis to work with API. I am trying to insert a variable on the requesbody but the variable is not resolved. It is considering the variable as a string.
timestamps {
node () {
def console_api = 'https://example.com/zyx'
def console_address = 'example.com'
stage ('download ') {
httpRequest authentication: 'sa', httpMode: 'POST', ignoreSslErrors: true, outputFile: 'output.yaml', requestBody: ''' {
"consoleAddr": "${console_address}",
}''', responseHandle: 'NONE', url: "${console_api}/api/v1/daemonset.yaml", wrapAsMultipart: false
I need consoleAddr to be resolved to example.com on the http request body.
Below is my declarative pipeline code to deploy code to 2 environments upon approval from UAT lead. But UAT lead would like to approve to deploy one environment . Second environment he would like to after a day or so ( this can be day or few days . Unpredictable) . How can it be achieved ? . Sleep / timeout does work here . Two separate approval stage can be done ?
#Library('xxxxxx') _
import jenkins.model.*
def userInput
def builduserid
def buildusername
def MANIFESTFILE
def SNAPSHOT
def BUILD_TIMESTAMP
def ucdDeployProcess
def deplprocess = env.DEPLOYPROCESS.split(",").findAll { it }.collect { it.trim() }
node("BDP") {
wrap([$class: 'BuildUser']) {
builduserid = env.BUILD_USER_ID
buildusername = env.BUILD_USER
}
}
pipeline {
agent { label 'BDP'}
stages {
stage ('Generate and Create Consolidated Snapshot') {
steps {
println "Cleaning workspace"
step([$class: 'WsCleanup'])
dir('') {
git url: 'xxxxx'
}
dir('scripts') {
git url: 'xxxxx'
}
script {
def now = new Date()
BUILD_TIMESTAMP=now.format("yyyyMMddHHmm", TimeZone.getTimeZone('UTC'))
env.MANIFESTFILE="${ucdApplication}_${RELEASE}_Manifest.csv"
env.SNAPSHOT="${ucdApplication}_${RELEASE}_${BUILD_TIMESTAMP}"
sh(script: '$WORKSPACE/scripts/scripts/SelfServiceBaselineVerificationPrePareForSnapshot.ksh "$ucdApplication" "${COMPSNAPSHOT}" "$ucdApplication"/"${MANIFESTFILE}"')
def props = readProperties file: 'env.cfg' //readProperties is a step in Pipeline Utility Steps plugin
env.SnapshotContent = props.COMBINEDSNAPSHOTVERSION
}
}
post {
failure {
emailext body: '''
<div>Hi Application Team</div>
<br>
<div>
<br>
<br>
<h4>Failed Checks: </h4>
<div style="margin-left: 50px;">
${BUILD_LOG_REGEX, regex="FAILED!", showTruncatedLines=false, escapeHtml=true, defaultValue="Nothing found, please check logs for other errors", matchedLineHtmlStyle="color:red;"}
</div>
<br>
<br>
</div>
<br>
<div>Thank you</div>
''',
mimeType: 'text/html',
to: "${builduserid}",
subject: '$ucdApplication Component Baseline Verification FAILED'
}
}
}
stage ('Create Consolidated Snapshot') {
steps {
ucdCreateCustomSnapshot()
}
}
stage ('Approval Stage') {
steps {
script {
emailext body: """
Hi Approver,<br/><br/><br/>
You have request from application team (${buildusername}) to deploy $ucdApplication application snapshot ${env.SNAPSHOT} to ${deploymentEnv} environment.<br/><br/><br/>
Please approve or reject deployement request: Click here.<br/><br/><br/>
Thanks,<br/><br/>
Happy Automation<br/>
""",
mimeType: 'text/html',
subject: "Deployment Approval Request",
from: "${builduserid}",
to: "${approverRecipients}"
userInput = input id: 'userInput',
message: 'Let\'s promote?.Please select to approve',
submitterParameter: 'submitter',
submitter: approverRecipients,
parameters: [
[$class: 'BooleanParameterDefinition', defaultValue: false, description: "Select this to deploy the code ${deploymentEnv} environment", name: deploymentEnv]]
if (userInput[deploymentEnv] == false ) {
currentBuild.result = 'ABORTED'
}
}
}
}
stage("Deploy to Acceptance") {
when {
expression { userInput[deploymentEnv] == true }
}
steps {
script {
for (int i = 0; i < deplprocess.size(); i++) {
env.ucdDeployProcess = deplprocess[i]
ucdCustomDeploySnapshot("${deploymentEnv}")
}
}
}
}
stage('Post Activities') {
steps {
println "Cleaning workspace"
step([$class: 'WsCleanup'])
}
}
}
post {
failure {
emailext body: """
Hi Team,<br/><br/><br/>
Code Deployment is failed for ${ucdApplication} application.<br/><br/><br/>
<p><font size="5" color="red">Deployment Request is failed for ${ucdApplication} application with snapshot ${env.SNAPSHOT}!</font></p>
<p>Check console output at "<a href='${BUILD_URL}consoleText'>${JOB_NAME} [${BUILD_NUMBER}]</a>"</p>
Thanks,<br/>
Happy Automation<br/><br/><br/>
""",
mimeType: 'text/html',
to: "${mailToRecipients},${builduserid}",
from: "${builduserid}",
subject: "FAILURE: Code Deployment is failed for '$ucdApplication' application with snapshot ${env.SNAPSHOT}"
}
success {
emailext body: """
Hi Team,<br/><br/><br/>
<p><font size="5" color="green">Code Deployment is success for $ucdApplication application for ${deploymentEnv} environment with snapshot ${env.SNAPSHOT}!</font></p>
Thanks,<br/>
Happy Automation<br/><br/><br/>
""",
mimeType: 'text/html',
to: "${mailToRecipients},${builduserid}",
from: "${builduserid}",
subject: "SUCCESSFUL: Code Deployment is success for '$ucdApplication' application with snapshot ${env.SNAPSHOT}"
}
aborted {
emailext body: """
Hi Team,<br/><br/><br/>
<p><font size="5" color="red">Deployment Request is rejected for ${ucdApplication} application by approver !</font></p>
Thanks,<br/>
Happy Automation<br/><br/><br/>
""",
mimeType: 'text/html',
to: "${mailToRecipients},${builduserid}",
from: "${builduserid}",
subject: "REJECTED: Code Deployment is rejected for $ucdApplication application with snapshot ${env.SNAPSHOT} by approver"
}
}
enter code here
}
jenkins-pipeline
I've seen this example on how to load declarative piplines form a shared Library:
https://jenkins.io/doc/book/pipeline/shared-libraries/#defining-declarative-pipelines
But I would like to have the pipeline as inline functions:
def linux_platform = "U1604_x64_gcc54"
def windows_platform = "WIN10_x64_vc141"
properties(
[
parameters(
[
choice(name: 'platform', choices: [linux_platform, windows_platform], description: 'Platform'),
string(defaultValue: "-1", description: 'Upsteam Project build number', name: 'upsteam_project_build_number')
]
)
]
)
if(params.platform == windows_platform) {
windows(params.upsteam_project_build_number)
}
def windows(upsteam_project_build_number) {
pipeline {
agent {
label windows_platform
}
environment {
WINDOWS_ENV = "C:/my_path"
}
stages {
stage('Do stuff') {
steps{
echo "Doing stuff"
}
}
}
post {
failure {
job_status_mail(currentBuild.currentResult, JOB_NAME, BUILD_NUMBER, BUILD_URL)
}
fixed {
job_status_mail("fixed", JOB_NAME, BUILD_NUMBER, BUILD_URL)
}
}
}
}
Im getting the following error:
java.lang.NoSuchMethodError: No such DSL method 'agent' found among steps
Is my syntax some how wrong or is it not possible to load a pipeline from a inlne function?
I'm running:
Jenkins ver. 2.138.4
Declarative Pipeline Plugin ver. 1.3.8