K8s InitContainer中$ip_list变量在Dashboard中丢失问题求助
问题:K8s InitContainer脚本中
$ip_list变量被自动移除 我在Kubernetes Pod的YAML配置中,为InitContainer编写了一段bash脚本。部署完成后,在K8s Dashboard查看容器YAML配置时,发现脚本里的$ip_list变量被移除了。
原配置代码
initContainers: - name: init-redis image: busybox:1.36.1-glibc command: - sh - '-c' - >- until [ $(nslookup headless-svc.default.svc.cluster.local | grep 'Address: ' | awk '{print $2}' | wc -w) = 3 ]; do echo Waiting-all-instances...; sleep 1; done; for ip_list in $(nslookup headless-svc.default.svc.cluster.local | awk '/^Address: / { print $2 }'); do until nc -vz $ip_list 80; do echo waiting-SENTINEL...; sleep 1; done; done;
K8s Dashboard中显示的配置代码
initContainers: - name: init-redis image: busybox:1.36.1-glibc command: - sh - '-c' - >- until [ $(nslookup headless-svc.default.svc.cluster.local | grep 'Address: ' | awk '{print $2}' | wc -w) = 3 ]; do echo Waiting-all-instances...; sleep 1; done; for ip_list in $(nslookup headless-svc.default.svc.cluster.local | awk '/^Address: / { print $2 }'); do until nc -vz 80; do echo waiting-SENTINEL...; sleep 1; done; done;
原因分析
这是YAML字符串解析机制导致的问题:当使用>-折叠块标量格式时,Kubernetes或Dashboard的解析逻辑会把$ip_list识别为YAML变量,由于没有对应的变量定义,最终会将其移除。
解决方法
方法一:转义美元符号
给脚本中的$ip_list加上反斜杠转义,让YAML将其视为普通字符串传递给bash:
initContainers: - name: init-redis image: busybox:1.36.1-glibc command: - sh - '-c' - >- until [ $(nslookup headless-svc.default.svc.cluster.local | grep 'Address: ' | awk '{print $2}' | wc -w) = 3 ]; do echo Waiting-all-instances...; sleep 1; done; for ip_list in $(nslookup headless-svc.default.svc.cluster.local | awk '/^Address: / { print $2 }'); do until nc -vz \$ip_list 80; do echo waiting-SENTINEL...; sleep 1; done; done;
方法二:使用单引号包裹脚本
将整个脚本用单引号包裹,同时转义脚本内部的单引号,这样YAML不会解析内部的美元符号:
initContainers: - name: init-redis image: busybox:1.36.1-glibc command: - sh - '-c' - 'until [ $(nslookup headless-svc.default.svc.cluster.local | grep ''Address: '' | awk ''{print $2}'' | wc -w) = 3 ]; do echo Waiting-all-instances...; sleep 1; done; for ip_list in $(nslookup headless-svc.default.svc.cluster.local | awk ''/^Address: / { print $2 }''); do until nc -vz $ip_list 80; do echo waiting-SENTINEL...; sleep 1; done; done;'
内容的提问来源于stack exchange,提问作者Batuhan Avlayan
相关产品推荐
相关产品推荐

