Home > database >  Shell Script for delete the namespace if it is existed and waited till it complete
Shell Script for delete the namespace if it is existed and waited till it complete

Time:11-30

script will need to check if aaa-new-ui-dev and bbb-java-new-ui-dev namespace exist - and if it exists - it needs to delete them and wait until delete operation is complete

I am trying to create a shell script which check if namespace is exist and if it exists then it should delete the kubectl namespace.

CodePudding user response:

# For each namespace to delete.
for ns in aaa-new-ui-dev bbb-java-new-ui-dev ; do 
  # If 'get' returns 0, then the namespace exists. 
  if kubectl get namespace/$ns ; then
    # Issue delete. 
    kubectl delete namespace/$ns
    # Wait up to 30 seconds for deletion.
    kubectl wait --for=delete namespace/$ns --timeout=30s
  else
    # Get returned an error. Assume namespace does not exist.
    echo "$project does not exist; skipping delete"
  fi
done

CodePudding user response:

I just issue the deletion because there is not need to validate if exists.

Also I'm printing a dot just to have a visual idea of the wait command - it will print a dot each 0.1s until the deletion is complete

ns_to_delete=(aaa-new-ui-dev bbb-java-new-ui-dev)

# For each namespace to delete.
for ns in ${ns_to_delete[@]} ; do 
  if ! output=$(kubectl delete namespace/$ns 2>&1); then
    printf "$ns does not exists, not need to delete it\n" >&2
  else
    printf "Deleting $ns \n" >&2
    while sleep 0.1; do printf "."; done &
        kubectl wait --for=delete namespace/$ns
    kill $!
    echo "Deleted!"
  fi
done

Expected output assuming just aaa-new-ui-dev exists:

Deleting aaa-new-ui-dev 
...........Deleted!
bbb-java-new-ui-dev does not exists, not need to delete it
  • Related