Using a Custom Script to Trigger an Action in Monit

Let’s see how to use a custom script to trigger an action if a service has restarted or if there are other problems in Monit – utility for monitoring services on a Unix system. 

1) Create a script with an action for what you want to do when Monit triggers an action.
        For example, in the code below, I need to send a message to Slack/Google chat:
slack-webhook.sh

URL='Slack Webhook URL' 
PAYLOAD="{
  "attachments": [
    {
      "title": "$PROCESS was restarted",
      "color": "#ff0000",
      "mrkdwn_in": ["text"],
      "fields": [
        { "title": "Date", "value": "$MONIT_DATE", "short": true },
        { "title": "Host", "value": "$MONIT_HOST", "short": true }
      ]
    }
  ]
}"
curl -s -X POST --data-urlencode "payload=$PAYLOAD" $URL

google-chat.sh

URL='google chat Webhook URL'

curl -H 'Content-Type: application/json' -X POST $URL -d'{
  "cardsV2": [
    {
      "cardId": "unique-card-id",
      "card": {
        "header": {
          "title": "'"$MONIT_HOST"'",
          "subtitle": "'"$PROCESS'" was restarted",
          "imageUrl":
          "https://developers.google.com/chat/images/quickstart-app-avatar.png",
          "imageType": "CIRCLE",
          "imageAltText": "Avatar for Noda"
        },
        "sections": [
          {
            "widgets": [
              {
                "decoratedText": {
                  "text": "'"$MONIT_DATE"'"
                }
              },
              {
                "decoratedText": {
                  "text": "<font color="#80e27e">Online</font>"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}
'

2) In your installed Monit, add the service that you want to monitor:
     For example, in the code below, I need to monitor elasticsearch:

check process elasticsearch with pidfile /var/run/elasticsearch/elasticsearch.pid
   start program = "/etc/init.d/elasticsearch start"
   stop  program = "/etc/init.d/elasticsearch stop"
   if changed pid then exec "/bin/bash -c 'PROCESS=Elasticsearch /opt/slack-webhook.sh'"
   if 1 restart within 1 cycle then exec "/bin/bash -c 'PROCESS=Elasticsearch /opt/slack-webhook.sh'"
check host elasticsearch_connection with address 0.0.0.0
   start program = "/etc/init.d/elasticsearch start"
   stop  program = "/etc/init.d/elasticsearch stop"
   if failed port 9200 for 4 cycles then restart

Now, when Monit triggers an action, you get a notification about it.
For example, in the screenshot below, I get a response about restarting elasticsearch.

The post Using a Custom Script to Trigger an Action in Monit appeared first on SOC Prime.