Create a gist now

Instantly share code, notes, and snippets.

Generic service init script written using a jinja2 template which is then called by a template task in an ansible play.
#!/bin/bash
### BEGIN INIT INFO
# Provides: {{ item.service_name }}
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: {{ item.service_description }}
### END INIT INFO
# Taken loosely from https://gist.github.com/tilfin/5004848
prgcmd={{ item.service_exec }} # What gets executed?
prgname={{ item.service_name }} # What's the name (used to ensure only one instance is running)
prguser={{ item.service_user }} # Which user should be used
pidfile=/var/run/{{ item.service_name }}.pid # Where should the pid file be stored?
logfile=/var/log/{{ item.service_name }}.log
export BJA_CONFIG={{ bja_config }}
start() {
if [ -f $pidfile ]; then
pid=`cat $pidfile`
kill -0 $pid >& /dev/null
if [ $? -eq 0 ]; then
echo "{{ item.service_name }} has already been started."
return 1
fi
fi
echo -n "Starting {{ item.service_name }}"
nohup start-stop-daemon -c $prguser -n $prgname -p $pidfile -m --exec /usr/bin/env --start $prgcmd >> $logfile 2>&1 &
if [ $? -eq 0 ]; then
echo "."
return 0
else
echo "Failed to start {{ item.service_name }}."
return 1
fi
}
stop() {
if [ ! -f $pidfile ]; then
echo "{{ item.service_name }} not started."
return 1
fi
echo -n "Stopping {{ item.service_name }}."
start-stop-daemon -p $pidfile --stop
if [ $? -ne 0 ]; then
echo "Failed to stop {{ item.service_name }}."
return 1
fi
rm $pidfile
echo "."
}
status() {
if [ -f $pidfile ]; then
pid=`cat $pidfile`
kill -0 $pid >& /dev/null
if [ $? -eq 0 ]; then
echo "{{ item.service_name }} running. (PID: ${pid})"
return 0
else
echo "{{ item.service_name }} might have crashed. (PID: ${pid} file remains)"
return 1
fi
else
echo "{{ item.service_name }} not started."
return 0
fi
}
restart() {
stop
if [ $? -ne 0 ]; then
return 1
fi
sleep 2
start
return $?
}
case "$1" in
start | stop | status | restart)
$1
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
exit 2
esac
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment