Define credential parameter in parameters in Jenkins declarative pipeline? - jenkins

I Currently using Jenkins Delarative pipeline with a parameterised build
pipeline {
agent any
parameters {
booleanParam(name: 'cleanDB',defaultValue: false,description: 'should clean db ?' )
string(name: 'host',defaultValue: 'xyx',description: 'DB Host')
}
stages {
stage('Build') {
steps {
sh 'mvn verify'
}
}
stage('Execute') {
steps {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'CREDENTIALS', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']])
{
sh "ant " +"-Ddb.clean=${params.cleanDB} -Ddb.host=${params.host} -Ddb.userid=$USERNAME \"-Ddb.password=$PASSWORD\" "
}
}
}
}
}
when i try to build with parameters it prompts only two param cleanDB,host params.i would like it to also ask which credential parameter to take.it takes only when explicitly added though UI in parameterised build.
so how can i add credential parameter in parameters can any one share an example of defining it in below syntax.
parameters {
booleanParam(name: 'cleanDB',defaultValue: false,description: 'should clean db ?' )
string(name: 'host',defaultValue: 'xyx',description: 'DB Host')
credentialParam(name: 'host',description: 'Credentials')
}

While as of today (2017-08-29) jenkins docs mention only string and boolean types of possible parameters, there is some ticket that answer this question. It says to do:
parameters {
credentials(name: 'CredsToUse', description: 'A user to build with', defaultValue: '', credentialType: "Username with password", required: true )
}
I just tried it and it works fine. When executed for the first time it doesn't ask anything, it just creates parameter for the job. After then it asks for credentials as it should.
Naturally, it works for Declarative Pipeline syntax, so must be enveloped with 'pipeline'.

Try the following:
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'CREDENTIALS', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']])
{
sh 'ant -Ddb.clean=${params.cleanDB} -Ddb.host=${params.host} -Ddb.userid=$USERNAME -Ddb.password=$PASSWORD'
}
according to the documentation on cloudbees https://support.cloudbees.com/hc/en-us/articles/204897020-Fetch-a-userid-and-password-from-a-Credential-object-in-a-Pipeline-job-

Related

what can I do on Jenkinsfile to get credentials?

