Build a custom Ansible Module with Python

Posted by

Standard, there are a lot of modules available that are developed by the big active Ansible community. So reinventing the wheel is not always needed. BUT, if you are using Ansible in your organization for all your applications and services you find out soon that only the basic modules are not suitable. One of the biggest reasons is that every environment is different from each other.

Why should I create custom Ansible Modules?

There are a couple of reasons why you prefer making custom modules instead of running a script within a playbook. The biggest one in my opinion is; making your scripts human-readable and bringing it all together in one framework.  Another positive thing is that you can re-use your already created scripts. Creating Ansible modules sounds very difficult but it is not that hard. In the next chapter, i discuss how to create a custom Ansible module in Python.

How to create a custom Python Ansible Module?

It all starts with an empty Python (myModule.py) file which you safe for example on SCM in a folder called library. In the first lines of code, we specify the script type and importing the modules we need to talk with the Ansible Core.

Then add your custom function or class with functions.

Now the Ansible Magic.

  1. Define the def main(): function.
  2. Write down your variables which you want to assign in your playbook, I like the JSON method and loading them together. You can choose what the requirements are for that variable, I added some examples.
  3. Load the JSON Fields with AnsibleModule module we imported earlier.
  4. I like to define my variables again to simplify the vars (which is not necessary).
  5. Then do some stuff with your variables.
  6. Now you can choose how to interpreter the results. Choose when returning changed and failed ones.
  7. Example script below

The Ansible module playbook

When it comes to your playbook it is important to use the same name as your script file name (without .py). The playbook in this example looks like this.

Leave a Reply

Your email address will not be published. Required fields are marked *