如何从 Kubernetes 部署中删除标签选择器?

How to remove a label selector from a Kubernetes deployment?

我正在尝试从现有部署的 spec.selector.matchLabels 配置中删除 key/value 对。例如,我试图从 spec.selector.matchLabelsspec.template.metadata.labels 中删除 some.old.label: blah 标签。所以这是我发送给 kubectl apply -f:

的摘录
    spec:
      selector:
        matchLabels:
          app: my-app
      template:
        metadata:
          labels:
            app: my-app

但这给了我以下错误:

selector does not match template labels

我也试过 kubectl replace,这给了我这个错误:

v1.LabelSelector{MatchLabels:map[string]string{“app”: "my-app"}, MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is immutable

一旦我检查了产品中的部署配置,这就有意义了:

metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
       # my config is trying to mutate the matchLabels here:
       {"apiVersion":"apps/v1", ... "selector":{"matchLabels":{"app":"my-app"} ... }
  # etc...
spec:
  selector:
    matchLabels:
      app: my-app
      some.old.label: blah  # how do I remove this label from both the metadata.labels and matchLabels?
  template:
    metadata:
      labels:
        app: my-app
        some.old.label: blah # I want to remove this label

注意 some.old.label: blah key/value 是如何设置在 selector.matchLabelstemplate.metadata.labels 下的。

我是否必须先删除然后重新创建我的部署?或者打电话给 kubectl replace --force?

备注

我在 Kubernetes Deployment docs 中看到了这个部分:

Selector removals removes an existing key from the Deployment selector -- do not require any changes in the Pod template labels. Existing ReplicaSets are not orphaned, and a new ReplicaSet is not created, but note that the removed label still exists in any existing Pods and ReplicaSets.

以及 this PR and this Github issue 谈到了问题背后的原因,但我无法弄清楚 如何 我可以安全地更新我的部署以删除这个选择器。

当错误消息显示“字段是不可变的”时,这意味着它一旦设置就无法更改。您需要使用所需的标签选择器删除并重新创建 Deployment(这也会暂时删除所有匹配的 Pods)。

kubectl delete deployment my-app
kubectl apply -f ./deployment.yaml