manifests/ping-all-node/job-alpine.yaml
2025-04-12 13:11:34 +08:00

88 lines
2.9 KiB
YAML

apiVersion: batch/v1
kind: CronJob
metadata:
name: ping-nodes
namespace: cron
spec:
schedule: "*/5 * * * *" # 每5分钟执行一次
concurrencyPolicy: Allow
jobTemplate:
spec:
template:
spec:
serviceAccountName: ping-nodes-sa # 需要创建具有节点列表权限的服务账号
containers:
- name: ping-nodes
image: busybox
command:
- /bin/sh
- -c
- |
# 安装必要工具
#apk add --no-cache kubectl curl dnsutils iputils
# 获取当前节点的主机名
CURRENT_NODE=$(cat /etc/hostname)
echo "Current node: $CURRENT_NODE"
# 获取所有节点的 IP 地址
NODE_IPS=$(kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}')
# 遍历每个节点 IP 并 ping
for IP in $NODE_IPS; do
# 检查是否为当前节点的 IP
CURRENT_IP=$(kubectl get nodes $CURRENT_NODE -o jsonpath='{.status.addresses[?(@.type=="InternalIP")].address}' 2>/dev/null)
if [ "$IP" != "$CURRENT_IP" ]; then
echo "Pinging node IP: $IP"
ping -c 3 $IP
echo "-----------------------------------"
fi
done
# 或者使用节点名称获取其 ZeroTier IP 地址并 ping
# 如果 ZeroTier IP 地址存储在节点标签或注释中
NODE_NAMES=$(kubectl get nodes -o jsonpath='{.items[*].metadata.name}')
for NODE in $NODE_NAMES; do
if [ "$NODE" != "$CURRENT_NODE" ]; then
echo "Pinging node: $NODE"
# 你需要调整这里来获取 ZeroTier IP
# 例如,如果你将 ZeroTier IP 存储在节点标签中:
# ZT_IP=$(kubectl get node $NODE -o jsonpath='{.metadata.labels.zerotier-ip}')
# ping -c 3 $ZT_IP
# 或者直接使用节点名称 ping (如果DNS解析配置正确)
ping -c 3 $NODE
echo "-----------------------------------"
fi
done
restartPolicy: OnFailure
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: ping-nodes-sa
namespace: cron
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-reader
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ping-nodes-rb
subjects:
- kind: ServiceAccount
name: ping-nodes-sa
namespace: cron
roleRef:
kind: ClusterRole
name: node-reader
apiGroup: rbac.authorization.k8s.io