How to use Monit Environment variables

environment-variablesmonitmonitoring

According to Monit link :

No environment variables are used by Monit. However, when Monit executes a start/stop/restart program or an exec action, it will set several environment variables which can be utilised by the executable to get information about the event, which triggered the action.

Is it possible to use those variables on custom actions?

For example, for notification I don't use mail service, then rather custom script which should receive that ENV monit variable and provide output.
This is a basic example to test env variables.

check process dhcp with pidfile "/var/run/dhcpd.pid"
        start = "/etc/init.d/isc-dhcp-server start"
        stop = "/etc/init.d/isc-dhcp-server stop"
        if does not exist program then exec "/bin/echo $MONIT_EVENT > /tmp/monittest"
        depends on lan

And when I intentionally make the program fail, like
check process dhcp with pidfile "/var/run/unexisting.pid"

I get no output in /tmp/monittest. Am I doing something wrong?

Best Answer

Yes, there be wrongness. The monit exec appears to perform an exec(3) style execution of the given string, and not a system(3) call; this means shell syntax (redirections and whatnot) are not supported as the supplied data is not being run through a shell. Instead, write suitable code that uses the monit environment variables (which will be exported to the code thus execed):

# cat /root/blah                                                               
#!/bin/sh
echo "$MONIT_EVENT" > /root/woot
# chmod +x /root/blah
#

And then call that code from the monit configuration:

# tail -2 /etc/monitrc                                                         
check process itsdeadjim with pidfile "/nopenopenope"
    if does not exist then exec "/root/blah"
# 

This populates the /root/woot file for me:

# rm /root/woot
# rcctl restart monit && sleep 10
monit(ok)
monit(ok)
# cat /root/woot
Does not exist
# 
Related Question