kubectl patch命令日常用法

1、使用策略性合并补丁更新一个 Deployment

    通过补丁,您可以避免定义整个对象,只需要定义您希望更改的部分。
    通过策略性合并补丁,您只需要定义新增的元素就可以更新一个列表。
列表中已有的元素仍然保留,新增的元素和已有的元素会被合并。上述例子
中,最终结果的 containers 列表中既有原先的 nginx 容器,也有新增的 redis 容器。
第一步: 创建一个deployment
# cat deployment-patch-demo.yaml

apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: patch-demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: patch-demo-ctr
        image: nginx
      tolerations:
      - effect: NoSchedule
        key: dedicated
        value: test-team

$ kubectl create -f ./deployment-patch-demo.yaml

 

第二步: patch 更新 api 对象
# cat patch-file.yaml

spec:
  template:
    spec:
      containers:
      - name: patch-demo-ctr-2
        image: redis

$ kubectl patch deployment patch-demo --patch "$(cat patch-file.yaml)"

 

第三步: 查看更新结果
kubectl get deployment patch-demo --output yaml

 


# deployment中的POD中会有两个容器

2、使用一个 JSON 合并补丁更新一个 Deployment

第一步: 创建一个deployment (同上)
第二步: patch 更新api对象
cat patch-file-2.yaml

spec:
  template:
    spec:
      containers:
      - name: patch-demo-ctr-3
        image: gcr.io/google-samples/node-hello:1.0

$ kubectl patch deployment patch-demo --type merge --patch "$(cat patch-file-2.yaml)"

 

第三步: 查看更新结果
kubectl get deployment patch-demo --output yaml

 


# deployment中的POD中只有一个容器,原容器被替换

3、其他

# 等价命令
kubectl patch deployment patch-demo --patch "$(cat patch-file.yaml)"
kubectl patch deployment patch-demo --patch $'spec:\n template:\n  spec:\n   containers:\n   - name: patch-demo-ctr-2\n     image: redis'

kubectl patch deployment patch-demo --patch "$(cat patch-file.json)"

kubectl patch deployment patch-demo --patch '{"spec": {"template": {"spec": {"containers": [{"name": "patch-demo-ctr-2","image": "redis"}]}}}}'

 



kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

kubectl patch pod xxx -n xxx --type=json -p '[{"op":"replace","path":"/a/b/c","value":456}]'

a:
 b:
  c:456

 

#yaml生成工具
https://k8syaml.com/
https://www.yuque.com/coolops/kubernetes/ke3qu2

 




posted @ 2022-01-09 00:27  夜辰雪扬  阅读(3267)  评论(0编辑  收藏  举报