How to make a REST API call from jenkins pipeline - jenkins

I'm trying to make a REST API call from jenkins pipeline once a build job is finished. Since I'm new to the content, I'm unable to complete the build with my below script:
pipeline {
agent any
stages {
stage('BUILD') {
steps {
echo 'Demo Staging Build Running'
}
}
}
post {
always {
echo 'Demo Staging Build Completed'
echo "Build Result: ${currentBuild.result}"
echo "Build Url: ${env.BUILD_URL}"
def response = httpRequest acceptType: 'APPLICATION_JSON', httpMode: 'GET', url: 'http://localhost:9091/demo/jenkins-res'
echo "Status: ${response.status}"
}
}
}
While running the script, I'm getting the below error:
Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 27: Expected a step # line 27, column 13.
def response = httpRequest acceptType: 'APPLICATION_JSON', httpMode: 'GET', url: 'http://localhost:9091/ucreator/jenkins-res'

Rectified the issue with a script tag surrounding the request
pipeline {
agent any
stages {
stage('BUILD') {
steps {
echo 'Demo Staging Build Running'
}
}
}
post {
always {
echo 'Demo Staging Build Completed'
echo "Build Result: ${currentBuild.result}"
echo "Build Url: ${env.BUILD_URL}"
script {
def response = httpRequest acceptType: 'APPLICATION_JSON', httpMode: 'GET', url: 'http://localhost:9091/demo/jenkins-res'
}
echo "Status: ${response.status}"
}
}
}

Related

Jenkins won't run my build script from perforce

I have a build script I created which is located in a perforce streams depot at //HVS/Main/BuildScripts/hvs_client.jenkinsfile. However, when I run it it's just automatically successful. You can see in the image what it's doing.
I have set the Script Path to the correct location:
And I also have it setup with the correct stream path:
This exact setup works just fine on my windows server running jenkins. The only difference is that I'm trying to migrate my jenkins setup off of a physical machine and onto the cloud. The new master which is running on Ubuntu 20.04 is what is having these issues. I also have one "Node" which is a windows server which has the java agent installed and connected.
This is what my pipeline script looks like:
def channelId = 'removed_for_stackoverflow'
def threadId
def slackResponse
pipeline {
agent {label 'Windows'}
parameters {
choice(name: "BuildType", choices: ['Development', 'Shipping', 'Testing'], description: "What environment are you building to? Default is Development.")
string(name: "SevenZIPDir", defaultValue: "C:\\Program Files\\7-Zip\\7z.exe", description: "Location of 7zip executable.")
booleanParam(name: "clean", description: "Should jenkins clean the workspace?", defaultValue: false)
}
options {
skipDefaultCheckout()
}
stages {
stage('P4 Sync') {
steps {
script {
if (params.clean)
{
cleanWs()
}
p4sync charset: 'none', credential: '5feaca76-6a4a-4540-8a1e-e86ac8b3dc5b', populate: syncOnly(force: false, have: true, modtime: false, parallel: [enable: false, minbytes: '1024', minfiles: '1', threads: '4'], pin: '', quiet: true, revert: false), source: streamSource('//HVS/Main')
}
}
}
// https://github.com/jenkinsci/slack-plugin#bot-user-mode
// https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/ProgrammingWithCPP/UnrealArchitecture/VersioningAssetsAndPackages/
// https://www.perforce.com/manuals/jenkins/Content/P4Jenkins/variable-expansion.html
stage('Notify Slack users') {
steps {
script {
slackResponse = slackSend(channel: channelId, replyBroadcast: true, message: "Beginning build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} ${env.BUILD_URL}")
threadId = slackResponse.threadId
slackResponse.addReaction("stopwatch")
}
}
}
stage('Build Client') {
steps {
retry(3) {
bat("%WORKSPACE%/Engine/Build/BatchFiles/RunUAT.bat BuildCookRun -project=\"%WORKSPACE%/HVS/HVS.uproject\" -noP4 -platform=Win64 -clientconfig=Development -cook -allmaps -clean -build -stage -pak -CrashReporter -archive -archivedirectory=\"%WORKSPACE%/temp/Development/x64\"")
}
}
}
/*stage('Deploy to Steam') {
}*/
stage('Archive Artifacts'){
steps {
dir("temp/${params.BuildType}/x64/WindowsNoEditor") {
bat "\"${params.SevenZIPDir}\" a -mx=1 -mmt=on %WORKSPACE%/temp/HVS_${params.BuildType}_x64_${P4_CHANGELIST}.7z *"
}
archiveArtifacts artifacts: "temp/*.7z", followSymlinks: false, onlyIfSuccessful: true
}
}
}
post {
success {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} successful! ${env.BUILD_URL}")
slackResponse.addReaction("white_check_mark")
}
}
failure {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} failed! ${env.BUILD_URL}")
slackResponse.addReaction("red_circle")
}
}
unstable {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} is not stable #channel ${env.BUILD_URL}")
slackResponse.addReaction("warning")
}
}
}
}
Has anyone seen this before? My one "Node" also has the label "Windows"
I didn't have the Pipeline plugin installd for some reason. It works now.

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
}
}

Jenkins Declarative pipeline deployment approval for only one environment

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 &QUOT;<a href='${BUILD_URL}consoleText'>${JOB_NAME} [${BUILD_NUMBER}]</a>&QUOT;</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

How to send allure or html report as an attachment in the Jenkins email notifications

How to send allure or html report as an attachment in the Jenkins email notifications. This is example of the pipeline i am using in my Pipeline script in Jenkins. I have setup my email notifcations, however i want to get some sort of report in the email. Please note that providing a link is not enough because my tests are setup on a different machine with the reports.
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'echo "Fail!"; exit 1'
}
}
}
post {
always {
echo 'This will always run'
}
success {
echo 'This will run only if successful'
}
failure {
mail bcc: '', body: "<b>Example</b><br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL de build: ${env.BUILD_URL}", cc: '', charset: 'UTF-8', from: '', mimeType: 'text/html', replyTo: '', subject: "ERROR CI: Project name -> ${env.JOB_NAME}", to: "foo#foomail.com";
}
unstable {
echo 'This will run only if the run was marked as unstable'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
echo 'For example, if the Pipeline was previously failing but is now successful'
}
}
}
You should use emailext plugin not mail
failure {
emailext(
attachmentsPattern: "<path to report>",
body: '',
subject: "",
to: ""
)
}

Is there a way to show the name of failed tests in email body via jenkins

I want to see the names of all failed tests in email body when an email is triggered by jenkins using editable email notification plugin.
I am using TestNg with selenium+java.
You can add allure reports in your tests and send the allure links or file via emial as in code below:
stage('Create properties file for allure') {
steps {
sh '''
export CHATBOT_ENV
touch allure-results/environment.properties
'''
}
}
stage('Allure reports') {
steps {
script {
allure([
includeProperties: true,
jdk: '',
properties: [],
reportBuildPolicy: 'ALWAYS',
results: [[path: 'allure-results/']]
])
}
}
}
}
post
{
always
{
echo 'This will always run'
emailext body: "Build URL: ${BUILD_URL}",
attachmentsPattern: "**/path_to_your_report",
subject: "$currentBuild.currentResult-$JOB_NAME",
to: 'nobody#optum.com'
}
}
}
THe build URL can be used to navigate to allure report.

Resources