conditional_set_fact.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/python
  2. """ Ansible module to help with setting facts conditionally based on other facts """
  3. from ansible.module_utils.basic import AnsibleModule
  4. DOCUMENTATION = '''
  5. ---
  6. module: conditional_set_fact
  7. short_description: This will set a fact if the value is defined
  8. description:
  9. - "To avoid constant set_fact & when conditions for each var we can use this"
  10. author:
  11. - Eric Wolinetz ewolinet@redhat.com
  12. '''
  13. EXAMPLES = '''
  14. - name: Conditionally set fact
  15. conditional_set_fact:
  16. fact1: not_defined_variable
  17. - name: Conditionally set fact
  18. conditional_set_fact:
  19. fact1: not_defined_variable
  20. fact2: defined_variable
  21. - name: Conditionally set fact falling back on default
  22. conditional_set_fact:
  23. fact1: not_defined_var | defined_variable
  24. '''
  25. def run_module():
  26. """ The body of the module, we check if the variable name specified as the value
  27. for the key is defined. If it is then we use that value as for the original key """
  28. module = AnsibleModule(
  29. argument_spec=dict(
  30. facts=dict(type='dict', required=True),
  31. vars=dict(required=False, type='dict', default=[])
  32. ),
  33. supports_check_mode=True
  34. )
  35. local_facts = dict()
  36. is_changed = False
  37. for param in module.params['vars']:
  38. other_vars = module.params['vars'][param].replace(" ", "")
  39. for other_var in other_vars.split('|'):
  40. if other_var in module.params['facts']:
  41. local_facts[param] = module.params['facts'][other_var]
  42. if not is_changed:
  43. is_changed = True
  44. break
  45. return module.exit_json(changed=is_changed, # noqa: F405
  46. ansible_facts=local_facts)
  47. def main():
  48. """ main """
  49. run_module()
  50. if __name__ == '__main__':
  51. main()