2

Does anybody know how to create a new jenkins (2.8) credentials (f.e for a git access) via API or POST request in Jenkins? I have tried to use this code (from another stackoverflow topic), but it does nothing:

import json
import requests

def main():
    data = {
        'credentials': {
            'scope': "GLOBAL",
            'username': "jenkins",
            'privateKeySource': {
                'privateKey': "-----BEGIN RSA PRIVATE KEY-----\nX\n-----END RSA PRIVATE KEY-----",
                'stapler-class': "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource"
            },
            'stapler-class': "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"
        }
    }

    payload = {
        'json': json.dumps(data),
        'Submit': "OK",
    }
    r = requests.post("http://%s:%d/credential-store/domain/_/createCredentials" % (localhost, 8080), data=payload)
    if r.status_code != requests.codes.ok:
        print r.text
CSchulz
  • 10,882
  • 11
  • 60
  • 114
Oleg
  • 41
  • 1
  • 3

3 Answers3

2

I did it this way:

java -jar /tmp/jenkins-cli.jar -s http://localhost:8080/ \
groovy /tmp/credentials.groovy id username password

credentials.groovy

import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.common.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.plugins.credentials.impl.*

domain = Domain.global()
store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()

usernameAndPassword = new UsernamePasswordCredentialsImpl(
  CredentialsScope.GLOBAL,
  args[0],
  "",
  args[1],
  args[2]
)

store.addCredentials(domain, usernameAndPassword)
Oleg
  • 41
  • 1
  • 3
1

I ran into the same issue and after a bit of digging/testing it seems you need to change this

/credential-store/domain/_/createCredentials

to this

/credentials/store/system/domain/_/createCredentials
StephenKing
  • 36,187
  • 11
  • 83
  • 112
0

It's doesn't work: /credential-store/domain/_/api/json

You have to use this url: /credentials/store/system/domain/_/api/json

Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Frank Yen
  • 93
  • 1
  • 1
  • 4