Jenkins groovy if condition within steps does not work - jenkins

I have the following stage in groovy script of a jenkins job":
stage('Remove servers') {
when {
expression { params.DO_REMOVE == true }
}
steps {
script {
parallel RemoveSource: {
sh """set -x
export KUBECONFIG=${source_config}
kubectl get ns ${source_namespace} || exists="False"
"""
echo "${exists}"
if ("${exists}" != "False") {
build job: 'RemoveFCC',
parameters: [string(name: 'Branch', value: Branch),
booleanParam(name: 'build_ansible', value: false),
string(name: 'pipeline', value: 'yes')]
} else {
echo "Server does not exist. skipped fcc run"
}
},
RemoveTarget: {
sh """set -x
export KUBECONFIG=${target_config}
kubectl get ns ${target_namespace} || exists="False"
"""
echo "${exists}"
if ("${exists}" != "False") {
build job: 'RemoveFCC',
parameters: [string(name: 'Branch', value: Branch),
booleanParam(name: 'build_ansible', value: false),
string(name: 'pipeline', value: 'yes')]
} else {
echo "Server does not exist. skipped fcc run"
}
}
}
}
}
Even though echo "${exists}" prints False the if condition is still getting executed. I am not sure what am I missing here. Tried things like adding when instead of if.

Related

How to pass file parameters to upstream pipeline job in build step plugin

def BUILD_USER = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
pipeline {
agent {label "master"}
parameters {
string(name: 'BUILD', defaultValue: '123')
booleanParam(name: 'Deploy', defaultValue: 'true')
booleanParam(name: 'Upgrade_Config', defaultValue: 'true')
booleanParam(name: 'SchemaComparison', defaultValue: 'false')
booleanParam(name: 'Publish_Server', defaultValue: 'false')
}
stages {
stage ('Start Deployment') {
agent {label "master"}
steps{
script{
sh '''
rm -rf /params/parameters
cd /params
echo $BUILD_USER
python3 buildParameters.py --Build=$BUILD --Publish_VM=$Publish_Server --userName=BUILD_USER --Upgrade_Config=$Upgrade_Config
'''
file = readFile('/params/parameters.txt')
}
}
}
stage ('UpgradeConfigurations') {
when {
expression { params.Deploy == true }
}
agent {label "master"}
environment {
file = "${file}"
}
steps{
script{
println("${file}")
build(job: 'UpgradeConfigurations', parameters: [ file(name: 'parameters', file: "${file}"), string(name: 'build_uniqe_id' , value: "${BUILD_USER}") , booleanParam(name: 'Deploy' , value: "${Deploy}") , booleanParam(name: 'SchemaComparison' , value: "${SchemaComparison}")], propagate: false, wait: false )
}
}
}
}
}
buildParameters.py file generate some additional parameters in parameters.txt file on master vm and I am trying to pass it to the upstream job UpgradeConfigurations
Upstream job UpgradeConfigurations is getting started but file parameters are not getting passed as parameters to it.
I have tried using base64file as well but no luck.
Referred Build Plugin doc:
https://www.jenkins.io/doc/pipeline/steps/pipeline-build-step/

How to run the same scripted pipeline multiple times in jenkins?

