【问题标题】:Kubernetes cron job call curl in loopKubernetes cron 作业在循环中调用 curl
【发布时间】:2018-12-14 07:56:22
【问题描述】:

我正在使用 kubernetes 1.10 集群,我想安排 cron 作业,该作业将使用 bash 脚本永远循环并每两秒向 http 端点发送 get 请求。

这是我的工作 yaml:

apiVersion: batch/v1
kind: Job
metadata:
  name: notifsender-sms-cron
  namespace: staging
spec:
  template:
    spec:
      containers:
      - name: notifsender-sms-cron
        image: alpine:latest
        command: ["/bin/sh"]
        args:
          - -c
          - >
            apk update && apk add --no-cache curl bash && bash -c 
            " echo \"Running cron loop\";
              while true; 
              do
                exit_status=$(curl -v -o /dev/null -w '%{http_code}' http://bbc.com);
                if [ $exit_status -ne 200 ]; then
                    exit 1;
                fi
                sleep 2;
              done
              "
      restartPolicy: OnFailure
  backoffLimit: 4

问题是输出是意外的,因为 curl 请求只发出一次,甚至在循环之前,而不是没有发出任何 curl 请求的程序循环:

...
 > Accept: */*
 > 
 < HTTP/1.1 301 Moved Permanently
 < Server: Varnish
 < Retry-After: 0
 < Content-Length: 0
 < Accept-Ranges: bytes
 < Date: Thu, 05 Jul 2018 17:53:32 GMT
 < Via: 1.1 varnish
 < Connection: close
 < X-Served-By: cache-fra19122-FRA
 < X-Cache: MISS
 < X-Cache-Hits: 0
 < X-Timer: S1530813212.281242,VS0,VE0
 < Location: http://www.bbc.com/
 < cache-control: public, max-age=3600
 < 

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
* Closing connection 0
Running cron loop
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected
bash: line 4: [: -ne: unary operator expected

我认为我的脚本有错误,但是以我目前对 bash 脚本的了解,我无法解决这个问题。谁能指出我出了什么问题?

谢谢

【问题讨论】:

    标签: bash curl kubernetes alpine


    【解决方案1】:

    小改动:

    美元符号 $ 应该被转义 -> \$

    "\$exit_status" 代替 $exit_status

    bash -c " echo \"Running cron loop\";
                while true; 
                do
                exit_status=\$(curl -v -o /dev/null -w '%{http_code}' http://bbc.com);
                if [ \$exit_status -ne 200 ]; then
                    exit 1;
                fi
                sleep 2;
                done
                "
    

    【讨论】:

    • 天啊,真是个愚蠢的错误,谢谢你拯救了我的一天 :)
    猜你喜欢
    • 2019-11-21
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2020-03-09
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多