Run jenkins job based on previous job status - jenkins

I have scenario where i need job to run only if the previous build was success .
if previous build had failed i need user to wait for admin apporval.
if previous build had success user can run the job.
can anyone help me how to go about it .

Below is the pipeline script which will check the previous build and ask for the approval if the pervious build is failed or sucess
pipeline{
agent any
stages{
stage('Previous Status check'){
steps{
echo "Checking"
sleep 10
}
}
stage('Deploy approval'){
when {
expression {
// When last build has failed
!hudson.model.Result.SUCCESS.equals(currentBuild.rawBuild.getPreviousBuild()?.getResult()) == true
}
}
steps {
input(message: 'last build was failed please check target group and approve', ok: 'Release!' , submitter: "ritesh.mahajan")
}
}
stage('Building code on server'){
steps{
script {
def inputConfig
def inputTest
// Get the input
def userInput = input(
id: 'userInput', message: 'Enter the branch to build',
parameters: [
string(defaultValue: 'Master',
description: 'Enter the branch',
name: 'Branch'),
])
inputbranch=userInput
echo "${inputbranch}"
echo "here we can execute script in remote machine by default it will build master ..we can also accept parameter"
}
}
}
}
}

Related

Jenkins Pipeline - how to execute sequential sub-jobs and propagate the error while keeping the sequence

I am trying to have a pipeline that executes multiple sequential jobs.
The problem is that if I have the "propagate false" flag, the jobs are executed but the pipeline build always returns 'Success' regardless the sub-jobs status.
If I want the pipeline reflects the 'Fail' status when a sub-job fails, and remove the propagate flag, the sequence is broken at that failure point, and no more jobs are executed.
Can you help me getting the best way to achieve this?
I hope I was clear. Thank you very much.
pipeline{
stages{
stage('Tests'){
steps{
parallel(
'TestSet':{
build wait: true, job: 'Test A'
build wait: true, job: 'Test B'
build wait: true, job: 'Test C'
}
)
}
}
}
}
When you run the build step it actually returns an RunWrapper object (see Java Docs).
The RunWrapper has a getResult() function which enables you to get the result of the build that was executed, along side many other proproteins of the executed build, like the build number.
You can then run your jobs with the propagate false option, save the results, examine them after all builds are finished and then run your required logic.
For example:
pipeline{
stages{
stage('Tests'){
steps{
script {
parallel(
'TestSet': {
// Collect all results of build execution into a map
def results = [:]
results['Test A'] = build(wait: true, job: 'Test A').getResult()
results['Test B'] = build(wait: true, job: 'Test B').getResult()
results['Test C'] = build(wait: true, job: 'Test C').getResult()
// Analyze the result
failedJobs = results.findAll(it.value != 'SUCCESS') // you can also use Result.SUCCESS instead of the string
if (failedJobs){
error "The following jobs have failed: ${failedJobs.collect{it.key}.join(',')}"
}
}
)
}
}
}
}
}

Jenkins / How to deploy with one click

I am working on a project with git and jenkins (pipeline).
I want to build the project at every commit but only deploy it when the chief wants.
So I would like to have like, two pipelines, one that run at every commit and only build / test and one that I can run by clicking on a button labelled "click me to deploy" that do the job.
Do I must create 2 jenkins jobs or is there a plugin or a way to do this with 1 job.
I have searched but I found nothing about this.
You can achieve with 1job using Input Step (Pipeline). As part of your pipeline, after the build and test execution, add input step (Wait for Interactive input) and then add the deployment related stages.
So for each check-in, Jenkins build will trigger. But it will complete only build and test stages after that it will wait for chief approval to proceed for deployment.
reference: https://jenkins.io/doc/pipeline/steps/pipeline-input-step
This is an example on how to build a pipeline that builds, waits for input, and deploys when input is yes. If input timeout is exceeded then the job will exit. If one does not need the timeout then it can be ommited and the pipeline will wait indefinately without consuming an executor (note the agent annotation in the top pipeline and in each stage)
pipeline {
agent none
stages {
stage('Build') {
agent { label 'master' }
steps {
sh 'build something'
}
}
stage('Production deploy confirmation') {
options {
timeout(time: 60, unit: 'SECONDS')
}
input {
message "Deploy to production?"
ok "Yes"
}
steps {
echo 'Confirmed production deploy'
}
}
stage('Deploy Production') {
stage('internal') {
agent { label 'master' }
steps {
sh 'deploy something'
}
}
}
}
}
Try a parametrized Job with a Boolean parameter and two separate stages for Build and Deploy:
pipeline{
parameters {
booleanParam(name: 'deploy_param', defaultValue: false, description: 'Check if want to deploy')
}
stages{
stage("Build"){
steps{
// build steps
}
}
stage("Deploy"){
when {
environment name: 'deploy_param', value: 'true'
}
steps{
// deploy steps
}
}
}
}
In this way yo can have a CI build with "Deploy" stage turned off, as the deploy_param is set to false by default. And also a manual build ("when the chief wants") with "Deploy" stage turned on by manually setting the deploy_param to true.

