rpm_q.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # (c) 2015, Tobias Florek <tob@butter.sh>
  4. # Licensed under the terms of the MIT License
  5. from ansible.module_utils.basic import *
  6. DOCUMENTATION = """
  7. ---
  8. module: rpm_q
  9. short_description: Query the RPM database
  10. author: Tobias Florek
  11. options:
  12. name:
  13. description:
  14. - The name of the package to query
  15. required: true
  16. state:
  17. description:
  18. - Whether the package is supposed to be installed or not
  19. choices: [present, absent]
  20. default: present
  21. """
  22. EXAMPLES = """
  23. - rpm_q: name=ansible state=present
  24. - rpm_q: name=ansible state=absent
  25. """
  26. import os
  27. RPM_BINARY = '/bin/rpm'
  28. def main():
  29. """
  30. Checks rpm -q for the named package and returns the installed packages
  31. or None if not installed.
  32. """
  33. module = AnsibleModule(
  34. argument_spec=dict(
  35. name=dict(required=True),
  36. state=dict(default='present', choices=['present', 'absent'])
  37. ),
  38. supports_check_mode=True
  39. )
  40. name = module.params['name']
  41. state = module.params['state']
  42. rc, out, err = module.run_command([RPM_BINARY, '-q', name])
  43. installed = out.rstrip('\n').split('\n')
  44. if rc != 0:
  45. if state == 'present':
  46. module.fail_json(msg="%s is not installed" % name, stdout=out, stderr=err, rc=rc)
  47. else:
  48. module.exit_json(changed=False)
  49. elif state == 'present':
  50. module.exit_json(changed=False, installed_versions=installed)
  51. else:
  52. module.fail_json(msg="%s is installed", installed_versions=installed)
  53. if __name__ == '__main__':
  54. main()