删除Jenkins JOB后清理workspace

原创
2016/05/19 13:40
阅读数 1.3W

如果Jenkins使用的Master-Slave多节点架构,删除Jenkins JOB后,相应JOB的slave节点的workspace不会被删除

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

google groups上有相关的讨论:https://groups.google.com/forum/#!topic/jenkinsci-users/SiZ3DL-UJ-8

所以需要自行处理,于是用脚本实现该功能

具体思路是:

  • 遍历jenkins节点的workspace,根据路径解析获得jenkins job name
  • 如果该job不存在(通过python jenkinsapi实现),则删除相应的workspace 
    • 暂不考虑自定义的workspace
  • 需要在jenkins每个节点上进行处理(可以在jenkins上创建job,将job绑定到相应slave上;也可以在相应slave上直接运行脚本)

相关的Python脚本如下: 

# -*- 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()

 

展开阅读全文
打赏
2
4 收藏
分享
加载中
更多评论
打赏
0 评论
4 收藏
2
分享
返回顶部
顶部