如何通过Bearer Token认证用vmagent采集指标?K8s配置遇404问题
问题排查:VMStaticScrape采集报404但curl请求正常
我在GCP Kubernetes集群使用vmagent 1.79版本,已创建名为web-site-token的Secret资源,其中bearer密钥对应值为XXX。配置VMStaticScrape资源后,尝试用该Secret里的Bearer Token采集host1:9254和host2:9254的/internal/metrics指标,采集时持续返回404错误;但直接用curl携带对应请求头访问目标接口时,一切正常。相关配置如下:
--- apiVersion: v1 kind: Secret metadata: name: web-site-token data: bearer: XXX type: Opaque --- apiVersion: operator.victoriametrics.com/v1beta1 kind: VMStaticScrape metadata: name: web-site labels: xxx.com/vmagent: nodes spec: jobName: web-site targetEndpoints: - targets: - host1:9254 - host2:9254 path: /internal/metrics labels: env: preupdate region: us domain: web site: game scheme: http authorization: credentials: key: bearer name: web-site-token tlsConfig: insecureSkipVerify: true
排查与解决思路
补全authorization的type字段
当前配置的authorization块仅指定了credentials,但缺少type: Bearer。vmagent默认不会自动添加Bearer认证类型,这会导致请求头格式错误,部分服务会将无效认证的请求直接返回404而非401。只需在authorization下添加type: Bearer即可修正:authorization: type: Bearer # 新增该行 credentials: key: bearer name: web-site-token验证Secret的编码格式
Secret的data字段要求值必须是Base64编码后的内容。如果之前直接写入明文,需要重新编码后更新Secret:# 生成Base64编码的Token echo -n "实际的Bearer Token明文" | base64 # 更新Secret kubectl create secret generic web-site-token --from-literal=bearer=$(echo -n "实际Token明文" | base64) --dry-run=client -o yaml | kubectl apply -f -查看vmagent日志确认请求细节
通过vmagent的Pod日志,可直接看到采集请求的实际URL、请求头和状态码,便于定位问题:kubectl logs -l xxx.com/vmagent=nodes
内容的提问来源于stack exchange,提问作者a1dude
相关产品推荐
相关产品推荐

