jenkins+python+kubectl实现批量更新k8s镜像

一、jenkins使用官方镜像(官方镜像默认是jenkins用户,权限太低)

  因此通过dockerfile重新改为root启动

  

FROM         jenkins/jenkins:lts
MAINTAINER    dwy

COPY	get-pip.py /tmp/
# if we want to install via apt
USER root
RUN   python /tmp/get-pip.py \
	&& pip install requests

RUN apt-get update && apt-get install -y apt-transport-https \
	&& curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl \
	&&  chmod +x ./kubectl \
	&&  mv ./kubectl /usr/local/bin/kubectl \
	&& mkdir /root/.kube \
    && touch /root/.kube/config \
	&& apt-get install vim -y
	
# drop back to the regular jenkins user - good practice
#USER jenkins

 

二、容器启动后,创建/root/.kube/config文件

     然后在k8s集群里面下载对应kubeconfig.json,将文件内容复制到/root/.kube/config里面

三、jenkins安装python插件

具体代码如下

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 
 5 import requests
 6 import json,sys
 7 from subprocess import Popen,PIPE
 8 
 9 
10 image_tag_list = [
11     ["hlike","nginx","201804h2_0721"],
12     ["hlik","slm",""],
13 ]
14 
15 
55 for n,li in enumerate(image_tag_list,1):
56   print "num %s execute: ******************************************************************" %n
57   namespace = li[0]
58   repository = li[1]
59   tag = li[2] #文件读取出
60   uri="swr-api.cn-north-1.myhuaweicloud.com" #北京swr-api
61   url = "https://%s/v2/manage/namespaces/%s/repos/%s/tags" %(uri,namespace,repository) #根据官方容器镜像仓库api获取对应image:tag
62   res = requests.get(url, headers=headers).json() #这里我没写token,具体仓库,具体自己分析一下api如何获取信息,
63   tag_exist = False
64 
65   if type(res) == dict and res.has_key("errors"):
66     print "log: %s/%s is wrong!!!!!" %(namespace,repository)
67     sys.exit(1)
68   for line in res: #循环返回的结果,得到镜像对应信息
69     if line["Tag"] == tag :#比较返回tag和文件里面的tag是否有相等,若相等,说仓库存在对应镜像
70        tag_exist = True
71        print "%s/%s %s is  exist!!!!!!!!!" % (namespace, repository, tag)
72        updated = line["updated"]
73        path = line["path"]
74        cmd1 = "kubectl set image deployment/%s %s=%s" %(repository,repository,path)
75        print "log: now is setting image,cmd: ",cmd1
76        ret = excute(cmd1)
77        print ret
78   if not tag_exist:
79     print "log: %s/%s %s is not exist" %(namespace,repository,tag)
80     sys.exit(1)

 

posted @ 2018-11-19 14:11  凯文队长  阅读(2143)  评论(0编辑  收藏  举报