Writing a custom Ansible module

Vincent Bernat

An­si­ble ships a lot of mod­ules you can com­bine for your con­fig­u­ra­tion man­age­ment needs. How­ever, the qual­ity of these mod­ules may vary widely. Some­times, it may be quicker and more ro­bust to write your own mod­ule in­stead of shop­ping and as­sem­bling ex­ist­ing ones.1

In my opin­ion, a ro­bust mod­ule ex­hibits the fol­low­ing char­ac­teristics:

  • idem­potency,
  • diff support,
  • check mode com­pat­ibility,
  • cor­rect change sig­naling, and
  • life­cy­cle man­agement.

In a nut­shell, it means the mod­ule can run with --diff --check and show the changes it would ap­ply. When run twice in a row, the sec­ond run will not ap­ply or sig­nal changes. The last bul­let point sug­gests the mod­ule should be able to delete out­dated ob­jects con­fig­ured dur­ing pre­vi­ous runs.2

The mod­ule code should be min­i­mal and tai­lored to your needs. Mak­ing the mod­ule generic for use by other users is a non-goal. Less code usu­ally means fewer bugs and is eas­ier to un­derstand.

I do not cover test­ing here. It is un­de­ni­ably a good prac­tice, but it re­quires a sig­nif­i­cant ef­fort. In my opin­ion, it is prefer­able to have a well-writ­ten mod­ule match­ing the above char­ac­ter­is­tics rather than a mod­ule that is well tested but with­out them or a mod­ule re­quir­ing fur­ther (untested) as­sem­bly to meet your needs.

Module skeleton#

An­si­ble doc­u­men­ta­tion con­tains in­struc­tions to build a mod­ule, along with some best prac­tices. As one of our non-goals is to dis­trib­ute it, we choose to take some short­cuts and skip some of the boil­er­plate. Let’s as­sume we build a mod­ule with the fol­low­ing signature:

custom_module:
  user: someone
  password: something
  data: "some random string"

There are var­i­ous lo­ca­tions you can put a mod­ule in An­si­ble. A com­mon pos­si­bil­ity is to in­clude it into a role. In a library/ sub­di­rec­tory, cre­ate an empty __init__.py file and a custom_​module.py file with the fol­low­ing code:3

#!/usr/bin/python

import yaml
from ansible.module_utils.basic import AnsibleModule


def main():
    # Define options accepted by the module. ❶
    module_args = dict(
        user=dict(type='str', required=True),
        password=dict(type='str', required=True, no_log=True),
        data=dict(type='str', required=True),
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )

    result = dict(
        changed=False
    )

    got = {}
    wanted = {}

    # Populate both `got` and `wanted`. ❷
    # […]

    if got != wanted:
        result['changed'] = True
        result['diff'] = dict(
            before=yaml.safe_dump(got),
            after=yaml.safe_dump(wanted)
        )

    if module.check_mode or not result['changed']:
        module.exit_json(**result)

    # Apply changes. ❸
    # […]

    module.exit_json(**result)


if __name__ == '__main__':
    main()

The first part, in ❶, de­fines the mod­ule, with the ac­cepted op­tions. Re­fer to the doc­u­men­ta­tion on argument_​spec for more details.

The sec­ond part, in ❷, builds the got and wanted vari­ables. got is the cur­rent state while wanted is the tar­get state. For ex­am­ple, if you need to mod­ify records in a data­base server, got would be the cur­rent rows while wanted would be the mod­i­fied rows. Then, we com­pare got and wanted. If there is a dif­fer­ence, changed is switched to True and we pre­pare the diff ob­ject. An­si­ble uses it to dis­play the dif­fer­ences be­tween the states. If we are run­ning in check mode or if no change is de­tected, we stop here.

The last part, in ❸, ap­plies the changes. Usu­ally, it means it­er­at­ing over the two struc­tures to de­tect the dif­fer­ences and cre­ate the miss­ing items, delete the un­wanted ones and up­date the ex­ist­ing ones.

Documentation#

An­si­ble pro­vides a fairly com­plete page on how to doc­u­ment a mod­ule. I ad­vise you to take a more min­i­mal ap­proach by only doc­u­ment­ing each op­tion spar­ingly,4 skip­ping the ex­am­ples and only doc­u­ment­ing re­turn val­ues if needed. I usu­ally limit my­self to some­thing like this:

DOCUMENTATION = """
---
module: custom_module.py
short_description: Pass provided data to remote service
description:
  - Mention anything useful for your workmate.
  - Also mention anything you want to remember in 6 months.
options:
  user:
    description:
      - user to identify to remote service
  password:
    description:
      - password for authentication to remote service
  data:
    description:
      - data to send to remote service
"""

Error handling#

If you run into an er­ror, you can stop the ex­e­cu­tion with module.​fail_json():

module.fail_json(
    msg=f"remote service answered with {code}: {message}",
    **result
)

There is no re­quire­ment to in­ter­cept all er­rors. Some­times, not swal­low­ing an ex­cep­tion pro­vides bet­ter in­for­ma­tion than re­plac­ing it with a generic message.

Returning additional values#

A mod­ule may re­turn ad­di­tional in­for­ma­tion that can be cap­tured to be used in an­other task through the register di­rec­tive. For this pur­pose, you can add ar­bi­trary fields to the result dic­tio­nary. Have a look at the doc­u­men­ta­tion for com­mon re­turn val­ues. You should try to add these fields be­fore ex­it­ing the mod­ule when in check mode. The re­turned val­ues can be doc­umented.

Examples#

Here are sev­eral ex­am­ples of cus­tom mod­ules fol­low­ing the pre­vi­ous skele­ton. Each ex­am­ple high­lights why a cus­tom mod­ule was writ­ten in­stead of as­sem­bling ex­ist­ing modules. ⚙️