Passing credentials to downstream build step in Jenkins pipeline - jenkins

We're trying to start a downstream build which expects "UserName" and "UserPassword" as parameters.
withCredentials([usernamePassword(
credentialsId: params.deployCredentialsId,
usernameVariable: 'MY_USER',
passwordVariable: 'MY_PASS',
)]) {
build(job: "deploy/nightly",
parameters: [stringParam(name: "UserName", value: MY_USER), password(name: "UserPassword", value: MY_PASS),
... more parameters
)
}
but the downstream job never sees the UserName / UserPassword parameters. Is there a bug in the above definition, or should I look at the downstream job?

You need to look in the downstream job. It should have a 'parameters' block that looks like:
parameters {
string(defaultValue: "", description: 'foo', name: "UserName")
string(defaultValue: "", description: 'foo', name: "UserPassword")
}
Then in your stage you can do this:
stage('PrintParameter'){
steps{
sh 'echo ${UserName}'
}
}

Let's say you have 2 Jenkins pipeline jobs called job-A and job-B and you want to call job-B from job-A by passing some parameters and you want to access those on job-B. The example would look like below:
job-A
pipeline {
agent any;
stages {
stage('Build Job-B') {
steps {
build(job: "job-B", parameters: [string(name:"username",value: "user"),password(name:"password",value: "fake")], propagate: false, wait: true, quietPeriod: 5)
}
}
}
}
job-B
pipeline {
agent any;
stages {
stage('echo parameter') {
steps {
sh "echo $params"
}
}
}
}
Note-
params is by default available in all pipeline job, no matter whether you use a scripted pipeline or a declarative pipeline.
you no need to define any parameter in the downstream job

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/

Use Jenkins WORKSPACE environment variable in Jenkins declarative pipeline parameter

Is there a way to use Jenkins WORKSPACE environment variable in Jenkins declarative pipeline parameters?
Below attempt failed.
pipeline {
parameters {
extendedChoice description: 'Template in project',
multiSelectDelimiter: ',', name: 'TEMPLATE',
propertyFile: env.WORKSPACE + '/templates.properties',
quoteValue: false, saveJSONParameterToFile: false, type: 'PT_MULTI_LEVEL_SINGLE_SELECT',
value: 'Project,Template', visibleItemCount: 6
...
}
stages {
...
}
propertyFile: '${WORKSPACE}/templates.properties' didn't work either.
The environment variable can be accessed in various place in Jenkinsfile like:
def workspace
node {
workspace = env.WORKSPACE
}
pipeline {
agent any;
parameters {
string(name: 'JENKINS_WORKSPACE', defaultValue: workspace, description: 'Jenkins WORKSPACE')
}
stages {
stage('access env variable') {
steps {
// in groovy
echo "${env.WORKSPACE}"
//in shell
sh 'echo $WORKSPACE'
// in groovy script
script {
print env.WORKSPACE
}
}
}
}
}
The only way that worked is putting absolute path to Jenkins master workspace where properties file is located.
pipeline {
parameters {
extendedChoice description: 'Template in project',
multiSelectDelimiter: ',', name: 'TEMPLATE',
propertyFile: 'absolute_path_to_master_workspace/templates.properties',
quoteValue: false, saveJSONParameterToFile: false, type: 'PT_MULTI_LEVEL_SINGLE_SELECT',
value: 'Project,Template', visibleItemCount: 6
...
}
stages {
...
}
It seems that environment variables are not available during pipeline parameters definition before the pipeline actually triggered.

Unable to pass a parameter from one pipeline job to another

Editing the question: I am trying to run a simple pipeline job which triggers another pipeline job and sends parameter values.
I tried a simplified usecase in the example below
Piepeline - Parent
pipeline{
agent any
options {
buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')
}
stages {
stage('Invoke sample_pipleline') {
steps {
CommitID = 'e2b6cdf1e8018560b3ba51cbf253de4f33647b5a'
Branch = "master"
input id: 'Environment', message: 'Approval', parameters: [choice(choices: ['FRST', 'QA', 'PROD'], description: '', name: 'depServer')], submitter: 'FCMIS-SFTP-LBAAS', submitterParameter: 'user'
build job: 'simple_child',
parameters: [string(name: 'CommitID', value: 'e2b6cdf1e8018560b3ba51cbf253de4f33647b5a'),string(name: 'Environment', value: depServer), string(name: 'Branch', value: 'master')],
quietPeriod: 1
}
}
}
}
Pipeline - child
pipeline{
agent any
parameters {
string defaultValue: '', description: 'K', name: 'depServer'
}
options {
buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')
}
stages {
stage('CodePull') {
steps {
echo "Testing"
echo "${depServer}"
}
}
}
}
When I run the parent pipeline it did not trigger child pipeline but gave error.
Started by user ARAV
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Windows_aubale in C:\Users\arav\Documents\Proj\Automation\Jenkins\Jenkins_slave_root_directory\workspace\sample_parent2
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Invoke sample_pipleline)
[Pipeline] input
Input requested
Approved by ARAV
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: depServer for class: groovy.lang.Binding
After implementing changes suggested and with some tweaks The parent job triggers the child job but the child log shows that it doesn't receive the parameter passed.
Started by upstream project "sample_parent" build number 46
originally caused by:
Started by user ARAV
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/simple_child
[Pipeline] {
[Pipeline] stage
[Pipeline] { (CodePull)
[Pipeline] echo
Testing
[Pipeline] echo
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Please help me understand what am I doing wrong here.
Appreciate your help!!
If your child pipeline has parameter named "depServer":
parameters {
string name: 'depServer', defaultValue: '', description: ''
}
You should provide a value for it:
build job: 'simple_child',
parameters: [string(name: 'depServer', value: 'SOMETHING']
Finally, you should address it:
steps {
echo "Testing"
echo "${params.depServer}"
}
groovy.lang.MissingPropertyException: No such property: depServer for
class: groovy.lang.Binding
This means that you don't have defined a variable depServer.
Fix it by assigning the result of the input step to variable depServer:
steps {
script {
def input_env = input id: 'Environment', message: 'Approval', parameters: [choice(choices: ['FRST', 'QA', 'PROD'], description: '', name: 'depServer')], submitter: 'FCMIS-SFTP-LBAAS', submitterParameter: 'user'
build job: 'simple_child',
parameters: [string(name: 'CommitID', value: 'aa21a592d1039cbce043e5cefea421efeb5446a5'),string(name: 'Environment', value: input_env.depServer), string(name: 'Branch', value: "master")],
quietPeriod: 1
}
}
I've added a script block, to be able to create and assign a variable.
The input actually returns a HashMap that looks like this:
[depServer:QA, user:someUser]
That's why we have to write input_env.depServer as argument for the build job.
Thank you so much zett42 and MaratC! So finally the code that worked is as follows(combining both the answers):
Parent script:
pipeline{
agent any
options {
buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')
}
stages {
stage('Invoke sample_pipleline') {
steps {
script{
def CommitID
def depServer
def Branch
CommitID = 'e2b6cdf1e8018560b3ba51cbf253de4f33647b5a'
Branch = "master"
userip = input id: 'Environment', message: 'Approval', parameters: [choice(choices: ['FRST', 'QA', 'PROD'], description: '', name: 'input_env')], submitter: 'FCMIS-SFTP-LBAAS', submitterParameter: 'user'
depServer = userip.input_env
echo "${depServer}"
build job: 'simple_child',
parameters: [string(name: 'CommitID', value: "${CommitID}"),
string(name: 'Environment', value: "${depServer}"),
string(name: 'Branch', value: "${Branch}")],
quietPeriod: 1
}
}
}
}
}
Child script:
pipeline{
agent any
parameters {
string defaultValue: '', description: 'K', name: 'Environment'
}
options {
buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')
}
stages {
stage('CodePull') {
steps {
echo "Testing"
echo "${params.Environment}"
}
}
}
}

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

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