How to use jenkins plugin for username with password in dsl?

Viewed 6509

I'm new to jenkins and I'm trying to use the credentials in a dsl using the credentials plugin

template.xml

<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
      <scope>GLOBAL</scope>
      <id>PROD</id>
      <description>prod credentials</description>
      <username>prod</username>
      <password>{{ encrypted_password_prod }}</password
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>

I have defined the credentials in jenkins as username with password . the above encrypted value is saved in ansible.

My question is how should i call them in my dsl

Map credentials = [:]

credentialsBinding {
                    credentials.each { key, value ->
                        string("${key}", "${value}")
                    }


.credentials(["TF_VAR_username": "PROD" ,"TF_VAR_password" : "password_prod"])

Error:

22:11:16 FATAL: Credentials 'PROD' is of type 'Username with password' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected

1 Answers

You can put credentials in Jenkins keystore (Jenkins -> Credentials -> System -> Global credentials -> Add Credentials), and then refer to them in your pipeline using withCredentials block like this:

node {
  withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
    sh '''
      set +x
      curl -u "$USERPASS" https://private.server/ > output
    '''
  }
}

More info here: https://jenkins.io/doc/pipeline/steps/credentials-binding/

Related