You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ansible/library/service

112 lines
2.8 KiB
Python

#!/usr/bin/python
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
try:
import json
except ImportError:
import simplejson as json
import os
import sys
import shlex
import subprocess
# ===========================================
argfile = sys.argv[1]
args = open(argfile, 'r').read()
items = shlex.split(args)
if not len(items):
print "failed=True msg='the module requires arguments (-a)'"
sys.exit(1)
params = {}
for x in items:
(k, v) = x.split("=")
params[k] = v
name = params['name']
state = params.get('state','unknown')
if state not in [ 'running', 'stopped', 'restarted' ]:
print "failed=True msg='invalid state'"
sys.exit(1)
# ===========================================
# get service status
status = os.popen("/sbin/service %s status" % name).read()
# ===========================================
# determine if we are going to change anything
running = False
if status.find("not running") != -1:
running = False
elif status.find("running") != -1:
running = True
elif name == 'iptables' and status.find("ACCEPT") != -1:
# iptables status command output is lame
# TODO: lookup if we can use a return code for this instead?
running = True
changed = False
if not running and state == "started":
changed = True
elif running and state == "stopped":
changed = True
elif state == "restarted":
changed = True
# ===========================================
# run change commands if we need to
def _run(cmd):
return subprocess.call(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
rc = 0
if changed:
if state == 'started':
rc = _run("/sbin/service %s start" % name)
elif state == 'stopped':
rc = _run("/sbin/service %s stop" % name)
elif state == 'restarted':
rc1 = _run("/sbin/service %s stop" % name)
rc2 = _run("/sbin/service %s start" % name)
rc = rc1 and rc2
if rc != 0:
# yeah, should probably include output of failure...
print json.dumps({
"failed" : 1,
"rc" : rc
})
sys.exit(1)
# ===============================================
# success
print json.dumps({
"changed" : changed
})