Standardizing the module

reviewable/pr18780/r1
Nikhil Singh 12 years ago committed by Michael DeHaan
parent 12b7b2750c
commit f24c75ce58

@ -17,29 +17,10 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
try:
import json
except ImportError:
import simplejson as json
import sys
import shlex
import subprocess
import os.path
import syslog
# TODO: switch to fail_json and other helper functions
# like other modules are using
# ===========================================
SERVICE = None SERVICE = None
CHKCONFIG = None CHKCONFIG = None
def fail_json(d): def _find_binaries(m):
print json.dumps(d)
sys.exit(1)
def _find_binaries():
# list of possible paths for service/chkconfig binaries # list of possible paths for service/chkconfig binaries
# with the most probable first # with the most probable first
global CHKCONFIG global CHKCONFIG
@ -63,11 +44,11 @@ def _find_binaries():
elif location.get('update-rc.d', None): elif location.get('update-rc.d', None):
CHKCONFIG = location['update-rc.d'] CHKCONFIG = location['update-rc.d']
else: else:
fail_json(dict(failed=True, msg='unable to find chkconfig or update-rc.d binary')) m.fail_json(msg='unable to find chkconfig or update-rc.d binary')
if location.get('service', None): if location.get('service', None):
SERVICE = location['service'] SERVICE = location['service']
else: else:
fail_json(dict(failed=True, msg='unable to find service binary')) m.fail_json(msg='unable to find service binary')
if location.get('initctl', None): if location.get('initctl', None):
INITCTL = location['initctl'] INITCTL = location['initctl']
else: else:
@ -145,57 +126,37 @@ def _do_enable(name, enable):
return rc, stdout, stderr return rc, stdout, stderr
argfile = sys.argv[1] def main():
args = open(argfile, 'r').read() module = AnsibleModule(
items = shlex.split(args) argument_spec = dict(
syslog.openlog('ansible-%s' % os.path.basename(__file__)) name = dict(required=True),
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args) state = dict(choices=['running', 'started', 'stopped', 'restarted', 'reloaded']),
list_items = dict(choices=['status']),
if not len(items): enable = dict(choices=['on', 'off', 'true', 'false', 'yes', 'no', 'enable', 'disable', 'none'])
fail_json(dict(failed=True, msg='this module requires arguments (-a)')) )
)
params = {}
for arg in items: p = module.params
if "=" not in arg: name = p['name']
fail_json(dict(failed=True, msg='expected key=value format arguments')) state = p.get('state', None)
list_items = p.get('list_items', None)
(name, value) = arg.split("=") enable = p.get('enable', None)
params[name] = value
# ===========================================
name = params.get('name', None) # find binaries locations on minion
_find_binaries(module)
if name is None:
fail_json(dict(failed=True, msg='missing name'))
state = params.get('state', None)
list_items = params.get('list', None)
enable = params.get('enabled', params.get('enable', None))
# running and started are the same
if state and state.lower() not in [ 'running', 'started', 'stopped', 'restarted','reloaded' ]:
fail_json(dict(failed=True, msg='invalid value for state'))
if list_items and list_items.lower() not in [ 'status' ]:
fail_json(dict(failed=True, msg='invalid value for list'))
if enable and enable.lower() not in [ 'on', 'off', 'true', 'false', 'yes', 'no', 'enable', 'disable' ]:
fail_json(dict(failed=True, msg='invalid value for enable'))
# ===========================================
# get service status
running = _get_service_status(name)
# =========================================== # ===========================================
# find binaries locations on minion # Some common variables
_find_binaries() changed = False
# ===========================================
# get service status
running = _get_service_status(name)
if state or enable:
rc = 0 rc = 0
out = ''
err = '' err = ''
changed = False out = ''
if enable: if enable:
rc_enable, out_enable, err_enable = _do_enable(name, enable) rc_enable, out_enable, err_enable = _do_enable(name, enable)
rc += rc_enable rc += rc_enable
@ -203,30 +164,24 @@ if state or enable:
err += err_enable err += err_enable
if state and running == None: if state and running == None:
print json.dumps({ module.fail_json(msg="failed determining the current service state => state stays unchanged", changed=False)
"failed" : True,
"msg" : "failed determining the current service state => state stays unchanged",
"changed": False
})
sys.exit(1)
elif state: elif state:
# a state change command has been requested # a state change command has been requested
# =========================================== # ===========================================
# determine if we are going to change anything # determine if we are going to change anything
if not running and state in ["started", "running"]:
if not running and state in ("started", "running"):
changed = True changed = True
elif running and state in ("stopped","reloaded"): elif running and state in ["stopped","reloaded"]:
changed = True changed = True
elif state == "restarted": elif state == "restarted":
changed = True changed = True
# =========================================== # ===========================================
# run change commands if we need to # run change commands if we need to
if changed: if changed:
if state in ('started', 'running'): if state in ['started', 'running']:
rc_state, stdout, stderr = _run("%s %s start" % (SERVICE, name)) rc_state, stdout, stderr = _run("%s %s start" % (SERVICE, name))
elif state == 'stopped': elif state == 'stopped':
rc_state, stdout, stderr = _run("%s %s stop" % (SERVICE, name)) rc_state, stdout, stderr = _run("%s %s stop" % (SERVICE, name))
@ -244,27 +199,17 @@ if state or enable:
rc = rc + rc_state rc = rc + rc_state
if rc != 0: if rc != 0:
module.fail_json(msg=err)
print json.dumps({
"failed" : True,
"rc" : rc,
})
sys.exit(1)
# ===============================================
# success
result = {"changed": changed} result = {"changed": changed}
rc, stdout, stderr = _run("%s %s status" % (SERVICE, name)) rc, stdout, stderr = _run("%s %s status" % (SERVICE, name))
if list_items and list_items in [ 'status' ]: if list_items == 'status':
result['status'] = stdout result['status'] = stdout
print json.dumps(result) module.exit_json(**result);
else:
print json.dumps(dict(failed=True, msg="expected state or list parameters"))
# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
sys.exit(0) main()

Loading…
Cancel
Save