如何批量修改Jenkins job的配置?


背景:jerkins 有100多個job,但是運行機器下線了,需要修改所有job的機器配置,手工一條條修改的話會瘋掉的,所以想到寫一個腳本進行批量修改。

思路:第一步:獲取Jenkins的所有jobname

         第二步:  遍歷jobname,獲取每個job的配置文件config.xml

         第三步:將獲取到的xml類型字符串轉化為document對象,然后修改機器節點的值,然后將修改的document對象寫入一個新的xml文件

         第四步:將新的修改后的xml文件作為參數傳給job

好了,上代碼:

import org.xml.sax.InputSource;
import com.offbytwo.jenkins.JenkinsServer;
import java.net.URI;

import org.jdom2.input.SAXBuilder;
import org.jdom2.Document;
import org.jdom2.Element;


public void modifyJenkinsTest(){
        String username=*******;
        String password=*******;
        String url = *******;
        String filename="tempConfig.xml";
        //count 用於統計成功修改多少個job的配置
        int count=0;
        try {
            JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
            Map<String, Job> jobs = jenkins.getJobs();
            //遍歷獲取到所有的jobname
            for (String jobname:jobs.keySet()) {                 
                String configUrl = url+"job/" + jobname + "/config.xml"; 
                //在這里需要單獨寫一個httpRequest類,里面寫一個靜態函數sendGet,需要攜帶Authorization參數,因為訪問Jenkins需要認證信息,(通過用戶名和密碼生成)
                String response = httpRequest.sendGet(configUrl, "");  
                # 將字符串xml轉化為document對象
                StringReader read = new StringReader(response); 
                InputSource source = new InputSource(read);      
                SAXBuilder sb = new SAXBuilder();
                Document document; 
                document = sb.build(source); 
                Element root = document.getRootElement(); 
                //配置文件沒有assignedNode節點或者這個節點的值已經修改過了就跳過這條job 

                if(root.getChild("assignedNode")==null||root.getChild("assignedNode").getText().equals("********")){ 
                    continue; 
                } 
                //修改document對象中名字為assignedNode的節點的值為*******
                root.getChild("assignedNode").setText("********"); 
                //將修改之后的xml對象寫入一個臨時的xml文件
                File file = new File(filename); 
                XMLOutputter outputter = new XMLOutputter(format); 
                outputter.output(document, new FileOutputStream(file)); 
                //將修改之后xml文件傳給job,進行修改
                //在這里需要單獨寫一個httpRequest類,里面寫一個靜態函數requestPost,需要攜帶Authorization參數,因為訪問Jenkins需要認證信息,(通過用戶名和密碼生成)
                httpRequest.requestPost(configUrl, filename); 
                //修改成功一個,count加1
                count++; 
            } 
        }catch (Exception e){ 
            e.printStackTrace();
        } 
        System.out.println("成功修改了"+count+"條job的配置");
 }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM