shellkuberneteskustomizekubeconfig

limit applying kustomize overlay to a specific cluster


Is there a way for kustomize to reject applying an overlay if KUBECONFIG is not set to the correct cluster. I'm thinking of creating a shell script that does this, is there a better way?

We apply overlays with kubectl apply -k overlays/foo. It has been the case that KUBECONFIG is set to the wrong cluster thus overwriting configurations and causing havoc...


Solution

  • A script seems to be the only way at the moment. Maybe someone can also use this. The content of the CONTEXT file is the context that should be used.

    #!/bin/bash
    if [ ! -n "$1" ]
    then
      echo "usage: apply-with-check overlay/foo"
      exit 1
    fi
    
    if [ ! -f "$1/CONTEXT" ]; then
      echo "CONTEXT missing, won't apply!"
      exit 1
    fi
    
    CONTEXT_TO_USE=$(<$1/CONTEXT)
    
    echo "checking context: $CONTEXT_TO_USE"
    
    CURRENT_CONTEXT=$(kubectl config current-context)
    
    if [[ $CONTEXT_TO_USE != $CURRENT_CONTEXT ]]; then
      echo "ALARM! current context is: $CURRENT_CONTEXT **not applying**"
      exit 1
    fi
    
    echo "ok, current context is: $CURRENT_CONTEXT, now applying"
    kubectl apply -k $1