Search code examples
kubernetesyamlkubectlpatch

Patch multiple Kubernetes resources with a single command


I'm trying to patch multiple targets, of different types (let's say deployment and a replicaset) using the kubectl command. I've made the following file with all the patch information:

File patch_list_changes.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: custom-metric-sd
  namespace: default
spec:
  template:
    spec:
      containers:
      - name: sd-dummy-exporter
      resources:
        requests:
          cpu: 90m
---
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: frontend
  namespace: default
spec:
  template:
    spec:
      containers:
      - name: php-redis
      resources:
        requests:
          cpu: 200m

I've tried the following commands in the terminal, but nothing allows my to patch to work:

kubectl patch -f patch_list_changes.yaml --patch-file patch_list_changes.yaml

Output:

deployment.apps/custom-metric-sd patched
Error from server (BadRequest): the name of the object (custom-metric-sd) does not match the name on the URL (frontend)

and

kubectl apply -f patch_list_changes.yaml

Output:

error: error validating "patch_list_changes.yaml": error validating data: [ValidationError(Deployment.spec.template.spec): unknown field "resources" in io.k8s.api.core.v1.PodSpec, ValidationError(Deployment.spec): missing required field "selector" in io.k8s.api.apps.v1.DeploymentSpec]; if you choose to ignore these errors, turn validation off with --validate=false```

Is there a way to run multiple patches in a single command?

Solution

  • The appropriate approach is to use Kustomization for this purposes

    https://github.com/nirgeier/KubernetesLabs/tree/master/Labs/08-Kustomization

    Based upon those samples I wrote:

    Example:

    • Prepare your patches and use Kustomization
    # kustomization.yaml
    apiVersion: kustomize.config.k8s.io/v1beta1
    kind: Kustomization
    
    bases:
      - ../../_base
      
    patchesStrategicMerge:
    - patch-memory.yaml
    - patch-replicas.yaml
    - patch-service.yaml