How would you write a simple custom module?
AdvancedConceptAd-hoc Commands, Modules and Idempotency
Answer
A module is a Python file (any language that outputs JSON works, but Python gets helpers) placed in library/ next to the playbook or inside a collection's plugins/modules/.
#!/usr/bin/python
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(path=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['present', 'absent'])),
supports_check_mode=True)
path = module.params['path']
changed = False # compare current and desired state here
if module.check_mode:
module.exit_json(changed=changed)
# make the change only if needed
module.exit_json(changed=changed, path=path)
if __name__ == '__main__':
main()
Document it with DOCUMENTATION, EXAMPLES and RETURN strings so ansible-doc works, and test with ansible-test sanity. Always check state first so the module is idempotent.
More on Ad-hoc Commands, Modules and Idempotency
What is an ad-hoc command and what is its syntax?BeginnerWhat does `ansible all -m ping` actually test?BeginnerGive practical use cases for ad-hoc commands.IntermediateWhat is the difference between the `command` and `shell` modules?BeginnerCompare `raw`, `command`, `shell` and `script`.IntermediateWhy prefer a dedicated module over `shell`/`command`?Beginner