简体   繁体   English

如何使用 api 更新 jenkins 作业

[英]How can i update a jenkins job using the api

I have to create/update a jenkins job using its api because all of my jobs are using parameters which are also used by other scripts and I am trying to centralize the scripts so when i change it in one place, the change reflects in all.我必须使用 api 创建/更新 jenkins 作业,因为我所有的作业都在使用其他脚本也使用的参数,并且我试图集中脚本,所以当我在一个地方更改它时,更改会全部反映。

currently, if someone changes the script, they they also have to manually edit the parameters of the jenkins job as well.目前,如果有人更改脚本,他们还必须手动编辑 jenkins 作业的参数。

I saw the example of the Remote API for creating jobs and was able to successfully create test jobs but how can i edit an existing job besides deleting it and creating it again(which isnt an option as i have to maintain the build history).我看到了用于创建作业的远程 API 的示例,并且能够成功创建测试作业,但是除了删除它并再次创建它之外,我如何编辑现有作业(这不是一个选项,因为我必须维护构建历史)。

You could use python like this: 你可以像这样使用python:

from jenkinsapi.jenkins import Jenkins
jenkinsSource = 'http://10.52.123.124:8080/'
server = Jenkins(jenkinsSource, username = 'XXXXX', password = 'YYYYY')
myJob=server.get_job("__test")
myConfig=myJob.get_config()
print myConfig
new = myConfig.replace('<string>clean</string>', '<string>string bean</string>')
myJob.update_config(new)

in case anyone else is also looking for the same answer, 如果其他人也在寻找相同的答案,

It appears the solution is far easier, all you have to do is update the config.xml and post the updated config.xml back to jenkins and your job will be updated. 看起来解决方案要容易得多,您只需更新config.xml并将更新后的config.xml发布回jenkins,您的工作就会更新。

You can also POST an updated config.xml to the URL which can fetch config.xml , to programmatically update the configuration of a job. 您还可以将更新的config.xml发布到可以获取config.xml的URL,以便以编程方式更新作业的配置。

The fetch url pattern: $JENKINS_SERVER/job/$JOB_NAME/config.xml 获取url模式: $JENKINS_SERVER/job/$JOB_NAME/config.xml

detailed doc pattern: $JENKINS_SERVER/job/$JOB_NAME/api 详细的doc模式: $JENKINS_SERVER/job/$JOB_NAME/api

example: https://ci.jenkins-ci.org/job/infra_atlassian-base/api/ 示例: https//ci.jenkins-ci.org/job/infra_atlassian-base/api/

http://asheepapart.blogspot.ca/2014/03/use-jenkins-rest-api-to-update-job.html http://asheepapart.blogspot.ca/2014/03/use-jenkins-rest-api-to-update-job.html

That little bit of scripting looks to be what you are looking for. 这一点脚本看起来就像你在寻找什么。 Uses the REST API to get and set the config with some regex S&R in the middle. 使用REST API来获取和设置配置,中间使用一些正则表达式S&R。

Edit: Code below based on comment. 编辑:以下代码基于评论。 It is copied directly from the blog so I take no credit for it. 它直接从博客中复制,所以我不相信它。

# First, get the http://jenkins.example.com/job/folder-name/job/sample-job--template/configure looking like you want

read -s token
# type token from http://jenkins.example.com/user/$userName/configure

# Download the configuration XML for the template job (which will be our model template)
curl -v -u "bvanevery:$token" http://jenkins.example.com/job/folder-name/job/sample-job--template/config.xml > generic-config.xml

# My modules
declare modules=('module1' 'module2' 'module3')

# POST the updated configuration XML to Jenkins
for m in ${modules[@]}; do
   echo "module $m";
   sed "s/MODULE/$m/g" generic-config.xml > $m-config.xml; 
   curl -v -X POST --data-binary @$m-config.xml -u "bvanevery:$token" \
        -H 'Content-Type: application/xml' \
        "http://jenkins.example.com/job/folder-name/job/$m/config.xml" ;
done

For those using RestSharp, I found that I needed to make sure that: 对于那些使用RestSharp的人,我发现我需要确保:

  1. The user ID performing the update had permission to do so under Manage > Global Security > Authorization Matrix 执行更新的用户标识具有在“管理”>“全局安全性”>“授权矩阵”下执行此操作的权限
  2. I had a current Jenkins Crumb token, required once CSRF (also under Manage > Security) is enabled. 我有一个当前的Jenkins Crumb令牌,一旦启用了CSRF(也在Manage> Security下),就需要这个令牌。
  3. Send the updated XML using a parameter of the Request object with the value of [ParameterType.RequestBody] (link) 1 for the type argument. 使用Request对象的参数发送更新的XML,类型参数的值为[ParameterType.RequestBody] (link) 1

     private XmlDocument JobConfigGet() { Uri JobConfigURI = GetJenkinsURI("job/" + _args.JobName + "/config.xml", null); RestClient restClient = new RestClient(JobConfigURI); RestRequest restRequest = new RestRequest(Method.GET); byte[] ua = Encoding.ASCII.GetBytes(Properties.Settings.Default.UserID + ":" + Properties.Settings.Default.UserPassword); restRequest.AddHeader("authorization", "Basic " + Convert.ToBase64String(ua)); IRestResponse restResponse = restClient.Execute(restRequest); if (restResponse.ResponseStatus != ResponseStatus.Completed || restResponse.StatusCode != HttpStatusCode.OK) throw new Exception(string.Format("Unable to retrieve job config: {0}. Wrong ResponseStatus ({1}) or StatusCode ({2}) returned.\\nURL: {3}", _args.JobName, restResponse.ResponseStatus.ToString(), restResponse.StatusCode.ToString(), restClient.BaseUrl.AbsoluteUri)); if (restResponse.ContentType != "application/xml") throw new Exception("Unexpected data type returned for job config: " + _args.JobName + ". Expected 'application/xml'. Got: " + restResponse.ContentType + ".\\nURL: " + restClient.BaseUrl.AbsoluteUri); XmlDocument jobConfig = new XmlDocument(); jobConfig.LoadXml(restResponse.Content); return jobConfig; } private void JobConfigUpdate(XmlDocument JobConfig, string JenkinCrumb) { // Update JobConfig XML as needed here. Uri JobConfigURI = GetJenkinsURI("job/" + _args.JobName + "/config.xml", null); RestClient restClient = new RestClient(JobConfigURI); RestRequest restRequest = new RestRequest(Method.POST); byte[] ua = Encoding.ASCII.GetBytes(Properties.Settings.Default.UserID + ":" + Properties.Settings.Default.UserPassword); restRequest.AddHeader("authorization", "Basic " + Convert.ToBase64String(ua)); string[] crumbSplit = JenkinCrumb.Split(':'); restRequest.AddHeader(crumbSplit[0], crumbSplit[1]); restRequest.AddParameter("text/xml", JobConfig.InnerXml, ParameterType.RequestBody); IRestResponse restResponse = restClient.Execute(restRequest); string resp = restResponse.Content; } 
curl -v -X POST https://jenkinsurl.fr:8443/job/jobname/config.xml  --data-binary "@config.xml" -u "jenkinsusername:yourjenkinstoken" -H "Content-Type: application/xml"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM