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
'''
}
}
}
Related
I have the following step in my pipeline:
node('linux') {
withCredentials(
[
usernamePassword(
credentialsId: 'cred1',
passwordVariable: '1PASSWORD', usernameVariable: '1USER'
),
usernamePassword(
credentialsId: 'cred2',
passwordVariable: '2PASSWORD', usernameVariable: '2USER'
)
]
) {
script {
sh """export SUDO_PASSWORD=\$2PASSWORD
}
}
I'm trying to export the password of the credential used. I do not know ahead of time which credentials would be used (this depends on the machine that's being built on). So above, if cred1 is used I want to run sh """export SUDO_PASSWORD=\$1PASSWORD.
How do I get the password from when it depends on which credential is used?
I am not getting google credentials when i am using the below code.
def GOOGLE_CREDENTIALS = credentials('XYZ Credentials')
[Edited]
Please check this official guide to see if you have defined it correctly.
Also check if you're passing credentials ID, not a description to credentials() method.
If you're using Jenkins pipelines, you also can try Credentials Binding Plugin.
From plugin wiki, a typical example of a username password type credential would look like:
withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
// available as an env variable, but will be masked if you try to print it out any which way
// note: single quotes prevent Groovy interpolation; expansion is by Bourne Shell, which is what you want
sh 'echo $PASSWORD'
// also available as a Groovy variable
echo USERNAME
// or inside double quotes for string interpolation
echo "username is $USERNAME"
}
For scripted pipeline you can use withCredentials() as well (see this):
node {
withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
sh '''
set +x
curl -u "$USERPASS" https://private.server/ > output
'''
}
}
Or you can use withEnv() section:
node {
withEnv(["CREDS=credentials('jenkins-creds')"]) {
stage('Build') {
sh 'printenv'
}
}
}
Here is my working example
node {
stage('Preparing env') {
withCredentials([usernamePassword(credentialsId: 'XYZ Credentials', passwordVariable: 'GOOGLE_CREDENTIALS_PSW', usernameVariable: 'GOOGLE_CREDENTIALS_USR')]) {
// Do something here with your username and password variables
}
}
}
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.
I have the following step in my declarative jenkins pipeline:
I create script which comes from my resources/ folder using libraryResource. This script contains credentials for my autobuild user and for some admintest user.
stage('Build1') {
steps {
node{
def script = libraryResource 'tests/test.sh'
writeFile file: 'script.sh', text: script
sh 'chmod +x script.sh'
withCredentials([usernamePassword(credentialsId: xxx, usernameVariable: 'AUTOBUILD_USER', passwordVariable: 'AUTOBUILD_PASSWD')]){
sh './script.sh "
}
}
}
This works fine. I can use my autobuild user. Now I'm searching for the best way how I can include also the crendentials of my admintest user.
Do I have to 'nest' it with a second withCredentials part or can I add again a usernamePassword 'array'?
Sure, you can use one withCredentials block to assign multiple credentials to different variables.
withCredentials([
usernamePassword(credentialsId: credsId1, usernameVariable: 'USER1', passwordVariable: 'PASS1'),
usernamePassword(credentialsId: credsId2, usernameVariable: 'USER2', passwordVariable: 'PASS2')
]){
//...
}
Also, you can use this with $class
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: 'awsID',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'],
[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'myID',
usernameVariable: 'USR',
passwordVariable: 'PWD']])
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-