Skip to content

Commit

Permalink
feat(kube): Allow to display / delete pods based on their status
Browse files Browse the repository at this point in the history
  • Loading branch information
kpatryk committed Sep 12, 2024
1 parent 2bcc3d8 commit c041f26
Showing 1 changed file with 104 additions and 0 deletions.
104 changes: 104 additions & 0 deletions functions/containers/kubernetes/pod.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,110 @@ else
fi
prevent_to_execute_directly

kube_pods_by_status() {
local namespace="" status="" delete_flag=false OPTIND

show_help() {
echo "Usage: kube_pod_show_pod_by_status [-n NAMESPACE] [-s STATUS] [-d] [-h]"
echo
echo "Options:"
echo " -n NAMESPACE Specify the Kubernetes namespace (default: current namespace)"
echo " -s STATUS Specify the pod status to filter (init, running, completed, failed)"
echo " -d Delete the pods instead of showing them"
echo " -h Display this help message"
echo
echo "Example:"
echo " kube_pod_show_pod_by_status -n my-namespace -s running"
echo " kube_pod_show_pod_by_status -s completed -d"
}

# Parse arguments
while getopts ":n:s:dh" opt; do
case ${opt} in
n)
namespace=$OPTARG
;;
s)
status=$OPTARG
;;
d)
delete_flag=true
;;
h)
show_help
return 0
;;
\?)
echo "Invalid Option: -$OPTARG" 1>&2
show_help
return 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
show_help
return 1
;;
esac
done
shift $((OPTIND - 1))

# Show help if no arguments provided
if [[ -z "$namespace" ]] && [[ -z "$status" ]] && [[ "$delete_flag" == false ]]; then
show_help
return 0
fi

# If no namespace is provided, use the current namespace
if [[ -z "$namespace" ]]; then
namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}')
# If still empty, default to "default" namespace
namespace=${namespace:-default}
fi

# Validate and normalize status
if [[ -z "$status" ]]; then
echo "Error: Status must be provided with -s flag" >&2
return 1
fi

case ${status,,} in
init | pending)
status="Pending"
;;
running)
status="Running"
;;
completed | succeeded)
status="Succeeded"
;;
failed)
status="Failed"
;;
*)
echo "Invalid status. Please use one of: init, running, completed, failed" >&2
return 1
;;
esac

# Get pods with the specified status
local pods
pods=$(kubectl get pods -n "$namespace" --field-selector=status.phase="$status" -o name)

if [[ -z "$pods" ]]; then
echo "No pods found with status '$status' in namespace '$namespace'"
return 0
fi

# Show or delete pods
if $delete_flag; then
echo "Deleting pods with status '$status' in namespace '$namespace':"
echo "$pods" | xargs kubectl delete -n "$namespace"
else
echo "Pods with status '$status' in namespace '$namespace':"
echo "$pods" | xargs kubectl get -n "$namespace"
fi
}

# List all images used in the current namespace
kube_pods_list_image_names_per_namespace() {
local namespace=${1}
Expand Down

0 comments on commit c041f26

Please sign in to comment.