批量修改 Jenkins 任務的技巧
通過指令碼命令列批量修改 Jenkins 任務
最近,筆者所在團隊的 Jenkins 所在的伺服器經常報硬碟空間不足。經查發現很多工沒有設定“丟棄舊的構建”。通知所有的團隊檢查自己的 Jenkins 任務有沒有設定丟棄舊的構建,有些不現實。
一開始想到的是使用Jenkins 的 API 來實現批量修改所有的 Jenkins 任務。筆者對這個解決方案不滿意,經 Google 發現有同學和我遇到了同樣的問題。他使用的更“技巧”的方式:在 Jenkins 指令碼命令列中,通過執行 Groovy 程式碼操作 Jenkins 任務。
總的來說,就兩步:
進入選單:系統管理 --> 指令碼命令列
在輸入框中,貼上如下程式碼:
import jenkins.model.Jenkins import hudson.model.Job import jenkins.model.BuildDiscarderProperty import hudson.tasks.LogRotator // 遍歷所有的任務 Jenkins.instance.allItems(Job).each { job -> if ( job.isBuildable() && job.supportsLogRotator() && job.getProperty(BuildDiscarderProperty) == null) { println " \"${job.fullDisplayName}\" 處理中" job.addProperty(new BuildDiscarderProperty(new LogRotator (2, 10, 2, 10))) println "$job.name 已更新" } } return; /** LogRotator構造引數分別為: daysToKeep:If not -1, history is only kept up to this days. numToKeep: If not -1, only this number of build logs are kept. artifactDaysToKeep: If not -1 nor null, artifacts are only kept up to this days. artifactNumToKeep: If not -1 nor null, only this number of builds have their artifacts kept. **/
指令碼
指令碼命令列介紹
指令碼命令列(Jenkins Script Console),它是 Jenkins 的一個特性,允許你在 Jenkins master 和 Jenkins agent 的執行時環境執行任意的 Groovy 指令碼。這意味著,我們可以在指令碼命令列中做任何的事情,包括關閉 Jenkins,執行作業系統命令 rm -rf /(所以不能使用 root 使用者執行 Jenkins agent)等危險操作。
除了上文中的,使用介面來執行 Groovy 指令碼,還可以通過 Jenkins HTTP API:/script執行。具體操作,請參考 官方文件。
問題:程式碼執行完成後,對任務的修改有沒有被持久化?
當我們程式碼job.addProperty(new BuildDiscarderProperty(new LogRotator (2, 10, 2, 10)))執行後,這個修改到底有沒有持久化到檔案系統中呢(Jenkins 的所有配置預設都持久化在檔案系統中)?我們看下 hudson.model.Job 的原始碼,在addProperty方法背後是有進行持久化的:
public void addProperty(JobProperty<? super JobT> jobProp) throws IOException { ((JobProperty)jobProp).setOwner(this); properties.add(jobProp); save(); }
小結
本文章只介紹了批量修改“丟棄舊的構建”的配置,如果還希望修改其它配置,可以參考 hudson.model.Job 原始碼。
不得不提醒讀者朋友,Jenkins 指令碼命令列是一把雙刃劍,大家操作前,請考慮清楚影響範圍。如果有必要,請提前做好備份。