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
相关产品推荐
相关产品推荐