How to run Ansible playbook with user input within Jenkins?

I have a playbook with section "pause" and prompt. If I create job within Jenkins with Pipeline plugin and run this job I get
[WARNING]: Not waiting from prompt as stdin is not interactive
and job is failed. The question is how I can run job in interactive mode or how I can pause playbook within exact task and push combination Ctrl+c+c (because ansible module 'pause' is working only like that)? I have googled a few time and tried to do that with
def userInput = input(
id: 'Password', message: 'input your input: ', ok: 'ok',
parameters: [string(defaultValue: '', description: '.....', name: 'INPUT_TEST')])
But I can't push keys combination and can't understand how I can pause jenkins job on specific ansible task within playbook.
Pipeline example:
pipeline {
agent { label 'master' }
environment {
WORKDIR = '/home/jenkins/'
}
stages {
stage('Checkout') {
agent { label 'master' }
steps {
sh '''cd $WORKDIR
ansible-playbook -vvvv manual_playbooks/test.yml'''
}
}
stage ('Echo') {
agent { label 'master' }
steps {
sh 'echo something'
}
}
}
}
Playbook example:
---
- name: test
hosts: localhost
tasks:
- name: Echo start
shell: echo 'start playbook'
- pause:
prompt: "do you want to continue?"
echo: yes
private: no
register: prompt_status
- name: Continue tasks
shell: echo 'Continue full flow'
register: reset_account_response
when: prompt_status.user_input is defined and
prompt_status.user_input == "yes"
- fail:
msg: "Unexpected user input while prompting approval"
when: prompt_status.user_input is defined and
prompt_status.user_input != "yes"
Many thanks.
Why not put a when clause on your pause task to check for the existence of some other variable and then pass that in using Ansible's -e option when running the playbook through Jenkins.

How we can get console output in jenkins job 'createhosts' log output instead of showing build number in jenkins build pipeline project?

I wrote a pipeline script and in console output i need createhosts log output also instead of showing build number.
Script:
pipeline {
agent none
stages {
stage('create hosts') {
steps {
echo "Hello! , This build for create VMs "
build job: 'createhosts',
parameters: [
*********
********* some parameters
]
}
}
stage ('CD job ') {
steps {
echo "This build for configure VMs "
build job: 'CD'
}
}
stage ('Delete VMs') {
steps {
echo "This job is required a host file as input for approval to Delete VMs"
input "approve for deletion"
build job: 'delete_vms'
}
}
}
}

How to restrict the users that can run jenkinsfile tests in pull requests?

I have deployed the pipeline-as-code docker demo with multibranch.
It works alright. I added my github username as the organization and when I make a pull request, the tests are run.
However, when some other user makes a pull request, their tests are also run. I would like to manually approve which pull requests from external contributors are good to run in my jenkins server. Is there a way to do that?
I can do it with ghprb, but it is not compatible with pipelines, and I want to migrate my jobs to pipelines.
please try adding these lines in your pipeline script:
node('slaveName') {
properties([
parameters([
string(
defaultValue: 'whitelisted1#gmail.com,whitelisted2#gmail.com',
description: 'comma separated whitelisted emails',
name: 'WHITELIST'
)
])
])
def authorEmail
stage('Git') {
authorEmail = sh([
// git log format docs here: https://git-scm.com/docs/pretty-formats
script : "git log -1 --format='%aE'",
returnStdout: true
]).trim()
boolean allowRun = isWhitelisted(env.WHITELIST, authorEmail)
if (allowRun) {
echo "email ${authorEmail} is whitelisted, proceed execution"
} else {
echo "email ${authorEmail} is not in whitelist ${env.WHITELIST}, proceed jenkins job?"
input message: 'Proceed?'
// or just abort build with non-zero shell exit
// currentBuild.result = 'FAILURE'
// sh "exit 10"
}
}
}
}
#NonCPS
boolean isWhitelisted(whitelist, email) {
def res = whitelist.tokenize(" ,;").find { white -> white == email }
return null != res
}

Resources