Kubernetes API创建部署失败

时间:2020-07-24 03:29:36

标签: python kubernetes kubernetes-apiserver

https://github.com/kubernetes-client/python/blob/master/examples/ingress_create.py

上面是我引用的链接

test3.py:

import yaml
from kubernetes import client, config
config.load_kube_config()
txt = ""
with open("/home/xxxxxx/ide-ingress/b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61.yaml", 'r') as f:
    for a in f.readlines():
        txt = txt + a
res = list(yaml.safe_load_all(txt))
deployment_dict = res[3]

def create_deployment(apps_v1_api):
    container = client.V1Container(
        name=deployment_dict.get("metadata").get("name"),
        image=deployment_dict.get("spec").get("template").get("spec").get("containers")[0].get("image"),
        image_pull_policy=deployment_dict.get("spec").get("template").get("spec").get("containers")[0].get(
            "imagePullPolicy"),
        ports=[client.V1ContainerPort(container_port=3000)],
    )
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels=deployment_dict.get("metadata").get("labels")),
        spec=client.V1PodSpec(containers=[container]))
    spec = client.V1DeploymentSpec(
        selector=deployment_dict.get("spec").get("selector").get("matchLabels"),
        replicas=1,
        template=template)
    deployment = client.V1Deployment(
        api_version=deployment_dict.get("apiVersion"),
        kind=deployment_dict.get("kind"),
        metadata=client.V1ObjectMeta(name=deployment_dict.get("metadata").get("name")),
        spec=spec)
    response3 = apps_v1_api.create_namespaced_deployment(
        namespace=deployment_dict.get("metadata").get("namespace"), body=deployment
    )
    print(response3)

print(deployment_dict.get("spec").get("selector").get("matchLabels"))

def main():
    config.load_kube_config()
    apps_v1_api = client.AppsV1Api()

    create_deployment(apps_v1_api)

if __name__ == "__main__":
    main()

然后我得到了错误:

{'app': 'b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61'}

Traceback (most recent call last):
  File "test3.py", line 109, in <module>
    main()
  File "test3.py", line 104, in main
    create_deployment(apps_v1_api)
  File "test3.py", line 93, in create_deployment
    namespace=deployment_dict.get("metadata").get("namespace"), body=deployment
  File "/srv/http/lib/python3.7/site-packages/kubernetes/client/api/apps_v1_api.py", line 290, in create_namespaced_deployment
    (data) = self.create_namespaced_deployment_with_http_info(namespace, body, **kwargs)  # noqa: E501
  File "/srv/http/lib/python3.7/site-packages/kubernetes/client/api/apps_v1_api.py", line 381, in create_namespaced_deployment_with_http_info
    collection_formats=collection_formats)
  File "/srv/http/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 345, in call_api
    _preload_content, _request_timeout)
  File "/srv/http/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 176, in __call_api
    _request_timeout=_request_timeout)
  File "/srv/http/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 388, in request
    body=body)
  File "/srv/http/lib/python3.7/site-packages/kubernetes/client/rest.py", line 278, in POST
    body=body)
  File "/srv/http/lib/python3.7/site-packages/kubernetes/client/rest.py", line 231, in request
    raise ApiException(http_resp=r)
kubernetes.client.rest.ApiException: (422)
Reason: Unprocessable Entity
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Fri, 24 Jul 2020 03:19:51 GMT', 'Content-Length': '692'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Deployment.apps \"b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61\" is invalid: spec.selector: Invalid value: v1.LabelSelector{MatchLabels:map[string]string(nil), MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: empty selector is invalid for deployment","reason":"Invalid","details":{"name":"b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61","group":"apps","kind":"Deployment","causes":[{"reason":"FieldValueInvalid","message":"Invalid value: v1.LabelSelector{MatchLabels:map[string]string(nil), MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: empty selector is invalid for deployment","field":"spec.selector"}]},"code":422}

该错误消息提示我一个空的选择器对于部署无效,但是我打印出的选择器也很有价值。 API中应该有值,但是报告了一个错误,但没有成功,我不知道为什么。

yaml文件:

apiVersion: v1
kind: Namespace
metadata:
  name: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  #name: rewrite
  name: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  namespace: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  annotations:
    #nginx.ingress.kubernetes.io/rewrite-target: /$2
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61.kfquantum.com
    http:
      paths:
      - path: /
        backend:
          serviceName: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
          servicePort: 80
---
apiVersion: v1
kind: Service
metadata:
 name: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
 namespace: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
spec:
 ports:
 - port: 80
   targetPort: 3000
 selector:
   app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  name: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  namespace: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
spec:
  selector:
    matchLabels:
      app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  replicas: 1
  template:
    metadata:
      labels:
        app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
    spec:
      containers:
      - image: theiaide/theia-python
        imagePullPolicy: IfNotPresent
        name: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
        ports:
        - containerPort: 3000
        volumeMounts:
        - mountPath: /home/project
          name: test-volume
        #download private image key dependence private-reg pod
        imagePullSecrets:
        - name: regcred
        # dns 8.8.8.8
        dnsPolicy: "None"
        dnsConfig:
          nameservers:
            - 8.8.8.8
          searches:
            - ns1.svc.cluster-domain.example
            - my.dns.search.suffix
          options:
            - name: ndots
              value: "2"
            - name: edns0
        volumes:
        - name: test-volume
          hostPath:
            path: /home/project/b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61

2 个答案:

答案 0 :(得分:2)

这行seems似乎有问题:

    spec = client.V1DeploymentSpec(
        selector=deployment_dict.get("spec").get("selector").get("matchLabels"),
        replicas=1,
        template=template)

在这种情况下,selector的结尾只是

app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61

因此K8s API认为根本没有选择器,因为它期望使用matchLabels键。

但是我相信你想要这个?:

    matchLabels:
      app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61

所以您可以尝试:

    spec = client.V1DeploymentSpec(
        selector=deployment_dict.get("spec").get("selector"),
        replicas=1,
        template=template)

✌️☮️

答案 1 :(得分:0)

将Yaml修改为:


apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  name: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  namespace: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
spec:
  selector:
    matchLabels:
      app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
  replicas: 1
  template:
    metadata:
      labels:
        app: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
    spec:
      containers:
      - image: theiaide/theia-python
        imagePullPolicy: IfNotPresent
        name: b3a1e295-d77c-41b4-a2e6-5cb75b7b2f61
        ports:
        - containerPort: 3000