Dernière activité 1 week ago

此腳本用於顯示 Kubernetes 環境中 Pod、Service、NodePort、Ingress 的狀態與連線資訊,並列出 PVC,方便快速掌握服務部署與存取方式。特別適用於 k3s + Traefik 環境。

k8s_status_access.sh Brut
1#!/usr/bin/env bash
2# 用途:查看 Kubernetes 服務狀態與實際連線方式
3# 包含:Pod、Service(NodePort)、Ingress(HTTP/HTTPS)、PVC
4# 適用:k3s + Traefik
5
6set -euo pipefail
7
8echo
9echo "=== Pods ==="
10kubectl get pods -o wide
11
12echo
13echo "=== Services ==="
14kubectl get svc
15
16echo
17echo "=== Node IPs ==="
18kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{range .status.addresses[?(@.type=="InternalIP")]}{.address}{" "}{end}{"\n"}{end}'
19
20echo
21echo "=== NodePort Access ==="
22NODE_IPS=$(kubectl get nodes -o jsonpath='{range .items[*]}{.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}')
23NODEPORT_SVCS=$(kubectl get svc -o jsonpath='{range .items[?(@.spec.type=="NodePort")]}{.metadata.name}{"\t"}{.spec.ports[0].nodePort}{"\n"}{end}')
24
25if [ -z "$NODEPORT_SVCS" ]; then
26 echo "(無 NodePort 服務)"
27else
28 for ip in $NODE_IPS; do
29 while IFS=$'\t' read -r svc port; do
30 echo "- $ip:$port ($svc)"
31 done <<< "$NODEPORT_SVCS"
32 done
33fi
34
35echo
36echo "=== Ingress (Access URLs) ==="
37INGRESS_LIST=$(kubectl get ingress -o name 2>/dev/null || true)
38
39if [ -z "$INGRESS_LIST" ]; then
40 echo "(無 Ingress)"
41else
42 for ing in $INGRESS_LIST; do
43 NAME=$(kubectl get "$ing" -o jsonpath='{.metadata.name}')
44 HOSTS=$(kubectl get "$ing" -o jsonpath='{range .spec.rules[*]}{.host}{"\n"}{end}')
45 TLS=$(kubectl get "$ing" -o jsonpath='{.spec.tls}')
46
47 echo "- $NAME"
48 while read -r host; do
49 [ -z "$host" ] && continue
50 if [ -n "$TLS" ]; then
51 echo " https://$host"
52 else
53 echo " http://$host"
54 fi
55 done <<< "$HOSTS"
56 done
57fi
58
59echo
60echo "=== PVC ==="
61kubectl get pvc
62
63