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
Related
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}"
}
}
}
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: ""
)
}
i wanted to send an email to developers to do manual testing and a link to approve the build and then to do the build in production.Can anyone achieve this using jenkins
You can have a step on your pipeline as per below. They cannot approve it on the email, but you can send the URL of the job build on the email:
stage("Stage with input") {
steps {
def userInput = false
script {
// build your custom email message here
emailext (
subject: "Job: ${env.JOB_NAME} - ${env.BUILD_NUMBER}",
body: """Job ${env.JOB_NAME} [${env.BUILD_URL}]""",
recipientProviders: "someone#somewhere.com"
)
def userInput = input(id: 'Proceed1', message: 'Promote build?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'userInput: ' + userInput
if(userInput == true) {
// do action
} else {
// not do action
echo "Action was aborted."
}
}
}
}
Check here email ext plugin.
And here the input step.
How to send a html file in the Email body based on multiple projects?
with the below straight forward code am able to send the mail but if i use " if else condition" then its failing, is it possible to use if condition with in the format?
straight forward code:
always {
emailext mimeType: 'text/html',
body: '${FILE,path="./logs/${JOB_NAME}_Build_${BUILD_NUMBER}/misc/email_dashboard.html"}',
subject: '${JOB_NAME} Report',
to: 'xyz.com'
}
I am trying to achieve something like this:
post {
success {
archiveArtifacts 'logs/${JOB_BASE_NAME}_Build_${BUILD_NUMBER}/**/*, logs/static_results/*'
script {
load "logs/${JOB_BASE_NAME}_Build_${BUILD_NUMBER}/display/pipeline_vars.groovy"
}
}
if ((${NODE_NAME}.contains("KG"))&&(${JOB_NAME}.contains("Nightly"))) {
always {
emailext mimeType: 'text/html',
body: '${FILE,path="./logs/${JOB_NAME}_Build_${BUILD_NUMBER}/misc/email_dashboard.html"}',
subject: '${JOB_NAME} Report',
to: 'xyz.com'
}
}
else if ((${NODE_NAME}.contains("MT")) &&(${JOB_NAME}.contains("Feature"))) {
always {
emailext mimeType: 'text/html',
body: '${FILE,path="./logs/${JOB_NAME}_Build_${BUILD_NUMBER}/misc/email_dashboard.html"}',
subject: '${JOB_NAME} Report',
to: 'xyz.com'
}
}
}
The issue here is that you cannot have always inside an if-else block. In Declarative pipeline syntax, you will have to use if-else inside a script block as shown below:
pipeline {
agent { label 'windows' }
//agent { label 'linux' }
stages {
stage('Echo') {
steps {
echo 'Inside Echo block'
}
}
}
post {
always {
script {
if ((env.NODE_NAME == "windows")) {
echo "Running on ${env.NODE_NAME} node"
}
else if ((env.NODE_NAME == "linux")) {
echo "Running on ${env.NODE_NAME} node"
}
}
}
}
}
Output:
Below code solved my problem:
always {
script {
if (env.JOB_NAME.contains('Nightly'))
{
emailext (
to: '${DEFAULT_RECIPIENTS}',
subject: "${env.JOB_NAME}-Report",
body: '${FILE,path="./logs/${JOB_NAME}_Build_${BUILD_NUMBER}/misc/xyz.html"}',
attachLog: true,
attachmentsPattern: 'logs/${JOB_NAME}_Build_${BUILD_NUMBER}/misc/xyz.png',
)
}
}
}
I am trying to pass the variable value from one stage to the mail body of jenkins. But the variable value is not reflecting.
The code works if I create another stage and call the variable. But not in the
notifyStatusChangeViaEmail method block
Below is the example code.
def variable
pipeline {
agent { label 'master' }
options {
timestamps()
timeout(time: 1, unit: 'HOURS' )
}
stages{
stage('Variable'){
steps {
script{
variable = "Hi, Build is successful"
}
}
}
}
}
def notifyStatusChangeViaEmail(prevBuild) {
def subject
def body
if (currentBuild.previousBuild != null) {
switch (prevBuild.result) {
case 'FAILURE':
emailext attachLog: true, body: "${variable}", recipientProviders: [[$class: 'CulpritsRecipientProvider']], subject: 'Build Status : Build is back to Normal', to: 'sumith.waghmare#gmail.com';
break
case 'UNSTABLE':
emailext attachLog: true, body: "${variable}", recipientProviders: [[$class: 'CulpritsRecipientProvider']], subject: 'Build Status : Build is back to Normal', to: 'sumith.waghmare#gmail.com';
break
case 'SUCCESS':
emailext attachLog: true, body: "${variable}", recipientProviders: [[$class: 'CulpritsRecipientProvider']], subject: 'Build Status', to: 'sumith.waghmare#gmail.com';
break
}
}
}
The problem is that the variable is not defined in the scope of the function (and this post explains how scope of functions works in groovy).
To fix the issue you're seeing I would either make variable a parameter of notifyStatusChangeViaEmail, or I would remove the def variable statement, because that would make variable a global variable and so the function would be able to access it.
Examples:
Making the variable, a parameter of notifyStatusChangeViaEmail:
pipeline {
agent { label 'master' }
options {
timestamps()
timeout(time: 1, unit: 'HOURS' )
}
stages {
stage('Send Email') {
steps {
script {
def emailBody = "Hi, Build is successful"
// I assume that prevBuild is defined somewhere already
notifyStatusChangeViaEmail(prevBuild, emailBody)
}
}
}
}
}
def notifyStatusChangeViaEmail(prevBuild, emailBody) {
if (currentBuild.previousBuild != null) {
switch (prevBuild.result) {
case 'FAILURE':
emailext attachLog: true,
body: emailBody,
recipientProviders: [[$class: 'CulpritsRecipientProvider']],
subject: 'Build Status : Build is back to Normal',
to: 'sumith.waghmare#gmail.com';
break
//...
}
}
}
Using variable as a global:
// --> I deleted the "def variable" line <--
pipeline {
agent { label 'master' }
options {
timestamps()
timeout(time: 1, unit: 'HOURS' )
}
stages {
stage('Variable') {
steps {
script {
// There is no "def" when you first assign a value to
// `variable`, so it will become a global variable,
// which is a variable you can use anywhere in your file
variable = "Hi, Build is successful"
}
}
}
}
}
def notifyStatusChangeViaEmail(prevBuild) {
if (currentBuild.previousBuild != null) {
switch (prevBuild.result) {
case 'FAILURE':
emailext attachLog: true, body: variable, recipientProviders: [[$class: 'CulpritsRecipientProvider']], subject: 'Build Status : Build is back to Normal', to: 'sumith.waghmare#gmail.com';
break
//...
}
}
}
Using variable as a parameter: