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)

 


免責聲明!

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



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