刪除Jenkins JOB後清理workspace

若是Jenkins使用的Master-Slave多節點架構,刪除Jenkins JOB後,相應JOB的slave節點的workspace不會被刪除python

stackoverflow上有相關的問答:http://stackoverflow.com/questions/20532705/deleting-jenkins-jobs-through-gui-does-not-delete-their-workspaces-in-slavesapi

google groups上有相關的討論:https://groups.google.com/forum/#!topic/jenkinsci-users/SiZ3DL-UJ-8架構

因此須要自行處理,因而用腳本實現該功能ui

具體思路是:google

  • 遍歷jenkins節點的workspace,根據路徑解析得到jenkins job name
  • 若是該job不存在(經過python jenkinsapi實現),則刪除相應的workspace 
    • 暫不考慮自定義的workspace
  • 須要在jenkins每一個節點上進行處理(能夠在jenkins上建立job,將job綁定到相應slave上;也能夠在相應slave上直接運行腳本)

相關的Python腳本以下: url

# -*- coding: utf-8 -*-
import os
import shutil
import logging

from jenkinsapi.jenkins import Jenkins

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__file__)


def get_jenkins_instance():
    jenkins_url = "http://jenkins.example.com"
    jenkins_username = "username"
    jenkins_password = "password"
    return Jenkins(jenkins_url, username=jenkins_username, password=jenkins_password)


def clean_workspace():
    jenkins_instance = get_jenkins_instance()

    jenkins_workspace_path = "/opt/JENKINS_HOME/workspace/"

    for dirpath, dirnames, filenames in os.walk(jenkins_workspace_path):
        if dirpath == jenkins_workspace_path:
            for dirname in dirnames:
                jenkins_job_name = dirname
                # 若是job被刪除,則清理相應的workspace
                if not jenkins_instance.has_job(jenkins_job_name):
                    logger.info("removing workspace dir of job:%s" % dirname)
                    shutil.rmtree(os.path.join(dirpath, dirname))


if __name__ == "__main__":
    clean_workspace()
相關文章
相關標籤/搜索