Kubernetes cron job call curl in loop

7/5/2018

I am using kubernetes 1.10 cluster and I want to schedule cron job which will use bash script to loop forever and send get request to http endpoint in every two seconds.

Here is my job 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

The problem is that output is unexpected, because curl request is made only once and even before the loop, than program loops without any curl request made:

...
 > 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

I think I have mistake in script, But with my current knowledge of bash scripting I can't fix this problem. Can anyone point me what's wrong ?

Thank you

-- Davit Tvildiani
alpine
bash
curl
kubernetes

1 Answer

7/5/2018

Minor modification:

dollar sign $ should be escaped -> \$

"\$exit_status" in place of $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
            "
-- arunp9294
Source: StackOverflow