Does not work credentials in Jenkins pipeline - jenkins

I have created credentials (method: username and password) in Jenkins with name wwe_hello.
For test, i created pipeline with name test:
pipeline {
agent {label 'slave1'}
environment {
CREDS = credentials("wwe_hello")
}
stages {
stage('WWE') {
steps {
sh 'echo "$CREDS"'
}
}
}
}
In result i have:
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on slave1 in /var/lib/jenkins/workspace/test
[Pipeline] {
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: wwe_hello
Finished: FAILURE
Where, i have error. I am doing everything according to working examples and documentation. But i don't understand, why it does not work.

Look at the pipeline step documentation for withCredentials. You don't need to create the environment variable with env - withCredentials does it for you:
pipeline {
agent any
stages {
stage('only') {
steps {
withCredentials([
usernamePassword(
credentialsId: 'CRED',
usernameVariable: 'USER',
passwordVariable: 'PASS'
)]) {
sh '''
echo "The username is: ${USER}"
echo "The password is : ${PASS}"
'''
}
}
}
}
}

you need to create credentials with name "wwe_hello"
Go to credentials Manager
Under stores scoped to jenkins, select jenkins
Select global credentials
Select add credentials
give credentails (see in the dropdown, secret text has been selected)

Related

Error: (Stage "Deploy to Dev" skipped due to when conditional) on Jenkins

I am using Jenkins and I would like to deploy my application according to the git branch. Before adding the "when" statements, it runs successfully but as soon as I add the "when" statements, Jenkins runs successfully but returns a clause that makes the deployment not complete and it is shown thus:
Stage "Deploy to Dev" skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Deploy to Staging)
[Pipeline] input
Deploy staging deployment?
Proceed or Abort
Approved by admin
Stage "Deploy to Staging" skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Deploy to Production)
[Pipeline] input
Deploy production deployment?
Proceed or Abort
Approved by admin
Stage "Deploy to Production" skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Also, my Jenkins file part for the dev environment is shown thus:
stage('Deploy to Dev') {
when {branch 'dev'}
environment {
KUBECONFIG = credentials('kubeconfig')
}
steps {
sh 'kubectl --kubeconfig=${KUBECONFIG} --namespace=${DEV_ENVIRONMENT} --record deployment/api set image deployment/api api=wizelinedevops/samuel:${BUILD_NUMBER}'
}
}
stage('Deploy to Staging') {
when {branch 'dev'}
input{message "Deploy staging deployment?"}
environment {
KUBECONFIG = credentials('kubeconfig')
}
steps {
sh 'kubectl --kubeconfig=${KUBECONFIG} --namespace=${STAGING_ENVIRONMENT} --record deployment/api set image deployment/api api=wizelinedevops/samuel:${BUILD_NUMBER}'
}
}
stage('Deploy to Production') {
when {branch 'master'}
input{message "Deploy production deployment?"}
environment {
KUBECONFIG = credentials('kubeconfig')
}
steps {
sh 'kubectl --kubeconfig=${KUBECONFIG} --namespace=${PROD_ENVIRONMENT} --record deployment/api set image deployment/api api=wizelinedevops/samuel:${BUILD_NUMBER}'
}
}
The screenshot is shown below:
screenshot
You have to use a multibranch pipeline, see documentation.
branch Execute the stage when the branch being built matches the branch pattern (ANT style path glob) given, for example: when { branch
'master' }. Note that this only works on a multibranch Pipeline.

How to use jenkins use environment variables in parameters in a Pipeline

I'm trying to use "JOB_BASE_NAME" jenkins environmental variable in a parameter's path in a pipeline script that gets set will building the project.
example: string(defaultValue: "/abc/test/workspace/test_${JOB_BASE_NAME}/sample", description: 'test', name: 'HOME')
but while executing the ${JOB_BASE_NAME} is not getting replaced by the value(jenkins job name). I'm unsure if I'm setting the jenkins environmental variable in the path of the parameter correctly.
thank you!
I have replicated your use case and it works for me. This is the section of code
node {
stage ('test') {
sh "echo ${HOME}"
}
}
and this is the output - (my Job name was stackoverflow)
[Pipeline] { (hide)
[Pipeline] stage
[Pipeline] { (test)
[Pipeline] sh
+ echo /abc/test/workspace/test_stackoverflow/sample
/abc/test/workspace/test_stackoverflow/sample
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Check the picture of how I set the String parameter.

Trouble reading Secrets from Jenkins Credential Manager in Multi Branch Pipeline job using Credential Parameter

I have a Jenkins multi branch pipeline job that uses a secret value in Jenkinsfile:
pipeline {
agent any
stages {
stage('Test') {
steps {
echo "DOCKER_REGISTRY_USER is ${env.DOCKER_REGISTRY_USER_NSV}"
}
}
}
}
The secret value is stored in Credentials Manager as secret text with the ID DOCKER_REGISTRY_USER_NSV:
I'm trying to read this value in Jenkinsfile as shown above but I get the following output that prints out the value null for my secret:
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] echo
DOCKER_REGISTRY_USER is null
[Pipeline] sh
I also tried referencing the secret text in my pipeline like this:
echo "DOCKER_REGISTRY_USER is ${DOCKER_REGISTRY_USER_NSV}"
But then I get this error when running the Jenkins job:
groovy.lang.MissingPropertyException: No such property: DOCKER_REGISTRY_USER_NSV for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:264)
I think I need to bind that credential to the job but I don't see an option to do that for a Multi-Branch Pipeline job, the way you can for a Freestyle or Pipeline job.
How can I use a secret credential in a Multi Branch Pipeline job?
You can use credentials() helper method to archive your purpose.
pipeline {
agent any
environment {
DOCKER_REGISTRY_USER = credentials('DOCKER_REGISTRY_USER_NSV')
// put the ID of credential as credentials()'s parameter.
}
stages {
stage('Test') {
steps {
echo "DOCKER_REGISTRY_USER is ${DOCKER_REGISTRY_USER}"
}
}
}
}

