pykube for k8s

A python client library for kubenetes

install pykube

1
pip install pykube

Usage

Query for all pods in a custom namespaces

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

import pykube

api = pykube.HTTPClient(pykube.KubeConfig.from_file("/Users/shuke/.kube/config"))
pods = pykube.Pod.objects(api).filter(namespace="kube-system")
ready_pods = filter(operator.attrgetter("ready"), pods)

for item in pods:
print(item)

# output:
coredns-66bff467f8-82256
coredns-66bff467f8-b49t6
etcd-minikube
kube-apiserver-minikube
kube-controller-manager-minikube
kube-proxy-j2pdv
kube-scheduler-minikube
my-rc-6978k
my-rc-kvhhg
my-rc-qn2zv
my-rc01-5lwlr
my-rc01-9hfvs
my-rc01-w5qhb
vault-0
vault-agent-injector-5487bc5b57-m44l5

Create a ReplicationController:

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
34
35
36
37
38
39
40
41
42
43
44
import operator
import pykube

api = pykube.HTTPClient(pykube.KubeConfig.from_file("/Users/shuke/.kube/config"))

obj = {
"apiVersion": "v1",
"kind": "ReplicationController",
"metadata": {
"name": "my-rc",
"namespace": "kube-system"
},
"spec": {
"replicas": 3,
"selector": {
"app": "nginx"
},
"template": {
"metadata": {
"labels": {
"app": "nginx"
}
},
"spec": {
"containers": [
{
"name": "nginx",
"image": "nginx",
"ports": [
{"containerPort": 80}
]
}
]
}
}
}
}
ret = pykube.ReplicationController(api, obj).create()
print(ret)

# output:
(base) ➜ k get rc
NAME DESIRED CURRENT READY AGE
my-rc 3 3 0 16m

Delete ReplicationController:

1
2
3
4
5
6
7
8
9
obj = {
"apiVersion": "v1",
"kind": "ReplicationController",
"metadata": {
"name": "my-rc",
"namespace": "kube-system"
}
}
pykube.ReplicationController(api, obj).delete()

Check server version:

1
2
3
4
5
6
7
8
9
10
import operator
import pykube

api = pykube.HTTPClient(pykube.KubeConfig.from_file("/Users/shuke/.kube/config"))

print(api.version)

# output:
(base) ➜ python version.py
('1', '18')

本文标题:pykube for k8s

文章作者:shuke

发布时间:2021年02月27日 - 18:02

最后更新:2021年02月27日 - 18:02

原始链接:https://shuke163.github.io/2021/02/27/pykube-for-k8s/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------本文结束感谢您的阅读-------------

本文标题:pykube for k8s

文章作者:shuke

发布时间:2021年02月27日 - 18:02

最后更新:2021年02月27日 - 18:02

原始链接:https://shuke163.github.io/2021/02/27/pykube-for-k8s/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%