Skip to content

Instantly share code, notes, and snippets.

@vpArth
Last active July 14, 2016 12:38
Show Gist options
  • Save vpArth/7802008f55b86b4ee7179333329ecbde to your computer and use it in GitHub Desktop.
Save vpArth/7802008f55b86b4ee7179333329ecbde to your computer and use it in GitHub Desktop.
Ansible modules
#!/usr/bin/python
import os.path
import re
from subprocess import call
DOCUMENTATION = '''
module: php5mod
short_description: Wraps php5enmod/php5dismod functionality
description:
- The M(php5mod) module check current state of php module and change it if necessary with php5enmod/php5dismod utilities.
author: Alex Deider @vpArth
options:
name:
description:
- php module name
required: true
state:
description:
- Indicates the desired package state.
- C(enabled) ensures that module is enabled.
- C(disabled) ensures that module is disabled.
required: false
choices: [enabled, disabled]
default: enabled
notes:
- Will failed if php_module file is not found
'''
EXAMPLES = '''
# Enable php module
- php5mod: name=mcrypt
- php5mod: name=mcrypt state=enabled
# Disable php module
- php5mod: name=mcrypt state=disabled
'''
def getstate(name):
''' Find out current state '''
module = '/etc/php5/mods-available/'+name+'.ini'
if not os.path.lexists(module):
return 'not_found'
with open(module) as f:
cont = f.read()
f.closed
m = re.search("priority=(\d+)", cont)
priority = 20 if m == None else m.group(1)
conf = '/etc/php5/cli/conf.d/'+priority+'-'+name+'.ini'
state = 'enabled' if os.path.isfile(conf) else 'disabled'
return state
def php5enmod(data):
name = data['name']
call(['php5enmod', name])
def php5dismod(data):
name = data['name']
call(['php5dismod', name])
def main():
fields = {
"name": {"required": True, "type": "str"},
"state": {
"default": "enabled",
"choices": ["enabled", "disabled"],
"type": "str"
}
}
choice_map = {
"enabled": php5enmod,
"disabled": php5dismod,
}
module = AnsibleModule(
argument_spec=fields,
supports_check_mode=True
)
name = module.params['name']
state = module.params['state']
current = getstate(name)
if current == 'not_found':
return module.fail_json(msg="Module `"+name+"` is not found")
changed = current != state
if not module.check_mode:
choice_map.get(state)(module.params)
module.exit_json(changed = changed)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment