Interview Prep/Ansible/Ad-hoc Commands, Modules and Idempotency

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.

All Ansible questions Roadmap: Ansible

More on Ad-hoc Commands, Modules and Idempotency