How to place a condition in node for select an agent master or stage?
def curNode = "${env.Environment}"
node(curNode === 'prod' ? 'master' : 'stage') { <= "error this"
try {
dir(env.Environment) {
stage("Clone repository") {
echo "clong success"
}
}
} catch (e) {
echo 'Error occurred during build process!'
echo e.toString()
currentBuild.result = 'FAILURE'
}
}
If you need to compare two strings, you need to use ==. When you use === it checked whether the objects are identical. Hence update your Script like the below.
def curNode = "${env.Environment}"
node(curNode == 'prod' ? 'master' : 'stage') { <= "error this"
try {
dir(env.Environment) {
stage("Clone repository") {
echo "clong success"
}
}
} catch (e) {
echo 'Error occurred during build process!'
echo e.toString()
currentBuild.result = 'FAILURE'
}
}
Related
On running the below code, I am getting to the else block of String comparison section.
But unable to get into the else block of Boolean comparison section.
pipeline {
agent any
parameters{
string(
name: "s_Project_Branch_Name", defaultValue: "master",
description: "Enter Brnach Name")
}
stages {
stage('Example') {
input {
message "Proceed to Prod Deployment with ${params.s_Project_Branch_Name} branch?"
ok "Yes"
parameters {
string(name: 'PERSON', defaultValue: 'master', description: 'Who should I say hello to?')
booleanParam(name: "TOGGLE", defaultValue: false, description: "Check this box to Proceed.")
}
}
steps {
// echo "Hello, ${PERSON}, nice to meet you."
script{
echo 'String'
if ("${PERSON}" == "${params.s_Project_Branch_Name}") {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
currentBuild.result = "FAILURE"
}
}
script{
echo 'Boolean'
echo "${TOGGLE}"
if ("${TOGGLE}") {
echo 'I only execute if boolean true'
} else {
error('I only execute if boolean false')
currentBuild.result = "FAILURE"
}
}
}
}
}
}
When you do String interpolation "${TOGGLE}" you will be getting a String, not a Boolean. If you want to get the Boolean value you can directly access the variable by doing params.TOGGLE. So change the condition like below.
if (params.TOGGLE) {
echo 'I only execute if boolean true'
} else {
error('I only execute if boolean false')
currentBuild.result = "FAILURE"
}
OR
if ("${TOGGLE}" == "true") {
echo 'I only execute if boolean true'
} else {
error('I only execute if boolean false')
currentBuild.result = "FAILURE"
}
I would like to run pipeline with 2 stages. If any of the stage is failed, next stage should be started (not skipped). Currently if 1st stage is failed, next stage will be skipped.
Thank you for any help.
pipeline {
options { buildDiscarder(logRotator(numToKeepStr: '5', artifactNumToKeepStr: '5')) }
agent { label 'docker_gradle' }
triggers {
cron(env.BRANCH_NAME == 'develop' || env.BRANCH_NAME == 'master' ? '#daily' : '')
}
stages {
stage('Init') {
steps {
sh 'chmod +x gradlew'
}
}
stage('task1') {
when { anyOf { branch 'feature/*'; branch 'develop' }}
steps {
container(name: 'gradle') {
sh 'gradle clean task1'
}
}
}
stage('task2') {
when { anyOf { branch 'feature/*'; branch 'develop' }}
steps {
container(name: 'gradle') {
sh 'gradle clean task2'
}
}
}
}
post {
always {
script {
currentBuild.result = currentBuild.result ?: 'SUCCESS'
cucumber buildStatus: 'UNSTABLE',
failedFeaturesNumber: 1,
failedScenariosNumber: 1,
skippedStepsNumber: 1,
failedStepsNumber: 1,
reportTitle: 'Reoport',
fileIncludePattern: '**/cucumber.json',
sortingMethod: 'ALPHABETICAL',
trendsLimit: 100
}
}
}
}
1.You can change sh 'gradle clean task1' to
sh 'gradle clean task1 || true'
This will make sh return success even if sh scrip fails
2.You can also use try catch
Check this link: https://www.jenkins.io/doc/book/pipeline/syntax/#flow-control
for example:
stage("task1"){
steps {
script {
try {
sh 'gradle clean task1'
} catch (err) {
echo err.getMessage()
}
}
}
}
pipeline {
agent { label 'master' }
stages {
stage('test') {
steps {
script {
def job_exec_details = build job: 'build_job'
if (job_exec_details.status == 'Failed') {
echo "JOB FAILED"
}
}
}
}
}
}
I have a pipeline that executing build job, how can I get Job result in jenkins pipeline ?
It should be getResult() and status should be FAILURE not Failed.
so your whole code should be like this
pipeline {
agent { label 'master' }
stages {
stage('test') {
steps {
script {
def job_exec_details = build job: 'build_job', propagate: false, wait: true // Here wait: true means current running job will wait for build_job to finish.
if (job_exec_details.getResult() == 'FAILURE') {
echo "JOB FAILED"
}
}
}
}
}
}
Where is a second way of getting results:
pipeline {
agent { label 'master' }
stages {
stage('test') {
steps {
build(job: 'build_job', propagate: true, wait: true)
}
}
}
post {
success {
echo 'Job result is success'
}
failure {
echo 'Job result is failure'
}
}
}
}
You can read more about 'build' step here
In jenkins I have a choice:
choice(name: 'SERVICE', choices: ['SERVICE1', 'SERVICE2', 'SERVICE3', 'SERVICE4', 'SERVICE5', 'SERVICE6'], description: 'service')
Is there a way to set a variables depending of the above choice?
Something like this:
IF SERVICE == SERVICE1 then SERVICE_ID == SERVICE1_ID
IF SERVICE == SERVICE2 then SERVICE_ID == SERVICE2_ID
I'm struggling to find a plugin for this but I don't mind hardcoding in into jenkinsfile like above.
Done it
pipeline {
agent any
parameters {
choice(name: 'SERVICE', choices: ['Service1', 'Service2', 'Service3', 'Service4', 'Service5'], description: 'service')
}
stages {
stage('Stage 1') {
steps {
echo "This is Stage 1"
script {
if (env.SERVICE == 'Service1') {
echo 'You selected Service1'
} else {
echo 'You selected Some other service'
}
}
}
}
stage('Stage 2') {
steps {
echo "This is Stage 2"
script {
if (env.SERVICE == 'Service1') {env.SERVICE_ID = 'Service1_ID'}
if (env.SERVICE == 'Service2') {env.SERVICE_ID = 'Service2_ID'}
if (env.SERVICE == 'Service3') {env.SERVICE_ID = 'Service3_ID'}
if (env.SERVICE == 'Service4') {env.SERVICE_ID = 'Service4_ID'}
if (env.SERVICE == 'Service5') {env.SERVICE_ID = 'Service5_ID'}
echo "Service is ${env.SERVICE}"
echo "Service ID is ${env.SERVICE_ID}"
// Here goes some script you want to run
// For example:
// container('docker') {
// sh """
// some bash command with ${env.SERVICE_ID}
// """
// }
}
}
}
stage('Stage 3') {
steps {
echo "This is Stage 3"
}
}
stage ('Stage 4') {
steps {
echo "This is Stage 4"
}
}
}
}
Im readind a shell script file /tmp/cmd_list.sh with groove script and creating a dynamic stage to build.
The content of /tmp/cmd_list.sh is:
ls
pwd
aaaaaa
who
Only "aaaaaa" mut fail to execute (exit code 127).
My problem is, all stages are marked as failed, but when i see the log, comands such as "ls", "pwd" and "who" work fine fine and return code is 0.
I tried to foce stage status for box, but without sucess ...
My Groove script (Jenkinsfile):
import hudson.model.Result
node('master') {
stage ('\u27A1 Checkout'){
sh "echo 'checkout ok'"
}
def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
for (CMDRUN in BUILD_LIST) {
def status;
try {
node{
stage(CMDRUN) {
println "Building ..."
status = sh(returnStatus: true, script: CMDRUN )
println "---> EX CODE: "+ status
if(status == 0){
currentBuild.result = 'SUCCESS'
currentBuild.rawBuild.#result = hudson.model.Result.SUCCESS
}
else{
currentBuild.result = 'UNSTABLE'
currentBuild.rawBuild.#result = hudson.model.Result.UNSTABLE
}
def e2e = build job:CMDRUN, propagate: false
}
}
}
catch (e) {
println "===> " + e
currentBuild.result = 'UNSTABLE'
println "++++> EX CODE: "+ status
if(status == 0){
println "++++> NEW STATUS: "+ status
currentBuild.rawBuild.#result = hudson.model.Result.SUCCESS
currentBuild.result = 'SUCCESS'
}
else{
println "++++> NEW STATUS: "+ status
currentBuild.rawBuild.#result = hudson.model.Result.UNSTABLE
}
}
}
}
And the result is:
Anyone can help me to show right status?
Thank you!
I changed my script and now work as expected!
new code:
node('master') {
def build_ok = true
stage ('\u27A1 Checkout'){
sh "echo 'checkout ok'"
}
def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
for (CMDRUN in BUILD_LIST) {
try {
stage(CMDRUN) {
println "Building ..."
sh CMDRUN
}
}
catch (e) { build_ok = false }
}
if(build_ok) { currentBuild.result = "SUCCESS" }
else { currentBuild.result = "FAILURE" }
}
expected Result
Small improvement on waldir's answer
node('master') {
def build_ok = true
stage ('\u27A1 Checkout'){
sh "echo 'checkout ok'"
}
def BUILD_LIST = readFile('/tmp/cmd_list.sh').split()
for (CMDRUN in BUILD_LIST) {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
stage(CMDRUN) {
println "Building ..."
sh CMDRUN
}
}
}
if(build_ok) { currentBuild.result = "SUCCESS" }
else { currentBuild.result = "FAILURE" }
}