21

I need to create a jenkins credential ( https://wiki.jenkins-ci.org/display/JENKINS/Credentials+Plugin ) via a script. How can I do that using either the REST API or the cli ?

Note that I'm able to list the credentials using /credential-store/domain//api/json and /credential-store/domain//credential/8bd82461-e239-4db1-90bc-831ca3412e70/api/json etc.

Loic Dachary
  • 1,034
  • 1
  • 10
  • 24
  • not sure with the possibility of CLI or Rest. But it can be achieved in python or groovy using jenkins api – DevD Apr 14 '15 at 07:46
  • When I create secret with white spaces using the API, get `Caused: javax.servlet.ServletException: Failed to parse JSON:{"": "7", "credentials"...` Any idea? – hpaknia May 02 '19 at 18:42

8 Answers8

37

This issue took me a while to figure, a lot of digging around, so I decided to let the solution here, if someone else needs it.

curl -X POST 'http://user:token@jenkins_server:8080/credentials/store/system/domain/_/createCredentials' \
--data-urlencode 'json={
  "": "0",
  "credentials": {
    "scope": "GLOBAL",
    "id": "identification",
    "username": "manu",
    "password": "bar",
    "description": "linda",
    "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
  }
}'
Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
Fernando
  • 371
  • 3
  • 3
  • 1
    that looks very interesting ! Would you mind sharing the details of the reasoning that lead you to this conclusion ? – Loic Dachary Jun 24 '16 at 12:48
  • 1
    this looks useful..is there something to delete credentials as well? – noob_coder Jul 31 '18 at 06:42
  • 4
    Just addind how the json looks like with secret text, as we quite often use tokens these days: { "": "0", "credentials": { "scope": "GLOBAL", "id": "myid", "secret": "mysecret", "description": "mydescription", "$class": "org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl" } } – csviri Dec 06 '18 at 13:54
  • 4
    What does "":"0" mean? – Mohsen Kamrani Aug 19 '19 at 23:48
  • What should we use for the "id"? – zhangjinzhou Oct 10 '19 at 20:22
  • @csviri I am also looking a way to update the existing secret text using REST API. If I want to update the existing value, how it can be done? have you done that ? – Rmahajan Jul 01 '20 at 10:57
  • @Ros5292 did you try it just posting it again? That should do the job if I remember it correctly. – csviri Jul 02 '20 at 11:38
  • Yes I tried re posting it with updated value but I could see old value and not the updated value. – Rmahajan Jul 02 '20 at 12:25
  • @Ros5292 did you figure out a way to update the existing credential? – Mihado May 30 '22 at 15:54
17

with latest jenkins you need a CRUMB to authenticate for this operation (ref https://stackoverflow.com/a/38314286)

CRUMB=$(curl -s 'http://user:token@jenkins_server:8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')
curl -H $CRUMB -X POST 'http://user:token@jenkins_server:8080/credentials/store/system/domain/_/createCredentials' \
--data-urlencode 'json={
  "": "0",
  "credentials": {
    "scope": "GLOBAL",
    "id": "identification",
    "username": "manu",
    "password": "bar",
    "description": "linda",
    "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
  }
}'

Otherwise you get

<body><h2>HTTP ERROR 403</h2>
<p>Problem accessing /credentials/store/system/domain/_/createCredentials. Reason:
<pre>    No valid crumb was included in the request</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/>
Community
  • 1
  • 1
6

if you need to create credentials but with pem file path you can use this:

prerequisites: ssh-credentials plugin

CRUMB=$(curl -s 'http://{{jenkins_admin_username}}:{{jenkins_admin_password}}@localhost:8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')
curl -H $CRUMB -X POST 'http://{{jenkins_admin_username}}:{{jenkins_admin_password}}@localhost:8080/credentials/store/system/domain/_/createCredentials' \
--data-urlencode 'json={
  "": "0",
  "credentials": {
    "scope": "GLOBAL",
    "id": "'{{ii.ssh_user}}'",
    "username": "'{{ii.ssh_user}}'",
    "password": "",
    "privateKeySource": {
      "stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$FileOnMasterPrivateKeySource",
      "privateKeyFile": "'{{jenkins_home}}/{{ii.key_name}}.pem'",
    },
    "description": "'{{ii.ssh_user}}'",
    "stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"
  }
}'

this command used in ansible but you can replace the {{variables}} with your own variables

if you need to add all the pem file content you need to change the lines to:

....      
"stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource",
      "privateKey": "{{private_key_content}}",
    },
    "description": "{{user}}",
    "stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"
...
dsaydon
  • 4,421
  • 6
  • 48
  • 52
4

Just adding my 2 cents here: if you want to create the credentials for a specific folder, then use the following:

curl -H $CRUMB -X POST 'http://user:token@jenkins_server:8080/job/MY_FOLDER_NAME/credentials/store/folder/domain/_/createCredentials' \
...

So, you need to use /job/My_Folder at the beginning of the query part and replace the /store/system with /store/folder

katrash
  • 1,065
  • 12
  • 13
3

There is no specific API call for this, but you can do it via cli commands to the jenkins jar.

echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("username", "password")' | java -jar jenkins-cli.jar -s http://localhost/ groovy =

For granting them permissions you can create a task in Jenkins which is running every N minutes and executing a groovy script as described here:

https://wiki.jenkins-ci.org/display/JENKINS/Grant+Cancel+Permission+for+user+and+group+that+have+Build+permission

Stan E
  • 3,396
  • 20
  • 31
  • Here is what I get (probably because this is version sensitive ? I'm using jenkins 1.596.1) : `echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("username", "password")' | java -jar ~/jenkins-cli.jar -s http://localhost:11080/ groovy = groovy.lang.MissingMethodException: No signature of method: hudson.security.SecurityRealm$None.createAccount() is applicable for argument types: (java.lang.String, java.lang.String) values: [username, password]` – Loic Dachary Apr 14 '15 at 08:20
  • It looks like this is is for account creation though, not for credentials, right ? – Loic Dachary Apr 14 '15 at 08:26
  • How do you create an admin user with a call like this? – Doug Jul 26 '17 at 03:06
1

I have a groovy script that also sets user permission using Matrix-based security. The script was posted at Creating user in Jenkins via API

Community
  • 1
  • 1
barryku
  • 2,496
  • 25
  • 16
1

Unable to point to ssh keys in ~/.ssh on Jenkins host

Means this no longer works,

"privateKeySource": {
  "stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$FileOnMasterPrivateKeySource",
  "privateKeyFile": "'{{jenkins_home}}/{{ii.key_name}}.pem'",
},
budgester
  • 11
  • 2
1

Here is the official documentation for managing the Jenkins Credentials via REST API

https://github.com/jenkinsci/credentials-plugin/blob/master/docs/user.adoc#creating-a-credentials

Example of adding a deploy-key credential using the username wecoyote and the password secret123 in the testing domain of the /example-folder folder.

$ cat > credential.xml <<EOF
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
  <scope>GLOBAL</scope>
  <id>deploy-key</id>
  <description>Test User</description>
  <usernameSecret>false</usernameSecret>
  <username>wecoyote</username>
  <password>secret123</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
EOF

$ curl -X POST -u <username>:<password_or_token> -H content-type:application/xml -d @credential.xml \
https://jenkins.example.com/job/example-folder/credentials/store/folder/\
domain/testing/createCredentials

The expected responses are:

HTTP/200 Success, the credentials has been created.

HTTP/409 Failure, a credential with that id already exists.

HTTP/50x Could not parse the supplied domain XML body.

Saikat
  • 14,222
  • 20
  • 104
  • 125