如何通过API创建jenkins凭据?

时间:2016-06-06 12:28:09

标签: api jenkins jenkins-api

有人知道如何通过Jenkins中的API或POST请求创建新的jenkins(2.8)凭据(f.e用于git访问)吗?我曾尝试使用此代码(来自另一个stackoverflow主题),但它什么也没做:

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

3 个答案:

答案 0 :(得分:2)

我是这样做的:

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)

答案 1 :(得分:0)

我遇到了同样的问题,经过一些挖掘/测试后,你似乎需要改变这个

/credential-store/domain/_/createCredentials

到这个

/credentials/store/system/domain/_/createCredentials

答案 2 :(得分:0)

它不起作用:Array( [9]=> $2y$10$eP7dUFBqeCZItMg2A8cSFufAi7UC0OfKjzfpkohOAD/lHBsoM6tFu [76]=> $2y$10$DZn/JI0.2HV6DHA9CfEWZ.9MoNNkIKozTURcA5vOTVUE8O8uaBF3. [7]=>$2y$10$gSAtgpFVjhcMk2CAaLOuvOle3dkNqltZOu1I.0NzxOJT/COnu8evq [82]=> $2y$10$B9vG6uBHY004Xn0s2TGkkuRJfuE1wlNqmuQno5ZWqjlwbObMohH5O )

您必须使用此网址:/credential-store/domain/_/api/json