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

背景:jerkins 有100多個job,可是運行機器下線了,須要修改全部job的機器配置,手工一條條修改的話會瘋掉的,因此想到寫一個腳本進行批量修改。java

思路:第一步:獲取Jenkins的全部jobnamedom

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

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

         第四步:將新的修改後的xml文件做爲參數傳給joburl

好了,上代碼:.net

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的配置");
 }
相關文章
相關標籤/搜索