How to create a PowerShell module for Ansible

Posted by

In one of my older posts I discussed already how to create a custom Python modules for Ansible which you can read HERE. For PowerShell we can do the same, which is not that hard also. Creating modules is the preferred way when you want to reuse your script for multiple tasks in multiple playbooks or workflows. Another good reason is that your playbooks stay clean and you don’t have to parse output or scripts.

In this example I will create a Veeam Quickbackup PowerShell Ansible module.

A valid PowerShell Ansible module have 2 files:
Python: Veeam_quickbackup.py  <- This file is for documenting the module with examples
PowerShell: Veeam_quickbackup.ps1 <- This file contains the actual functions.

Lets start with the PowerShell file, I will highlight the important things  which you need.

  • Parameters: As you can see I use only one parameter in this example. But you can use as much parameters as you like. In different types for example: list, bool, str etc
  • Module object: Creating a PowerShell module object for storing all the values and outcomes from the script.
  • Fail-Json: If there is any executing exception you can pass this back to Ansible. The command supports returning of the failing object and a message.
  • Messages and results: Another way to interact with the Ansible PowerShell engine is to give the $module object values. As you may know from other playbooks there is a “Changed” state. Changing this in a PowerShell playbook can be done by setting the $module.Result.changed = $true . With the same $module object you can specify the result messages. $module.Result.msg = “Succesfully created the quickbackups”
  • Exit the module: $module.ExitJson()

About the Python file I’ve not much to say. Just follow the Ansible guidelines for documenting custom modules. A important chapter is the example.

One comment

  1. Hello.
    Regarding your tutorial, at least in my computer, both file names need to be lowercase to match the name of the ansible module. Otherwise, I get a “couldn’t resolve module” error.
    This means that they should be named:
    veeam_quickbackup.py
    veeam_quickbackup.ps1

Leave a Reply

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