如何在就绪探针(readinessProbe)中动态添加认证令牌
动态配置Kubernetes就绪探针的Bearer令牌
Kubernetes原生的httpGet探针不支持直接引用环境变量,但可以通过以下两种常用方式实现动态令牌配置:
1. 使用exec探针替代httpGet
用curl命令发起请求,直接引用环境变量,示例配置:
readinessProbe: exec: command: - sh - -c - "curl -f -H 'Authorization: Bearer ${TOKEN}' http://localhost:8080/path" initialDelaySeconds: 5 periodSeconds: 10
这里的${TOKEN}会从Pod的环境变量中读取,你需要先把令牌注入为Pod的环境变量(比如通过Secret挂载)。
2. 借助自定义探针脚本
如果需要更复杂的逻辑,可以编写一个小脚本,挂载到Pod中执行:
- 先创建一个探针脚本
probe.sh:
#!/bin/sh TOKEN=$(cat /var/run/secrets/token/token) curl -f -H "Authorization: Bearer $TOKEN" http://localhost:8080/path
- 在Pod配置中挂载脚本和令牌Secret,然后使用
exec探针:
readinessProbe: exec: command: - /scripts/probe.sh initialDelaySeconds: 5 periodSeconds: 10 volumes: - name: probe-script configMap: name: probe-configmap - name: token-secret secret: secretName: your-token-secret volumeMounts: - name: probe-script mountPath: /scripts - name: token-secret mountPath: /var/run/secrets/token
注意:两种方式都需要确保curl已安装在Pod镜像中,如果没有,需要在镜像构建时添加(比如基于Debian/Ubuntu的镜像执行apt-get install -y curl,Alpine镜像执行apk add --no-cache curl)。
内容的提问来源于stack exchange,提问作者Ritika
相关产品推荐
相关产品推荐

