kubectl run override nodeselctor: error: Invalid JSON Patch

kubectl run override nodeselctor: error: Invalid JSON Patch

我正在尝试覆盖 kubectl run 的节点选择器。

kubectl run -it powershell --image=mcr.microsoft.com/powershell:lts-nanoserver-1809-20211215 --restart=Never --overrides='{ "apiVersion": "v1", "spec": { "template": { "spec": { "nodeSelector": { "kubernetes.io/os": "windows" } } } } }' -- pwsh

但我得到“无效的 Json 路径”。

如果我进行部署,这是我的 yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
 ...
spec:
  ...
  template:
    ...
    spec:
      ...
      nodeSelector:
        kubernetes.io/os: windows

如果我这样做 get pods -o json 我得到:

{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        ...
    },
    "spec": {
        ...
        "nodeSelector": {
            "kubernetes.io/os": "windows"
        }

kubectl run 是启动 Pod 的命令。您可以阅读更多相关信息 here

kubectl run -it powershell --image=mcr.microsoft.com/powershell:lts-nanoserver-1809-20211215 --restart=Never --overrides='{ "apiVersion": "v1", "spec": { "template": { "spec": { "nodeSelector": { "kubernetes.io/os": "windows" } } } } }' -- pwsh

使用上面的命令,您正在尝试 运行 具有规范 "template": { "spec": { Pod,它仅用于 Deployment,这就是您收到错误 Invalid Json Path.

nodeSelector 如您在 documentation 中所见,可以在 Pod 配置文件中的 spec 下指定,如下所示:

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    env: test
spec:
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent
  nodeSelector:
    disktype: ssd

当您将 --dry-run=client -o yaml 添加到您的命令以查看对象将如何被处理时,您将看到以下没有 nodeSelector:

的输出
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: powershell
  name: powershell
spec:
  containers:
  - image: mcr.microsoft.com/powershell:lts-nanoserver-1809-20211215
    name: powershell
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}

要解决您的问题,您可以从命令中删除 templatespec,如下所示:

kubectl run -it powershell --image=mcr.microsoft.com/powershell:lts-nanoserver-1809-20211215 --restart=Never --overrides='{ "apiVersion": "v1", "spec": { "nodeSelector": { "kubernetes.io/os": "windows" } } }' -- pwsh

添加--dry-run=client -o yaml看看会发生什么变化,你会看到nodeSelector存在:

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: powershell
  name: powershell
spec:
  containers:
  - image: mcr.microsoft.com/powershell:lts-nanoserver-1809-20211215
    name: powershell
    resources: {}
  dnsPolicy: ClusterFirst
  nodeSelector:
    kubernetes.io/os: windows
  restartPolicy: Never
status: {}