Search code examples
kuberneteskubectlamazon-eks

Cycle for Kubernetes


I need some help. I would like to find a way to make a for loop to pass my namespaces inside the jsonpath and using kubectl commands. I tried various ways but got no result. I ran them first for test on the Git Bash terminal.

I'll show you now how I'm trying to do it:

for namespace in bike-b2p-old
                  bike-b2p-new; do kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl annotate --overwrite deploy "}{@.metadata.name}{" previous-size="}{@.spec.replicas}{"-n $namespace"}{" \n"}{end}' -n $namespace | sh; done

It should add in the annotations previus_size for both namespaces but the terminal gives me an error in execution.


Solution

  • It looks like you're trying to use kubectl get -o jsonpath to write out a shell command, and then execute that shell command. That's very clever, but it also means you're mixing multiple languages and quoting syntaxes in the same string, which can get confusing very quickly.

    I'd just write out this algorithm as you expect it to run, without trying to dynamically generate commands:

    For each Namespace:
      For each Deployment:
        Get its existing replica count
        Create the annotation
    

    Translating that into shell syntax:

    #!/bin/sh
    
    # For each namespace...
    for namespace in bike-b2p-old bike-b2p-new; do
      # For each deployment...
      for deployment in $(kubectl get -n "$namespace" deployment -o name); do
        # ($deployment has the form `deployment/some-name`)
    
        # Get the existing replica count
        replicas=$(kubectl get -n "$namespace" "$deployment" -o jsonpath='{.spec.replicas}')
    
        # Set the annotation
        kubectl annotate -n "$namespace" "$deployment" --overwrite "previous-size=$replicas"    
      done
    done
    

    When you start getting into this level of logic, you may find a higher-level language easier to work with than a shell script; there are Kubernetes client libraries for most popular languages. Also consider using a tool like Helm that can control the entire YAML file at deployment time rather than using imperative kubectl annotate commands that can result in untracked changes.