实现rancher2.1的jenkins自动部署功能,并且保证环境变量等其他配置不丢失。思路是,通过rancher api获取当前workload的信息,然后替换container的镜像名称,最后调用更新workload的rancher api即可。

要注意的是,需要提前在rancher获取app_key和app_secret。请保存申请的信息,这些信息仅显示一次。如果忘记了,需要重新创建新的key。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sys
import requests
from requests.auth import HTTPBasicAuth

image_name = sys.argv[1]
project_name = sys.argv[2] # eg: c-7cb96:p-z827j
deployment_name = sys.argv[3]
service_name = sys.argv[4]

app_key = 'app_key'
app_secret = 'app_secret'

# 获取服务信息
current_settings_requests = requests.get(
'https://xxx-rancher-domain/v3/project/{}/workloads/deployment:{}:{}'.format(project_name,deployment_name,service_name),
verify=False,
auth=HTTPBasicAuth(app_key, app_secret))
# 调用不成功脚本异常退出
if current_settings_requests.status_code != 200:
sys.exit(10)
payloads = current_settings_requests.json()
for i in payloads['containers']:
i['image'] = image_name
# 更新服务
update_settings_requests = requests.put(
'https://xxx-rancher-domain/v3/project/{}/workloads/deployment:{}:{}'.format(
project_name, deployment_name, service_name),
verify=False,
auth=HTTPBasicAuth(app_key, app_secret),
json=payloads)
# 调用不成功脚本异常退出
if update_settings_requests.status_code != 200:
sys.exit(10)