Trouble reading Secrets from Jenkins Credential Manager in Pipeline job using Credential Parameter

I have a Jenkins Pipeline job that uses a secret value in Jenkinsfile:
pipeline {
agent any
stages {
stage('Test') {
steps {
echo "DOCKER_REGISTRY_USER is $DOCKER_REGISTRY_USER"
}
}
}
}
The secret value is stored in Credentials Manager as secret text with the ID DOCKER_REGISTRY_USER. I parameterized my Jenkins pipeline job by referring to the secret text from Credential Manager:
I'm trying to read this value in Jenkinsfile as shown above but I get the following output:
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] echo
DOCKER_REGISTRY_USER is DOCKER_REGISTRY_USER
[Pipeline] sh
It just prints the ID of the credential but not the value. I thought it might be a Jenkins security mechanism but when I try and do something similar with a Freestyle job, I get a masked output (******).
But what DOES work is if I use a parameter in my pipeline job but instead of a Credential Parameter I use a String Parameter or Password Parameter - then the secret value gets printed out:
So I'm either not using the Credential Parameter correctly or there's a bug.
That is how it's supposed to work. To actually make use of that reference to a Jenkins credentials, you need to use credentials binding plugin. For example, if your credentials are of type 'Username and password' you'll do as follows:
withCredentials([userNamePassword: $DOCKER_REGISTRY_USER, usernameVariable: 'USER', passwordVariable: 'PASSWORD']) {
echo "DOCKER_REGISTRY_USER is $USER and password is $PASSWORD"
}
Nota that Jenkis will not show private credentials in the output, but the value it is properly populated.

Hiding password in Jenkins pipeline script

I'm trying to mask a password in my Jenkins build.
I have been trying the mask-passwords plugin.
However, this doesn't seem to work with my Jenkins pipeline script, because if I define the password PASSWD1 and then I use it in the script like this ${PASSWD1}, I am getting:
No such DSL method '$' found among steps [addToClasspath, ansiColor, ansiblePlaybook, ....]
If I use env.PASSWD1, then its value will be resolved to null.
So how should I mask a password in a Jenkins pipeline script?
The simplest way would be to use the Credentials Plugin.
There you can define different types of credential, whether it's a single password ("secret text"), or a file, or a username/password combination. Plus other plugins can contribute other types of credentials.
When you create a credential (via the Credentials link on the main Jenkins page), make sure you set an "ID". In the example below, I've called it my-pass. If you don't set it, it will still work, Jenkins will allocate an opaque UUID for you instead.
In any case, you can easily generate the required syntax with the snippet generator.
withCredentials([string(credentialsId: 'my-pass', variable: 'PW1')]) {
echo "My password is '${PW1}'!"
}
This will make the password available in the given variable only within this block. If you attempt to print the password, like I do here, it will be masked.
Looking at this issue, https://issues.jenkins-ci.org/browse/JENKINS-27392, you should be able to do the following:
node {
wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: '123ADS', var: 'SECRET']]]) {
echo env['SECRET'];
}
}
However, if you look at the last comments in that issue it doesn't work, seems like a bug. However, if you know the secret and accidentally print int in the logs, the it is hidden, like this:
node {
wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: '123ADS', var: 'SECRET']]]) {
echo "123ADS";
}
}
This produces:
[Pipeline] node
Running on master in workspace/pl
[Pipeline] {
[Pipeline] wrap
[Pipeline] {
[Pipeline] echo
********
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Regarding the error you are getting, No such DSL method '$' found among steps ..., I'm just guessing but you are probably using ${VAR} directly in the pipeline script, ${...} is only relevant inside strings in groovy.
EDIT:
Or you can use the Credentails Plugin and pipeline step withCredentials:
// Credential d389273c-03a0-45af-a847-166092b77bda is set to a string secret in Jenkins config.
node {
withCredentials([string(credentialsId: 'd389273c-03a0-45af-a847-166092b77bda', variable: 'SECRET')]) {
bat """
if ["${SECRET}"] == ["123ASD"] echo "Equal!"
""";
}
}
This results in:
[Pipeline] node
Running on master in workspace/pl
[Pipeline] {
[Pipeline] withCredentials
[Pipeline] {
[Pipeline] bat
[pl] Running batch script
workspace/pl>if ["****"] == ["****"] echo "Equal!"
"Equal!"
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Note that this plugin binds the variable directly to the closure and not the environment as the other, e.g. I can use the variable SECRET directly.

Resources