Apache auto-restart if config check

At work, we have several webservers who sync the scripts, data and config between them each night. During this process, apache virtual-server configurations are also dispatched around the place (we don’t user puppet, yet?!). I was asked to create a script who would check if the syntax of the config files are ok before restarting apache, because you never know when something might go horribly wrong and apache hangs.

Just thought I would share my script, because I didn’t find someone who’s done this and posted about it. Might not be rocket science, but I’m no bash guru :-)

#!/bin/bash

# Check current apachectl status
# - configtest sends to str.err, so map it back to str.out
CHECKCONF=`/usr/sbin/apachectl -t 2>&1`

# httpd service
HTTPDS='httpd'

# Is Syntax OK: restart
echo "Check syntax files..."
if [ "$CHECKCONF" = "Syntax OK" ]
then
        echo "- Config seems OK."
        echo "Restarting apache..."
        RESTARTCTL=`/usr/sbin/apachectl restart 2>&1 | grep -v "httpd not running, trying to start"`

        # If restart isn't empty, an error occured
        if [ "$RESTARTCTL" != "" ]
        then
                echo "Error on restart: $RESTARTCTL"
                echo ""
        fi

        # Check if apache is running successfully
        echo "Check if httpd is running...."
        if ps ax | grep -v grep | grep $HTTPDS > /dev/null
        then
                echo "- HTTPD is running"
        else
                echo "- Error: HTTPD isn't running!"
        fi
else
        echo "Configcheck error: $CHECKCONF"
        echo ""
fi

Hope this helps someone :-)

Posted in geek | Tagged , | 1 Comment

One Response to Apache auto-restart if config check

  1. mk3d says:

    Cool, tu te met au sh ;-)
    Est-ce que au lieu de faire un apachectl restart un reload ne serait pas suffisant pour recharger la config? See you, good post! Like that! ;-)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>