0

I have this script that checks if the webserver is up and the health check succeeds. I was using "sleep" before the service starts. I am looking to improve it, and put some "iteration/until" options which will check if service health check succeeds, but will timeout 60/120 seconds and do the LB registration else will throw an error.

#!/bin/bash
instanceid=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)

healthcheck=$(curl -X GET http://localhost | grep "yes its working")

HEALTHCHECK=$?

if [ $HEALTHCHECK -eq 0 ] ; then
echo "Server registered to ELB"
usr/local/bin/aws elbv2 register-targets --target-group-arn arn:aws:elasticloadbalancing:ap-south-1:xxxxxxxx:targetgroup/my-targetgroup/xxxxxxxx --targets Id=$instanceid

exit 0

else
echo "healthcheck failed"
exit 0
fi
Biffen
  • 6,249
  • 6
  • 28
  • 36
PriyeshG
  • 1
  • 1

2 Answers2

0

Try something like this:

#! /bin/bash

: ${TIMEOUT:=10}
: ${INTERVAL:=2}
: ${FAIL:=no}

healthcheck()
{
  case "$FAIL" in
    no) true;;
    *) false;;
  esac
}

(
  while true; do
    if healthcheck; then
      echo "Server registered to ELB"
      exit 0
    else
      echo "healthcheck failed"
    fi
    sleep "$INTERVAL"
  done
) & child=$!

kill_child() { kill -TERM "$child"; }

# See https://stackoverflow.com/a/11056286/402322
(
  sleep "$TIMEOUT" && {
    kill_child
    printf 'Timeout after %d seconds.\n' "$TIMEOUT"
  }
) 2>/dev/null & watcher=$!

kill_watcher () { pkill -TERM -P "$watcher"; }

trap kill_child INT
trap kill_watcher EXIT

wait "$child"

Example usage for success and timeout:

$ ./healthcheck.sh
Server registered to ELB
$ FAIL=yes ./healthcheck.sh
healthcheck failed
healthcheck failed
healthcheck failed
healthcheck failed
healthcheck failed
Timeout after 10 seconds.
ceving
  • 21,900
  • 13
  • 104
  • 178
0

Thank you @ceving, Used iteration with exit 0. This retries 5 times if the status check fails and exits. If the health check succeeds it will register to LB.

#!/bin/bash

instanceid=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)

for itr in {1..5}
do
healthcheck=$(curl -X GET http://localhost | grep "yes its working")
healthcheck=$?
if [ "$HEALTHCHECK" -ne 0 ] ; then
echo "Healthcheck failed. sleeping for 5 sec"
sleep 5
echo 'Iteration' $itr
if [ $itr == 5 ]; then
echo 'Failed to register instance to ELB.'
fi
else
echo "Server registered to ELB"
usr/local/bin/aws elbv2 register-targets --target-group-arn arn:aws:elasticloadbalancing:ap-south-1:xxxxxxxx:targetgroup/my-targetgroup/xxxxxxxx --targets Id=$instanceid
exit 0
fi
done
PriyeshG
  • 1
  • 1