发布时间:2020-08-11 13:48:00编辑:admin阅读(2634)
Rancher提供了api给我们调用,从而实现不用通过访问Rancher UI 或使用 Rancher CLI 来对应用服务进行例如启动,停止,创建,升级等一系列的操作;
在访问控制(Access Control)生效时,进行API 请求需要包含认证信息,在Rancher UI 创建使用 API Keys的步骤如下:
密钥由Environment拥有,并具有管理该环境的完全访问权限,但不能访问任何其他环境。这些密钥不适用于用户身份
账号API Keys与你的用户账号绑定, (admin) 能够创建、删除及管理您有权限访问的所有环境。
点击用户右上角-->API & Keys
添加key
输入描述,选择永不过期,这里不指定作用范围。
请根据实际情况来原则
创建成功后,一定要保存。它只会显示一次
我只需要用到2个:
Access Key(用户名): token-v82g7 Secret Key(密码): zzph8mnrv7r2q5qqt9kds85xvjcwzpg5btkttpvj72nmfll8jmxn67
先找到我需要发布的应用admin-master-->api查看
跳转的url为:
https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/statefulset:default:admin-master
点击右侧的编辑按钮
进入编辑页面,这里面有很多参数
什么都不要改,直接拖到最下面,点击Show Request
它显示了2段信息:
第一段是curl的请求命令,注意:它不是完整的命令。
第二段是请求数据,它是一段json内容。由于参数比较多,图片展示不全。
前方高能预警,上面给出的curl命令,是绝对不能用的。
显示的请求数据,也不是标准的json,是错误的json。
如果你用的老版本Rancher 2.3.x,显示的curl命令,是正确的。其中包括-d参数,也就是标准的json数据。这里面就包括了镜像地址,映射端口,映射目录等等配置信息。
那么问题来了,怎么操作才是正确的姿势呢?
经过我不断的努力尝试,终于测试出来了!!!
还是回到上面的编译页面,之前我已经点击了Show Requests。
先按F12,打开浏览器调试工具。点击网络,清空里面的连接。
再下面,点击Send Request。
此时会出现一个PUT请求
找到Request Payload,这里就是发送的请求数据。
点击view source,显示源格式
这里,就是发送的数据,把它给复制出来。后面会用到!
将压缩后的数据复制一下,那么完整的curl命令为:
export RANCHER_ACCESS_KEY="token-v82g7" export RANCHER_SECRET_KEY="zzph8mnrv7r2q5qqt9kds85xvjcwzpg5btkttpvj72nmfll8jmxn67" curl -u "${RANCHER_ACCESS_KEY}:${RANCHER_SECRET_KEY}" \ -X PUT \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ -d '{"annotations":{"cattle.io/timestamp":"2020-06-22T10:42:46Z"},"containers":[{"allowPrivilegeEscalation":false,"image":"10.212.82.86:1180/java/admin-master:32","imagePullPolicy":"Always","initContainer":false,"name":"admin-master","ports":[{"containerPort":8088,"dnsName":"admin-master-nodeport","hostPort":0,"kind":"NodePort","name":"tcp-8088","protocol":"TCP","sourcePort":0,"type":"/v3/project/schemas/containerPort"}],"privileged":false,"readOnly":false,"resources":{"type":"/v3/project/schemas/resourceRequirements"},"restartCount":0,"runAsNonRoot":false,"stdin":true,"stdinOnce":false,"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","tty":true,"type":"/v3/project/schemas/container"}],"created":"2020-06-22T10:42:46Z","creatorId":null,"deploymentConfig":{"maxSurge":1,"maxUnavailable":0,"minReadySeconds":0,"progressDeadlineSeconds":600,"revisionHistoryLimit":10,"strategy":"RollingUpdate"},"deploymentStatus":{"availableReplicas":1,"conditions":[{"lastTransitionTime":"2020-06-22T10:42:48Z","lastTransitionTimeTS":1592822568000,"lastUpdateTime":"2020-06-22T10:42:48Z","lastUpdateTimeTS":1592822568000,"message":"Deployment has minimum availability.","reason":"MinimumReplicasAvailable","status":"True","type":"Available"},{"lastTransitionTime":"2020-06-22T10:42:46Z","lastTransitionTimeTS":1592822566000,"lastUpdateTime":"2020-06-22T10:54:54Z","lastUpdateTimeTS":1592823294000,"message":"ReplicaSet \"admin-master-6c49c7c4b\" has successfully progressed.","reason":"NewReplicaSetAvailable","status":"True","type":"Progressing"}],"observedGeneration":7,"readyReplicas":1,"replicas":1,"type":"/v3/project/schemas/deploymentStatus","unavailableReplicas":0,"updatedReplicas":1},"dnsConfig":null,"dnsPolicy":"ClusterFirst","ephemeralContainers":[],"gids":[],"hostAliases":[],"hostIPC":false,"hostNetwork":false,"hostPID":false,"imagePullSecrets":[],"labels":{"workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"name":"admin-master","namespaceId":"default","nodeId":"","ownerReferences":[],"paused":false,"projectId":"c-l5nxb:p-dghs7","publicEndpoints":[],"readinessGates":[],"restartPolicy":"Always","scale":1,"scheduling":{"scheduler":"default-scheduler"},"selector":{"matchLabels":{"workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"type":"/v3/project/schemas/labelSelector"},"state":"active","sysctls":[],"terminationGracePeriodSeconds":30,"topologySpreadConstraints":[],"transitioning":"no","transitioningMessage":"","uuid":"96952959-73f4-48eb-9c8a-0476689c85f0","volumes":[],"windowsOptions":null,"workloadAnnotations":{"deployment.kubernetes.io/revision":"2","field.cattle.io/creatorId":"user-kmvzg"},"workloadLabels":{"cattle.io/creator":"norman","workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"workloadMetrics":[]}' \ 'https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master' --insecure
参数解释:
export 用了定义全局变量。RANCHER_ACCESS_KEY和RANCHER_SECRET_KEY分别对应Access Key(用户名)和Secret Key(密码)
-u 设置服务器的用户和密码
-X 指定什么访问类型。curl默认的HTTP动词是GET,使用-X参数可以支持其他动词。
-H 指定请求头参数
-d HTTP POST方式传送数据,也适用于其他方式。比如:PUT
--insecure 允许不使用证书到SSL站点。注意:由于我这里是ip访问,所以提示不安全。如果是通过域名访问,并且是安全的,不需要此参数。
执行之后,会返回一段json,比如:
{"actions":{"pause":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master?action=pause","redeploy":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master?action=redeploy","resume":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master?action=resume","rollback":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master?action=rollback"},"annotations":{"cattle.io/timestamp":"2020-06-22T10:42:46Z"},"baseType":"workload","containers":[{"allowPrivilegeEscalation":false,"image":"10.212.82.86:1180/java/admin-master:32","imagePullPolicy":"Always","initContainer":false,"name":"admin-master","ports":[{"containerPort":8088,"dnsName":"admin-master-nodeport","hostPort":0,"kind":"NodePort","name":"tcp-8088","protocol":"TCP","sourcePort":0,"type":"/v3/project/schemas/containerPort"}],"privileged":false,"readOnly":false,"resources":{"type":"/v3/project/schemas/resourceRequirements"},"restartCount":0,"runAsNonRoot":false,"stdin":true,"stdinOnce":false,"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","tty":true,"type":"/v3/project/schemas/container"}],"created":"2020-06-22T10:42:46Z","createdTS":1592822566000,"creatorId":null,"deploymentConfig":{"maxSurge":1,"maxUnavailable":0,"minReadySeconds":0,"progressDeadlineSeconds":600,"revisionHistoryLimit":10,"strategy":"RollingUpdate"},"deploymentStatus":{"availableReplicas":1,"conditions":[{"lastTransitionTime":"2020-06-22T10:42:48Z","lastTransitionTimeTS":1592822568000,"lastUpdateTime":"2020-06-22T10:42:48Z","lastUpdateTimeTS":1592822568000,"message":"Deployment has minimum availability.","reason":"MinimumReplicasAvailable","status":"True","type":"Available"},{"lastTransitionTime":"2020-06-22T10:42:46Z","lastTransitionTimeTS":1592822566000,"lastUpdateTime":"2020-06-22T10:54:54Z","lastUpdateTimeTS":1592823294000,"message":"ReplicaSet \"admin-master-6c49c7c4b\" has successfully progressed.","reason":"NewReplicaSetAvailable","status":"True","type":"Progressing"}],"observedGeneration":7,"readyReplicas":1,"replicas":1,"type":"/v3/project/schemas/deploymentStatus","unavailableReplicas":0,"updatedReplicas":1},"dnsPolicy":"ClusterFirst","hostIPC":false,"hostNetwork":false,"hostPID":false,"id":"deployment:default:admin-master","labels":{"workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"links":{"remove":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master","revisions":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master/revisions","self":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master","update":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master","yaml":"https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master/yaml"},"name":"admin-master","namespaceId":"default","paused":false,"projectId":"c-l5nxb:p-dghs7","publicEndpoints":[{"addresses":["10.212.21.159"],"allNodes":true,"ingressId":null,"nodeId":null,"podId":null,"port":32572,"protocol":"TCP","serviceId":"default:admin-master-nodeport"}],"restartPolicy":"Always","scale":1,"scheduling":{"scheduler":"default-scheduler"},"selector":{"matchLabels":{"workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"type":"/v3/project/schemas/labelSelector"},"state":"active","terminationGracePeriodSeconds":30,"transitioning":"no","transitioningMessage":"","type":"deployment","uuid":"96952959-73f4-48eb-9c8a-0476689c85f0","workloadAnnotations":{"deployment.kubernetes.io/revision":"2","field.cattle.io/creatorId":"user-kmvzg"},"workloadLabels":{"cattle.io/creator":"norman","workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"workloadMetrics":null}注意:返回上面的json格式,才是正确的。
此时,rancher中的镜像地址并没有更改。因为我的-d里面的json数据中,
"image": "10.212.82.86:1180/java/admin-master:32"
镜像地址还是原来的,如果需要更改。只需要更改这个值,再次发送PUT请求,就可以了。
那么我来测试一下,更改为:
"image": "10.212.82.86:1180/java/admin-master:33"
再次发送PUT请求,完整命令我就不贴了。更改image的值即可。
查看pod详情,发现已经更改过来了。
点击扳手按钮
点击settings,关闭ssl验证。
如果不这么做,会提示:Error: unable to verify the first certificate
选择PUT请求,url地址为:https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master
增加Headers参数
Accept=application/json Content-Type=application/json Authorization=Bearer token-v82g7:zzph8mnrv7r2q5qqt9kds85xvjcwzpg5btkttpvj72nmfll8jmxn67
其中Authorization参数的格式为:
Bearer Access Key(用户名):Secret Key(密码)
注意:Bearer后面接空格,Access Key和Secret Key中间用冒号间隔。
效果如下:
点击body-->raw-->json,粘贴上面的json数据
点击send按钮,发送请求。
可以看到返回HTTP 200,响应数据为一段json数据。
如果要更改镜像地址,只需要修改json数据中的image地址即可。
下面使用python 3.x的request模块,发送PUT请求。
rancher_deploy.py
#!usr/bin/python # -*- coding: utf-8 -*- import requests # 去除requests警告信息 from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) CATTLE_ACCESS_KEY = 'token-v82g7' RANCHER_SECRET_KEY = 'zzph8mnrv7r2q5qqt9kds85xvjcwzpg5btkttpvj72nmfll8jmxn67' # 请求头 header = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer {}:{}'.format(CATTLE_ACCESS_KEY, RANCHER_SECRET_KEY)} # 请求数据,r表示保留数据源格式。格式为:r"""json数据""" content = r"""{"annotations":{"cattle.io/timestamp":"2020-06-22T10:42:46Z"},"containers":[{"allowPrivilegeEscalation":false,"image":"10.212.82.86:1180/java/admin-master:33","imagePullPolicy":"Always","initContainer":false,"name":"admin-master","ports":[{"containerPort":8088,"dnsName":"admin-master-nodeport","hostPort":0,"kind":"NodePort","name":"tcp-8088","protocol":"TCP","sourcePort":0,"type":"/v3/project/schemas/containerPort"}],"privileged":false,"readOnly":false,"resources":{"type":"/v3/project/schemas/resourceRequirements"},"restartCount":0,"runAsNonRoot":false,"stdin":true,"stdinOnce":false,"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","tty":true,"type":"/v3/project/schemas/container"}],"created":"2020-06-22T10:42:46Z","creatorId":null,"deploymentConfig":{"maxSurge":1,"maxUnavailable":0,"minReadySeconds":0,"progressDeadlineSeconds":600,"revisionHistoryLimit":10,"strategy":"RollingUpdate"},"deploymentStatus":{"availableReplicas":1,"conditions":[{"lastTransitionTime":"2020-06-22T10:42:48Z","lastTransitionTimeTS":1592822568000,"lastUpdateTime":"2020-06-22T10:42:48Z","lastUpdateTimeTS":1592822568000,"message":"Deployment has minimum availability.","reason":"MinimumReplicasAvailable","status":"True","type":"Available"},{"lastTransitionTime":"2020-06-22T10:42:46Z","lastTransitionTimeTS":1592822566000,"lastUpdateTime":"2020-06-22T10:54:54Z","lastUpdateTimeTS":1592823294000,"message":"ReplicaSet \"admin-master-6c49c7c4b\" has successfully progressed.","reason":"NewReplicaSetAvailable","status":"True","type":"Progressing"}],"observedGeneration":7,"readyReplicas":1,"replicas":1,"type":"/v3/project/schemas/deploymentStatus","unavailableReplicas":0,"updatedReplicas":1},"dnsConfig":null,"dnsPolicy":"ClusterFirst","ephemeralContainers":[],"gids":[],"hostAliases":[],"hostIPC":false,"hostNetwork":false,"hostPID":false,"imagePullSecrets":[],"labels":{"workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"name":"admin-master","namespaceId":"default","nodeId":"","ownerReferences":[],"paused":false,"projectId":"c-l5nxb:p-dghs7","publicEndpoints":[],"readinessGates":[],"restartPolicy":"Always","scale":1,"scheduling":{"scheduler":"default-scheduler"},"selector":{"matchLabels":{"workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"type":"/v3/project/schemas/labelSelector"},"state":"active","sysctls":[],"terminationGracePeriodSeconds":30,"topologySpreadConstraints":[],"transitioning":"no","transitioningMessage":"","uuid":"96952959-73f4-48eb-9c8a-0476689c85f0","volumes":[],"windowsOptions":null,"workloadAnnotations":{"deployment.kubernetes.io/revision":"2","field.cattle.io/creatorId":"user-kmvzg"},"workloadLabels":{"cattle.io/creator":"norman","workload.user.cattle.io/workloadselector":"deployment-default-admin-master"},"workloadMetrics":[]}""" # 应用服务api地址 api_url = 'https://10.212.82.86/v3/project/c-l5nxb:p-dghs7/workloads/deployment:default:admin-master' # 发送put请求,verify=False表示关闭验证证书 r = requests.put(api_url, data=content, headers=header, verify=False) # print(r.text) # print(r.status_code) # 判断返回状态码 if (r.status_code == 200): print('ok') else: print('error')
执行脚本,输出:
ok
说明:虽然关闭了ssl证书验证,但是还是会弹出警告信息。因此我在上面,专门屏蔽了警告信息。参考链接:
https://blog.csdn.net/mike_Cui_LS/article/details/84249315
注意:代码中的json数据,是当前的服务状态设置而来的。如果后续服务有更新,比如增加环境,挂载目录之类的。还得重新获取json数据,并更新python代码才行。
本文参考链接:
https://rancher.com/docs/rancher/v1.1/en/api/v1/api-resources/apiKey/
http://www.dockerinfo.net/3723.html
https://www.jianshu.com/p/2821da562ecd
上一篇: 安装KubeSphere
47303
45507
36587
34101
28810
25424
24274
19469
18914
17483
5304°
5904°
5403°
5488°
6376°
5220°
5219°
5731°
5687°
6996°