Pod 内通过command + args 执行 while + for 循环

摘要

想在kubernetes的pod内执行shell的 while循环 + for 循环,现将配置记录如下

while 有限循环

---
kind: Pod
apiVersion: v1
metadata:
  name: pod-diy-command
spec:
  terminationGracePeriodSeconds: 0
  containers:
  - name: busybox-diy
    image: busybox
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh"]
    args:
    - -c
    - |
      i=0
      while [ $i -le 10 ] ;
      do
        ls -l
        sleep 30
        echo "hello world"  >> ./hello.txt
        cat ./hello.txt
        let i++
        pwd
      done
  restartPolicy: Always

效果:

# 创建
kubectl apply -f 3-pod-diy.yml
# 强制创建替换
kubectl replace --force -f 3-pod-diy.yml
# 查看记录
kubectl logs -f pod-diy-command

while 无限循环

---
kind: Pod
apiVersion: v1
metadata:
  name: pod-diy-command
spec:
  terminationGracePeriodSeconds: 0
  containers:
  - name: busybox-diy
    image: busybox
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh"]
    args:
    - -c
    - |
      while true ;
      do
        ls -l
        sleep 3
        echo "hello world"  >> ./hello.txt
        cat ./hello.txt
        pwd
      done
  restartPolicy: Always

效果:

for 循环

pod 内的command + args可能无法像Linux操作系统那样,书写 for i in {1..100}的这种方式进行for循环的遍历。
只能通过指定遍历的方式执行
---
kind: Pod
apiVersion: v1
metadata:
  name: pod-diy-command
spec:
  terminationGracePeriodSeconds: 0
  containers:
  - name: busybox-diy
    image: busybox
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh"]
    args:
    - -c
    - |
      for i in 01 02 03 04 05
      do
        ls -l
        sleep 3
        echo $i  >> ./hello.txt
        cat ./hello.txt
        pwd
      done
  restartPolicy: Always

猜你喜欢

转载自blog.csdn.net/m0_59267075/article/details/129541616