Skip to content

Instantly share code, notes, and snippets.

@jonls
Created September 11, 2015 15:16
Show Gist options
  • Save jonls/424c81dc63e266c152a1 to your computer and use it in GitHub Desktop.
Save jonls/424c81dc63e266c152a1 to your computer and use it in GitHub Desktop.
Ansible module for MacPorts select
#!/usr/bin/env python
import pipes
from ansible.module_utils.basic import *
def query_group(module, port_path, group):
rc, out, err = module.run_command('{} select --list {}'.format(
pipes.quote(port_path), pipes.quote(group)))
if rc != 0:
module.fail_json(msg='Failed to query group {}: {}'.format(
group, err.rstrip()))
options = set()
selected = None
for line in out.rstrip().split('\n')[1:]:
fields = line.strip().rsplit(' ', 1)
options.add(fields[0])
if len(fields) == 2 and fields[1] == '(active)':
selected = fields[0]
return options, selected
def change_group(module, port_path, group, version):
rc, out, err = module.run_command('{} select --set {} {}'.format(
pipes.quote(port_path), pipes.quote(group), pipes.quote(version)))
if rc != 0:
module.fail_json(msg='Failed to set {} to {}: {}'.format(
group, version, out.rstrip()))
def main():
module = AnsibleModule(
argument_spec=dict(
group=dict(required=True),
version=dict(required=True)
),
supports_check_mode=True
)
port_path = module.get_bin_path('port', True, ['/opt/local/bin'])
group = module.params['group']
version = module.params['version']
options, selected = query_group(module, port_path, group)
if version not in options:
module.fail_json(
msg='Version {} is not available for {}'.format(version, group),
version=list(options), selected=selected)
if selected != version:
if module.check_mode:
module.exit_json(
changed=True, options=list(options), selected=selected)
change_group(module, port_path, group, version)
module.exit_json(
changed=True, options=list(options), selected=selected)
else:
module.exit_json(
changed=False, options=list(options), selected=selected)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment