Jenkins build base don parameter value - jenkins

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
"""
}
}
}
}

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.

How to populate Jenkins build parameter values from URL in Jenkins declarative pipeline

How can I populate choice parameter from the URL?
I'm able to download and save values inside environment variable but if I try to use it I get error:
if I replace choicesFoo with choicesURL in parameters section, I get error.
Here is my pipeline:
def choicesFoo = ['x','y']
pipeline{
agent {
node {
label 'LinuxOpt'
}
}
environment{
choicesUrl = sh(script: "curl http://example.com/foo.txt", returnStdout: true)
}
parameters {
choice(name: 'CHOICE', choices: choicesFoo, description: 'Pick an option')
}
stages {
stage('Build') {
steps {
sh 'echo run build'
sh "echo ${choicesUrl}"
}
}
}
}
You can try preparing your choices before declaring a pipeline, e.g. like this:
def choicesUrl
node('Prepare Choices') {
stage('Get Choices') {
choicesUrl = sh(
script: "curl http://example.com/foo.txt",
returnStdout: true).trim()
}
}
pipeline{
agent { node { label 'LinuxOpt' } }
parameters {
choice(name: 'CHOICE', choices: choicesUrl, description: 'Pick an option')
}
stages {
stage('Build') {
steps {
sh 'echo run build'
sh "echo ${choicesUrl}"
}
}
}
}

How can I set Agent label dynamically?

What I'm trying to achieve here to run multiple stages in same node which will get captured in initial stage, then will be used by some of the following stages as required.
Below is the sample Jenkinsfile:
pipeline {
agent {
label 'redhat_linux'
}
stages {
stage('build') {
options {
timeout(time: 100, unit: 'SECONDS')
}
input {
message "Should we continue?"
ok "Yes, we should."
submitter "user1,user2"
parameters {
string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
}
}
steps {
script{
agentName = "${NODE_NAME}"
echo "The node name is :: ${agentName}"
}
sh 'pwd;ls -ltr'
}
}
stage("promote"){
agent{
node {
label "${agentName}"
}
}
steps{
script{
echo "The node name is :: ${agentName}"
}
sh 'echo "This is a promote step " '
}
}
}
}
I'm facing following error:
groovy.lang.MissingPropertyException: No such property: agentName for class: groovy.lang.Binding
I did tried solution from below link, but it didn't work.
In a declarative jenkins pipeline - can I set the agent label dynamically?
Jenkins version: CloudBees Jenkins Enterprise 2.121.3.1

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