Skip to content

Commit

Permalink
refactor(kube): Update kube logs function, use current namespace - if…
Browse files Browse the repository at this point in the history
… parameter not provided
  • Loading branch information
kpatryk committed Sep 2, 2024
1 parent 890bdc4 commit 4536de4
Showing 1 changed file with 45 additions and 8 deletions.
53 changes: 45 additions & 8 deletions functions/containers/kubernetes/logs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,64 @@ fi
prevent_to_execute_directly

kube_logs_dump_from_pod_containers_with_filter() {
local namespace="$1"
local pod_name="$2"
local filter="$3"
local namespace=""
local pod_name=""
local filter=""

while [[ "$#" -gt 0 ]]; do
case $1 in
-n | --namespace)
namespace="$2"
shift
;;
-p | --pod)
pod_name="$2"
shift
;;
-f | --filter)
filter="$2"
shift
;;
*)
echo "Unknown parameter passed: $1"
return 1
;;
esac
shift
done

if [[ -z "$pod_name" || -z "$namespace" ]]; then
echo "Usage: ${FUNCNAME[0]} <namespace> <pod_name> [filter]"
if [[ -z "$pod_name" ]]; then
echo "Usage: ${FUNCNAME[0]} -p|--pod <pod_name> [-n|--namespace <namespace>] [-f|--filter <filter>]"
echo "Pod name is required. Namespace is optional (current namespace will be used if not specified)."
return 1
fi

# If namespace is not provided, get the current namespace
if [[ -z "$namespace" ]]; then
namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}')
if [[ -z "$namespace" ]]; then
echo "No namespace specified and unable to determine current namespace."
return 1
fi
echo "Using current namespace: $namespace"
fi

local containers
containers=$(kubectl get pod "$pod_name" -n "$namespace" -o jsonpath='{.spec.containers[*].name} {.spec.initContainers[*].name}' | xargs)

if [[ -z "$containers" ]]; then
echo "No containers found in pod $pod_name in namespace $namespace"
return 1
fi

local -a read_params=("-r" "-a")
if [[ $SHELL == *"zsh"* ]]; then
read_params=("-r" "-A")
fi
# shellcheck disable=SC2162
IFS=' ' read "${read_params[@]}" container_array <<<"$containers"
IFS=' ' read -r "${read_params[@]}" container_array <<<"$containers"

for container in "${container_array[@]}"; do
echo -e "${GREEN}== Logs for container $container in pod $pod_name ==${RESET}"
echo -e "${GREEN}== Logs for container $container in pod $pod_name (namespace: $namespace) ==${RESET}"
if [[ -n "$filter" ]]; then
kubectl logs -n "$namespace" "$pod_name" -c "$container" | grep -E -i "$filter"
else
Expand Down

0 comments on commit 4536de4

Please sign in to comment.