How to run the same scripted pipeline multiple times in jenkins? - 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"
}
}
}

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/

Jenkins groovy if condition within steps does not work

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.

Jenkins pipeline execute job and get status

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

how to get the build number from a triggered job

In my jenkins pipeline, i trigger a job like this:
stage('Run downstream') {
parallel {
stage('partA') {
steps {
script {
if (env.GIT_BRANCH == 'origin/master') {
build job: 'downstream', wait: true
}
}
}
}
stage('partB') {
steps {
script {
if (env.GIT_BRANCH == 'origin/master') {
build job: 'downstream', wait: true, parameters: [
string(name: 'param', value: 'overriden value')
]
}
}
}
}
}
}
the downstream job creates an artifact which I'd like to copy to the triggering job. How would I get the build number for each invocation of the job so that I can pull their artifacts?
I changed:
build job: 'downstream', wait: true
to:
triggeredBuild = build job: 'downstream', wait: true
buildNumber = triggeredBuild.getNumber()

BlueOcean is not asking for some of my jenkins multibranch parameters

I recently modified the Jenkinsfile of my branch(for now, I've only one branch with this jenkins branch).
When I try to launch the multibranch pipeline for this branch, I've a lot of parameters requested, but not the new one I've added.
If I go into Jenkins(not BlueOcean), in the configuration I see them, and if I start a build from there, I also see them.
Here is my Jenkinsfile:
pipeline {
agent {
node{
label 'windows-node'
customWorkspace "D:\\ws\\${env.BRANCH_NAME}"
}
}
options{
skipDefaultCheckout()
}
triggers{
pollSCM 'H 23 * * *'
}
stages {
stage('Initialization started'){
steps{
echo "Job parameters:\n\t- Build X86: ${params.buildX86}\n\t- Build X64: ${params.buildX64}\n\t- Commit Version changes: ${params.commitVersionChanges}.${env.BUILD_NUMBER}\n\t- Setup Version: ${params.version}\n\t- Setup Configuration: ${params.setupConfiguration}\nCurrent repository: ${workspace}"
}
}
stage('Checkout'){
steps{
echo "Custom checkout: ${env.BRANCH_NAME}"
checkout scm
}
}
stage('ABC Solution Pre-build') {
steps {
changeAsmVer "${params.version}.${env.BUILD_NUMBER}"
bat 'nuget.exe restore Solution\\ABC.sln'
powershell 'ContinuousIntegration\\Scripts\\ChangeBindingVersion.ps1 "HDAPluginNet4" "Src\\Clients\\OpcServer\\Xms.OpcHda.Server\\HDANSrv.Net4.exe.config"'
}
}
stage('Preparing SonarQube'){
when{
expression{ params.runTests == true && env.BRANCH_NAME == 'develop'}
}
steps{
withSonarQubeEnv('XYZ SonarQube') {
script{
def sqScannerMsBuildHome = tool 'SonarQube.Runner-3.0'
}
bat "${sqScannerMsBuildHome}\\SonarQube.Scanner.MSBuild.exe begin /k:ABC /n:ABC /v:${params.version}.${env.BUILD_NUMBER} /d:sonar.host.url=%SONAR_HOST_URL% /d:sonar.login=%SONAR_AUTH_TOKEN% /d:sonar.cs.nunit.reportsPaths=TestResult.xml /d:sonar.cs.dotcover.reportsPaths=dotcover.html"
}
}
}
stage('Build ABC Solution') {
steps{
bat "\"${tool 'MSBUILD15'}\" Solution\\ABC.sln /p:Configuration=${params.setupConfiguration} /p:Platform=\"Any CPU\" /t:Rebuild"
}
}
stage('ABC Solution Pre-setup') {
when{
expression{ params.buildX64 == true || params.buildX86 == true}
}
steps{
bat "\"Src\\Obfuscation\\XmsApplicationsObfuscation\\Release\\obfuscationProcess.cmd\" \"${workspace}\" \"${workspace}\\output\\dotfuscator.zip\" \"XXXXXXXX\""
bat "Doc\\BuildDocumentation.bat"
}
}
stage('X64 Setup build') {
when{
expression{ params.buildX64 == true}
}
steps{
bat "\"${tool 'MSBUILD15'}\" Solution\\SetupWix.sln /p:Configuration=${params.setupConfiguration} /p:Platform=x64 /t:Rebuild /p:Version=\"${params.version}.${env.BUILD_NUMBER}\""
bat "move SetupWix\\SetupWix\\bin\\Release\\en-us\\ABCSetup.msi SetupWix\\SetupWix\\bin\\Release\\en-us\\ABCSetup_64_bit.msi"
}
}
stage('X86 Setup build') {
when{
expression{ params.buildX86 == true}
}
steps{
bat "\"${tool 'MSBUILD15'}\" Solution\\SetupWix.sln /p:Configuration=${params.setupConfiguration} /p:Platform=x86 /t:Rebuild /p:Version=\"${params.version}.${env.BUILD_NUMBER}\""
bat "move SetupWix\\SetupWix\\bin\\Release\\en-us\\ABCSetup.msi SetupWix\\SetupWix\\bin\\Release\\en-us\\ABCSetup_32_bit.msi"
}
}
stage('Post-setup'){
when{
expression{ params.buildX64 == true || params.buildX86 == true}
}
steps{
powershell 'ContinuousIntegration\\Scripts\\MoveSetups.ps1'
}
}
stage('Commit version change'){
when{
expression{ params.commitVersionChanges == true}
}
steps{
bat 'git add "./*AssemblyInfo.*"'
bat 'git commit -m "Assembly infos changed by Jenkins"'
bat "git push origin HEAD:${env.BRANCH_NAME}"
}
}
stage('Testing'){
when{
expression{ params.runTests == true}
}
steps{
bat 'dotcover.exe analyze ContinuousIntegration/DotCoverConfig.xml'
nunit testResultsPattern: 'TestResult.xml'
}
}
stage('Finishing SonarQube'){
when{
expression{ params.runTests == true && env.BRANCH_NAME == 'develop'}
}
steps{
withSonarQubeEnv('XYZ SonarQube') {
script{
def sqScannerMsBuildHome = tool 'SonarQube.Runner-3.0'
}
bat "${sqScannerMsBuildHome}\\SonarQube.Scanner.MSBuild.exe end"
}
}
}
}
post{
failure {
emailext body: "<b>Error while excuting the following job</b><br><br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br>Build URL: ${env.BUILD_URL}", mimeType: 'text/html', recipientProviders: [brokenTestsSuspects(), brokenBuildSuspects()], subject: "ERROR CI: Project name -> ${env.JOB_NAME}"
}
unstable{
emailext body: "<b>Error while excuting the following job</b><br><br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br>Build URL: ${env.BUILD_URL}", mimeType: 'text/html', recipientProviders: [brokenTestsSuspects(), brokenBuildSuspects()], subject: "ERROR CI: Project name -> ${env.JOB_NAME}"
}
}
parameters {
booleanParam(name: 'buildX86', defaultValue: false, description: 'Build for X86 platform')
booleanParam(name: 'buildX64', defaultValue: true, description: 'Build for X64 platform')
booleanParam(name: 'commitVersionChanges', defaultValue: false, description: 'Commit the version changes')
booleanParam(name: 'runTests', defaultValue: false, description: 'Run unit tests')
string(name: 'version', defaultValue: '3.6.0', description: 'Version of the setup to build')
choice(name: 'setupConfiguration', choices: '''Release
Debug''', description: 'Setup configuration to use')
}
}
The "new" parameters for which I don't get any request(only in BlueOcean) is the "runTests".
What can I do to get them? I tried to reboot, didn't changed anything.
According to the documentation example, parameters {} needs to be declared before stages{}, otherwise it does not know what values to place in the template variables because scripted pipelines are serially executed from top to bottom.
Also if this was just added to a Jenkinsfile, you may need to run it twice, it won't know the first time that there are params to deal with.

Resources