我正试图让一个busyboxPod每秒以JSON格式输出一些日志,同时更新time
时间戳和msg
值以进行调试。
为此,我创建了以下hello-pod
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: hello-pod
spec:
containers:
- name: count
image: busybox
args: [
/bin/sh,
-c,
'i=0; while true; do echo "{"time":$(date +%s),"msg":"This is my dummy log number $i"}"; i=$((i+1)); sleep 1; done'
]
EOF
我希望Pod将以下内容写入标准输出
{"time":1662474158,"msg":"This is my dummy log number 0"}
{"time":1662474159,"msg":"This is my dummy log number 1"}
{"time":1662474160,"msg":"This is my dummy log number 2"}
然而,我得到了相同的日志输出,time
保持不变,i
没有值。
{"time":1662473834,"msg":"This is my dummy log number "}
{"time":1662473834,"msg":"This is my dummy log number "}
{"time":1662473834,"msg":"This is my dummy log number "}
在查看了这个线程之后,我尝试用echo "{"time":my-time}" | sed "s/my-time/$(date +%s)/"
更新第三个参数中的echo语句,我希望用新的当前时间替换my-time
字符串,但我仍然得到了相同的结果。(每秒输出的第一个回波(
如果删除kubectl apply -f -
,您将看到cat
'd到kubectl
是什么,我想您会发现在生成文件时变量已经被替换过一次。
这应该有效:
echo 'apiVersion: v1
kind: Pod
metadata:
name: hello-pod
spec:
containers:
- name: count
image: busybox
args: [
/bin/sh,
-c,
"i=0; while true; do echo {"time":$(date +%s),"msg":"This is my dummy log number ${i}"}; i=$((i+1)); sleep 1; done"
]' | kubectl apply --filename=-
我个人的偏好是避免将JSON[...]
与YAML组合,并使用YAML的管道(|
(来更干净地布置脚本:
echo 'apiVersion: v1
kind: Pod
metadata:
name: hello-pod
spec:
containers:
- name: count
image: busybox
command:
- /bin/sh
- -c
args:
- |
i=0
while true
do
echo "{"time":$(date +%s),"msg":"This is my dummy log number ${i}"}"
i=$((i+1))
sleep 1
done
' | kubectl apply --filename=-