I went over the internet to find out a way to run the same pipeline multiple times but have not found an answer.
Basically, the pipeline has 5 stages and I want this pipeline to run 5 times, each iteration of the pipeline will execute the stages in the same order in the code.
node{
def build_ok = true
try{
stage('#1 SoftSync 4.5.1 CPU Usage Test') {
build job: 'SoftSync_4.5.1_CPU_Usage_Test', parameters: [string(name: 'LOG_LEVEL', value: 'debug'), string(name: 'FILE_PATH', value: 'TLV_SoftSync/Management_Bundle/SoftSync_CPU_Usage_Test.robot')]
}
} catch(e) {
build_ok = false
echo e.toString()
}
try{
stage ('#2 SoftSync 4.5.1 Improvments to system time management Test '){
build job: 'SoftSync_4.5.1_Improvments_To_System_TimeManagement_Test', parameters: [string(name: 'LOG_LEVEL', value: 'debug'), string(name: 'FILE_PATH', value: 'TLV_SoftSync/Management_Bundle/SoftSync_Improvments_to_system_time_management.robot')]
}
}catch(e) {
build_ok = false
echo e.toString()
}
try {
stage ('#3 SoftSync 4.5.1 Telematics and statistics Test'){
build job: 'SoftSync_4.5.1_Telematics_and_statistics_Test', parameters: [string(name: 'LOG_LEVEL', value: 'debug'), string(name: 'FILE_PATH', value: 'TLV_SoftSync/Management_Bundle/SoftSync_Telementry_and_Statistics.robot')]
}
}catch(e) {
build_ok = false
echo e.toString()
}
//try{
//stage ('#4 SoftSync 4.5.1 PTP Profiles Slave Lock Test'){
build job: 'SoftSync_4.5.1_PTP_Profiles_SlaveLock_Test', parameters: [string(name: 'LOG_LEVEL', value: 'debug'), string(name: 'FILE_PATH', value: 'TLV_SoftSync/PTP_Bundle/SoftSync_PTP_Lock_validation.robot')]
//}
//}catch(e) {
// build_ok = false
// echo e.toString()
//}
try{
stage ('#5 SoftSync 4.5.1 Alarms Test'){
build job: 'SoftSync_4.5.1_Alarms_Test', parameters: [string(name: 'LOG_LEVEL', value: 'debug'), string(name: 'FILE_PATH', value: 'TLV_SoftSync/Management_Bundle/SoftSync_Alarms_Test.robot')]
}
}catch(e) {
build_ok = false
echo e.toString()
}
if(build_ok) {
currentBuild.result = "SUCCESS"
} else {
currentBuild.result = "FAILURE"
}
post{
always{
junit allowEmptyResults: true, testResults: '/var/lib/jenkins/output/*.xml'
}
}
}
I have seen some usages with arrays and .each function but all for parallel usages witch is not help full in my case...
any ideas?
You can wrap your stages with a loop. Something like below.
node {
def itrList = ["Run1", "Run2", "Run3"]
itrList.each { val ->
def build_ok = true
try {
stage("#1 SoftSync 4.5.1 CPU Usage Test with $val") {
echo "111111"
}
} catch (e) {
build_ok = false
echo e.toString()
}
try {
stage("#2 SoftSync 4.5.1 Improvments to system time management Test with $val") {
echo "22222222222"
}
} catch (e) {
build_ok = false
echo e.toString()
}
if (build_ok) {
currentBuild.result = "SUCCESS"
} else {
currentBuild.result = "FAILURE"
}
}
}

can we run Jenkins file in pipeline?

I've Pipeline Generic Webhook from Bitbucket, this is a job to trigger another job.
currentBuild.displayName = "Generic-Job-#" + env.BUILD_NUMBER
pipeline {
agent any
triggers {
GenericTrigger(
genericVariables: [
[key: 'actorName', value: '$.actor.display_name'],
[key: 'TAG', value: '$.push.changes[0].new.name'],
[key: 'REPONAME', value: '$.repository.name'],
[key: 'GIT_URL', value: '$.repository.links.html.href'],
],
token: '11296ae8d97b2134550f',
causeString: ' Triggered on $actorName version $TAG',
printContributedVariables: true,
printPostContent: true
)
}
stages {
stage('Build Job DEVELOPMENT') {
when {
expression { return params.TARGET_ENV == 'DEVELOPMENT' }
}
steps {
build job: 'DEVELOPMENT',
parameters: [
[$class: 'StringParameterValue', name: 'FROM_BUILD', value: "${BUILD_NUMBER}"],
[$class: 'StringParameterValue', name: 'TAG', value: "${TAG}"],
[$class: 'StringParameterValue', name: 'GITURL', value: "${GIT_URL}"],
[$class: 'StringParameterValue', name: 'REPONAME', value: "${REPONAME}"],
[$class: 'StringParameterValue', name: 'REGISTRY_URL', value: "${REGISTRY_URL}"],
]
}
}
}
}
Another Pipeline
pipeline {
agent any
stages {
stage('Cleaning') {
steps {
cleanWs()
}
}
def jenkinsFile
stage('Loading Jenkins file') {
jenkinsFile = fileLoader.fromGit('Jenkinsfile', "${GIT_URL}", "${TAG}", null, '')
}
jenkinsFile.start()
}
}
can i run Jenkinsfile in Pipeline ? Because every project I make has a different Jenkinsfile, it can't be the same, but when I run this it doesn't execute the Jenkinsfile
it works for me :D
Sample Pipeline
stage 'Load a file from GitHub'
def jenkinsFile = fileLoader.fromGit('<path-jenkinsfile>', "<path-git>", "<branch>", '<credentials>', '')
stage 'Run method from the loaded file'
jenkinsFile
pipeline {
agent any
stages {
stage('Print Hello World Ke #1') {
steps {
echo "Hello Juan"
}
}
}
}
before run the pipeline, you must install plugin "Pipeline Remote Loader Plugin Version"

