timedatectl.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python
  2. '''
  3. timedatectl ansible module
  4. This module supports setting ntp enabled
  5. '''
  6. import subprocess
  7. def do_timedatectl(options=None):
  8. ''' subprocess timedatectl '''
  9. cmd = ['/usr/bin/timedatectl']
  10. if options:
  11. cmd += options.split()
  12. proc = subprocess.Popen(cmd, stdin=None, stdout=subprocess.PIPE)
  13. proc.wait()
  14. return proc.stdout.read()
  15. def main():
  16. ''' Ansible module for timedatectl
  17. '''
  18. module = AnsibleModule(
  19. argument_spec=dict(
  20. #state=dict(default='enabled', type='str'),
  21. ntp=dict(default=True, type='bool'),
  22. ),
  23. #supports_check_mode=True
  24. )
  25. # do something
  26. ntp_enabled = False
  27. results = do_timedatectl()
  28. for line in results.split('\n'):
  29. if 'NTP enabled' in line:
  30. if 'yes' in line:
  31. ntp_enabled = True
  32. ########
  33. # Enable NTP
  34. ########
  35. if module.params['ntp']:
  36. if ntp_enabled:
  37. module.exit_json(changed=False, results="enabled", state="enabled")
  38. # Enable it
  39. # Commands to enable ntp
  40. else:
  41. results = do_timedatectl('set-ntp yes')
  42. module.exit_json(changed=True, results="enabled", state="enabled", cmdout=results)
  43. #########
  44. # Disable NTP
  45. #########
  46. else:
  47. if not ntp_enabled:
  48. module.exit_json(changed=False, results="disabled", state="disabled")
  49. results = do_timedatectl('set-ntp no')
  50. module.exit_json(changed=True, results="disabled", state="disabled")
  51. module.exit_json(failed=True, changed=False, results="Something went wrong", state="unknown")
  52. # Pylint is getting in the way of basic Ansible
  53. # pylint: disable=redefined-builtin,wildcard-import,unused-wildcard-import
  54. from ansible.module_utils.basic import *
  55. main()