如何仅通过“ kubectl apply -f file.yaml”从kubernetes对象中删除标签?

问题描述 投票:0回答:3

我正在Redhat Openshift中玩GitOps和ArgoCD。我的目标是将工作节点切换到基础节点。

我想使用描述性的YAML文件来做到这一点,而不是通过使用命令行手动进行操作(使用kubectl标签节点很容易...)

为了使该节点成为基础节点,我想添加一个标签“基础”并从中获取标签“ worker”。之前,对象看起来像这样(省略了不相关的标签):

apiVersion: v1
kind: Node
metadata:
  labels:
    node-role.kubernetes.io/infra: ""
  name: node6.example.com
spec: {}

应用YAML文件后,应该看起来像这样:

apiVersion: v1
kind: Node
metadata:
  labels:
    node-role.kubernetes.io/worker: ""
  name: node6.example.com
spec: {}

如果将后一个配置放在文件中,然后执行“ kubectl apply -f”,则该节点同时具有基础标签和辅助标签。因此添加标签或更改标签的值很容易,但是有没有一种方法可以通过应用YAML文件来删除对象元数据中的标签?

kubernetes yaml label openshift argocd
3个回答
0
投票

您可以使用以下方法删除标签

kubectl label node node6.example.com node-role.kubernetes.io/infra-

然后您可以使用新标签再次运行kubectl apply。您将启动并运行。


0
投票

[我会说这与kubectl apply无关,至少我尝试过并且找不到有关此的任何信息。

正如@Petr Kotas提到的,您可以随时使用

kubectl label node node6.example.com node-role.kubernetes.io/infra-

但是我看到你在寻找其他东西

我想使用描述性的YAML文件来做到这一点,而不是通过使用命令行手动进行操作(使用kubectl标签节点很容易...)


所以答案可能是使用API​​客户端,例如python?我已经找到了@Prafull Ladha制作的示例here

如前所述,纠正kubectl示例以删除标签,但是没有提到使用API​​客户端删除标签。如果要使用API​​删除标签,则需要为新主体提供labelname: None,然后将该主体修补到节点或吊舱。我出于示例目的使用kubernetes python客户端API

from pprint import pprint
from kubernetes import client, config

config.load_kube_config()
client.configuration.debug = True

api_instance = client.CoreV1Api()

body = {
    "metadata": {
        "labels": {
            "label-name": None}
        }
}

api_response = api_instance.patch_node("minikube", body)

print(api_response)

0
投票

我已经使用以下命令成功更改了Kubernetes集群(使用kubeadm创建)中的节点标签:

# Check the original label ( last filter removes previous config annotation line)
$ kubectl get node node2 -o yaml | grep node-role | grep -v apiVersion
    node-role.kubernetes.io/infra: ""

# Replace the label using kubectl replace syntax
$ kubectl get node node2 -o yaml | sed '[email protected]/infra: ""@node-role.kubernetes.io/worker: ""@' | kubectl replace -f -
node/kube-node2-2 replaced

# check the new state of the label
$ kubectl get node node2 -o yaml | grep node-role | grep -v apiVersion
    node-role.kubernetes.io/worker: ""

# Replace the label using kubectl apply syntax
$ kubectl get node node2 -o yaml | sed '[email protected]/worker: ""@node-role.kubernetes.io/infra: ""@' | kubectl apply -f -
node/kube-node2-2 configured

# check the new state of the label
$ kubectl get node node2 -o yaml | grep node-role | grep -v apiVersion
    node-role.kubernetes.io/infra: ""

# Remove the label from the node ( for demonstration purpose)
$ kubectl get node node2 -o yaml | sed '[email protected]/infra: ""@@' | kubectl apply -f -

# check the new state of the label
$ kubectl get node node2 -o yaml | grep node-role | grep -v apiVersion
# empty output

第一次在节点资源上使用kubectl apply -f时,您可能会看到以下警告,但这不会影响结果:

Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
© www.soinside.com 2019 - 2024. All rights reserved.