Extended Choice Parameter implementation

I'm setting up a new job in which we are required to select Multiple values. Need to select Service1 and Service2...
Went through link How to pass multi select value parameter in Jenkins file(Groovy)
However, I am not sure how to pass values in my Jenkinsfile
A snippet of Jenkinsfile
stage('parallel'){
parallel(
"service1": {stage('service1-deployment') {
if (params.ServiceName == 'Service1' || params.ServiceName == 'ALL'){
b = build(job: 'job name', parameters: [string(name: 'ENVIRONMENT', value: TARGET_ENVIRONMENT),string(name: 'IMAGE_TAG', value: value)], propagate: false).result
if(b=='FAILURE'){
echo "job failed"
currentBuild.result = 'UNSTABLE'
}
}
}
},
"service2": {stage('service2t') {
if (params.ServiceName == 'service2' || params.ServiceName == 'ALL'){
b = build(job: 'Job name', parameters: [string(name: 'ENVIRONMENT', value: TARGET_ENVIRONMENT),string(name: 'IMAGE_TAG', value: value)], propagate: false).result
if(b=='FAILURE'){
echo "job failed"
currentBuild.result = 'UNSTABLE'
}
}
}
},
I see that you're using declarative pipeline syntax for your job.
So, if the accepted answer for that question with booleanParam is useful for you, then you can use it inside parameters section (see the official documentation for more details):
pipeline {
agent any
parameters {
booleanParam(defaultValue: false, name: 'ALL', description: 'Process all'),
booleanParam(defaultValue: false, name: 'OPTION_1', description: 'Process option 1'),
booleanParam(defaultValue: false, name: 'OPTION_2', description: 'Process options 2'),
}
stages {
stage('Example') {
steps {
echo "All: ${params.ALL}"
echo "Option 1: ${params.OPTION_1}"
echo "Option 2: ${params.OPTION_2}"
}
}
}
}
However, if you want to use extended choice parameter with multiselect input, you need to use scripted pipeline syntax, see this example (already mentioned here).

Jenkins build base don parameter value

Say my Jenkinsfile is like this:
pipeline {
agent any
parameters {
string(name: 'flag', defaultValue: 'stop', description: 'How should I greet the world?')
}
stages {
stage('Example') {
steps {
checkout scm
sh "echo \"Current Branch: ${env.BRANCH_NAME}.... \""
sh
if [[ $(params.flag) == "run" ]]; then
echo "something"
fi
This is failing. It is not able to read $(params.flag) inside steps. How can I do this?? I am using multibranch pipeline job type.
It's like this (i think it was mostly the multi-line sh syntax that was off):
pipeline {
agent { label 'docker' }
parameters {
string(name: 'flag', defaultValue: 'stop', description: 'How should I greet the world?')
}
stages {
stage('Example') {
steps {
checkout scm
sh "echo \"Current Branch: ${env.BRANCH_NAME}.... \""
sh """
if [[ "${params.flag}" == "run" ]]; then
echo "something"
fi
"""
}
}
}
}

Resources