You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本中kubectl exec内token变量赋值为空问题求助

问题:Kubectl Exec Here-Doc中变量无法传递到外部脚本

你的脚本存在两个核心问题:

  • Here-Doc中的$(cat ...)会被本地Shell解析执行,而非Pod内的Shell,本地机器不存在/var/run/secrets/kubernetes.io/serviceaccount/token路径,自然无法获取值。
  • 即便在Pod内的Shell中赋值了token变量,该变量仅存在于Pod内的Shell进程中,外部脚本的Shell进程无法访问跨进程的变量。

解决方案1:直接捕获Pod内命令输出

如果只是获取token,不需要多步交互,最简洁的方式是直接让kubectl exec执行cat命令,外部捕获输出:

token=$(kubectl exec $pod_name -n <namespace> -- cat /var/run/secrets/kubernetes.io/serviceaccount/token)
echo "retrieved token: $token"

解决方案2:禁止本地Shell扩展Here-Doc内容

如果需要保留多步操作逻辑,给Here-Doc的EOF加上单引号(<<'EOF'),禁止本地Shell解析其中的变量和命令替换,让所有逻辑在Pod内的Shell执行,再捕获输出:

token=$(kubectl exec $pod_name -n <namespace> /bin/bash <<'EOF'
echo "Step 3: Retrieving token from pod: $pod_name"
cat /var/run/secrets/kubernetes.io/serviceaccount/token
exit
EOF
)
echo "retrieved token: $token"

若需要在Pod内使用本地的$pod_name变量,可保留<<EOF但转义内部的命令替换符号(不需要转义$pod_name,让本地Shell替换为实际值):

token=$(kubectl exec $pod_name -n <namespace> /bin/bash <<EOF
echo "Step 3: Retrieving token from pod: $pod_name"
cat /var/run/secrets/kubernetes.io/serviceaccount/token
exit
EOF
)
echo "retrieved token: $token"

内容的提问来源于stack exchange,提问作者tshalamb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:47:07