I'm new to jenkins and I'm creating a jenkinsfile with a declarative pipeline that supports different parameters. I also need to access to a credential stored in Jenkins, that I created already. How can I access to this credentials though jenkinsfile? do I need to call them inside of the stage or like this is ok? I got very confused in this part :S
I saw something like this on internet:
steps {
withCredentials([usernamePassword(credentialsId: 'x'....
}
Until now I have this:
pipeline {
agent any
environment{
my_credentials = credentials('x-credentials-id')
}
stages{
stage('Setup parameters') {
steps {
parameters([
string(name: 'a', defaultValue: 'x', description: 'test'),
text(name: 'b', defaultValue: ''),
text(name: 'b2', defaultValue: ''),
text(name: 'c', defaultValue: ''),
text(name: 'c2', defaultValue: '')
])
//])
}
}
}
}
From Jenkins documentation.
Jenkins' declarative Pipeline syntax has the credentials() helper
method (used within the environment directive) which supports secret
text, username and password, as well as secret file credentials.
So basically credentials('x-credentials-id') will support the aforementioned credential types and you should be using this helper method within an Environment block. You can use this approach if you want to declare your credentials globally so they can be used anywhere in the pipeline.
example
environment {
AWS_ACCESS_KEY_ID = credentials('jenkins-aws-secret-key-id')
AWS_SECRET_ACCESS_KEY = credentials('jenkins-aws-secret-access-key')
}
For other types, you can use withCredentials directive.(This is coming from Credentials Binding plugin) Both will get the Job done.
withCredentials(bindings: [certificate(credentialsId: 'jenkins-certificate-for-xyz', \
keystoreVariable: 'CERTIFICATE_FOR_XYZ', \
passwordVariable: 'XYZ-CERTIFICATE-PASSWORD')]) {
//
}
Although it says secrettext, username and password etc are not supported with Bind Credentials plugin, you can use WithCredentials for those types as well.
withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
echo "username is $USERNAME"
}
Read more from here and here

set pipelineTriggers in Jenkinsfile to set 'Trigger builds remotely (e.g., from scripts)'

I have a Jenkinsfile and I want to set a pipelineTrigger property for my stage 'setup parameters'
#! /usr/bin/env groovy
pipeline {
agent any
stages {
stage('setup parameters'){
steps{
script{
properties([
parameters([
string(name: 'payload', defaultValue: '')
]),
pipelineTriggers(])
])
}
}
}
What i'm trying to do is after the first attempted run of the Job, the following checkbox should be checked with token filled out.
When I have looked for the pipeline syntax, it does not list this as one of the trigger options.
Thanks!
It's authenticationToken in the pipelineJob:
pipelineJob('project-name') {
definition {
...
}
parameters {
...
}
authenticationToken('TOKENHERE')
}
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.jobs.WorkflowJob.authenticationToken

Jenkinsfile: How to parameterise Credential Id as per branch name?

I am using credentials plugin in my Jenkinsfile like below-
stage("stage name"){
steps{
withCredentials([usernamePassword(credentialsId: 'credId', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
sh'''
statement 1
statement 2
'''
}
}
}
As per new requirement, I need to different credentials id as per branch name. That means if branch name is master, I should use credentialsId:'mastercred' and for other branches, I should use credentialsId:'othercred'. The code in "withCredentials" block will be the same for, the only change will be with credentialsId.
I don't want to duplicate code. Is there any way to parameterise this credentialsId?
You can read the branch name variable, and set the a credentialId variable to use on withCredentials would the work. For example:
stage("stage name"){
steps{
if (env.BRANCH_NAME == "master"){
credentialId = "mastercred"
}else
credentialId = "othercred"
}
withCredentials([usernamePassword(credentialsId: "${credentialId}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
sh'''
statement 1
statement 2
'''
}
}
}

How to invoke Jenkins credentials in a jenkins scripted pipeline (not declarative)

i am trying to use jenkins scripted pipeline to invoke config file provider plugin along with fetching credentials from jenkins for the username and password, but the below doesn't seem to work.
node {
def mvnHome
def mvnSettings
stage('Prepare') {
mvnHome = tool 'maven-3.5.4'
}
stage('Checkout') {
checkout scm
}
stage('Deploy'){
def usernameLocal, passwordLocal, usr, psw
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'xyz', passwordVariable: 'PASSWORD', usernameVariable: 'USERNAME']]) {
usernameLocal = env.USERNAME
passwordLocal = env.PASSWORD
}
configFileProvider(
[configFile(fileId: '*********', variable: 'MAVEN_SETTINGS', replaceTokens: true)])
{
usr="${usernameLocal}"
psw="${passwordLocal}"
sh "echo $usr"
sh "'${mvnHome}/bin/mvn' -s $MAVEN_SETTINGS deploy -Dserver.username="${usernameLocal}" -Dserver.password="${passwordLocal}""
}
}
}
where server.username and server.password are defined as properties under settings.xml server section for username and password.
Looks like i found out the issue and its nothing to do with withCredentials used here rather to do with the config file provider plugin. So i am able to print the credentials username correctly but somehow the config file provider is unable to substitute the variable value in the settings.xml.
so i don't get any error anymore, its just that the deployment doesn't go through with 401 unauthorized since the below in my settings.xml never gets the correct values :-
<server>
<id>snapshot</id>
<username>${server.username}</username>
<password>${server.password}</password>
</server>
Could you please advise how to resolve this?
The variables created by withCredentials are Groovy variables not environment variables. Try the following:
stage('Deploy'){
withCredentials([usernamePassword(credentialsId:'xyz', passwordVariable: 'Password', usernameVariable: 'Username')]) {
configFileProvider([configFile(fileId: 'abcde', variable:'MAVEN_SETTINGS')]) {
sh "'${mvnHome}/bin/mvn' -s $MAVEN_SETTINGS deploy -Dserver.username=${Username} -Dserver.password=${Password}"
}
}
}
Ok I figured out the solution, declare the configFileProvider entire section under the block of withCredentials and pass:
-Dserver.username='${usernameLocal}' -Dserver.password='${passwordLocal}'
(Please note single quotes). This way the values also get substituted and are outputted in the logs as masked.

How to mask a password field in Jenkins Pipeline project?

When a password property is defined in a Jenkinsfile:
properties([
parameters([
password(name: 'KEY', description: 'Encryption key')
])
])
Jenkins prompts users to provide its value every time the pipeline is executed:
I want this parameter to be masked so that echo ${KEY} does not print the actual value passed by the user. However, at the moment echoing it prints the provided value verbatim:
properties([
parameters([
password(name: 'KEY', description: 'Encryption key')
])
])
node {
stage('Stage 1') {
# Will print the actual value of the KEY, verbatim
sh "echo ${KEY}"
}
}
Also it seems that the Mask Passwords plugin does not work with Jenkins pipelines, so using that is not an option.
Is there a way to mask these password-typed parameters in the build logs?
You'll want to use the mask passwords plugin. Here's a Jenkinsfile example taken from my shared pipeline library.
properties([
parameters([
password(name: 'KEY', description: 'Encryption key')
])
])
node {
stage('Stage 1') {
// Will print the masked value of the KEY, replaced with ****
wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[var: 'KEY', password: KEY]], varMaskRegexes: []]) {
sh "echo ${KEY}"
}
}
}
Other than existing suggestions on withCredentials, there's not much to add. However, of you're automatically generating your jobs via templates and you're setting a default password, then you might want to make use of hudson.util.Secret to secure your templates.
You can use Jenkins Credentials plugin.With this plugin you can create a credential with an ID for use in your pipeline:
The code will be:
withCredentials([string(credentialsId: 'pass', variable: 'password1')]) {
echo "My password is '${password1}'!"
}
In your user case:
node {
stage('Echo') {
withCredentials([string(credentialsId: 'pass', variable: 'password1')]) {
echo "'${password1}'!"
}
}
}
Note: The password will be masked only in the withCredentials block.

Resources