python 修改jenkins的配置檔案

苹果芒發表於2024-04-19

python有jenkins獲取配置檔案的api,也有修改配置檔案的api,

下面介紹下 如果修改jenkins job的配置檔案內容:

import re
import time
import jenkins

jenkins_url="http://xxx.com/jenkins"
username="zhangsan"
token="1.......de"

jenkins = jenkins.Jenkins(jenkins_url,username,token)
#新增 舊構建記錄預設配置
daysToKeep = "20"
numToKeep = "10"
str = '<properties>\n' + \
      '<jenkins.model.BuildDiscarderProperty>\n' + \
      '<strategy class="hudson.tasks.LogRotator">\n' + \
      '<daysToKeep>'+daysToKeep+'</daysToKeep>\n' + \
      '<numToKeep>'+numToKeep+'</numToKeep>\n' + \
      '<artifactDaysToKeep>-1</artifactDaysToKeep>\n' + \
      '<artifactNumToKeep>-1</artifactNumToKeep>\n' + \
      '</strategy>\n' + \
      '</jenkins.model.BuildDiscarderProperty>'
# 獲取jenkins中所有job的名字
all_jobs=jenkins.get_jobs()
for job in all_jobs:
    job_name = job["name"]
    job_confogure_data = jenkins.get_job_config(job_name)  # 獲取job congifure info
    if job_confogure_data.find("jenkins.model.BuildDiscarderProperty") == -1:  # 如果這個job沒有勾選 構建舊記錄的配置策略
        job_confogure_data = re.sub("<properties>", str, job_confogure_data, 1)  # 需修改第一個<properties>
    else:
        job_confogure_data = re.sub("<daysToKeep>-?\d+</daysToKeep>", "<daysToKeep>" + daysToKeep + "</daysToKeep>",
                                    job_confogure_data)
        job_confogure_data = re.sub("<numToKeep>-?\d+</numToKeep>", "<numToKeep>" + numToKeep + "</numToKeep>",
                                    job_confogure_data)
        print(job_confogure_data)
    jenkins.reconfig_job(job_name, job_confogure_data)  # 修改job configure資訊
    time.sleep(3)

因為jenkins的特性是:如果構建記錄的儲存幾天 沒有配置,那麼值就是-1,具體可以透過jenkins job的config.xml檢視:

http://xxx.com/jenkins/job/【jobName】/config.xml

 

所以需要用到一些正規表示式:

<daysToKeep>-?\d+</daysToKeep>
解釋:
?:表示?前面的字元可以出現0到1次
-?\d+ :表示可以是負數,也可以為負數
\d+: 這樣 就只能匹配到正數

相關文章