How to run simple tests against custom Ansible modules

drewmullen profile image drewmullen ・2 min read

Say you're writing a module to ensure a cat.jpg file exists but the out of the box file module isn't cutting it for you! Typically, you'd bring up the documentation and start plugging away at your new, special module! Everytime you hit a major milestone of functionality, you'd write a little playbook using the new module, move over to your CLI and run ansible-playbook cat-module-test.yml

$cat cat-module-test.yml

- hosts: localhost
  connection: local
  gather_facts: false
    - cat_module:
        state: present
        src: cat.jpg
        dest: /tmp

While this DOES work, there are a couple problems:

  1. you are only testing if the module works; you can't see any debug outputs during execution
  2. cannot watch variables during execution
  3. cannot set break points
  4. output is ansible-ized, less friendly to read while testing

Instead, I will show you a new way to easily test this code by passing arguments directly. First we need to make an args file:

$ cat args.json

    "state": "present",
    "src": "cat.jpg",
    "dest": "/tmp"

Test via CLI

Using this args.json file you can easily test without invoking ansible!

python ./cat_module.py args.json

Test via VSCode

Alternatively, you can use an IDE, here's an example of how to use in VSCode

  1. after opening your folder, click the debug menu option on the left pane
  2. create a new debug config and adjust the appropriate stanza in launch.json
    "name": "Python: Terminal (integrated)",
    "type": "python",
    "request": "launch",
    "program": "/home/rmullen/git/library/cat_module/cat_module.py",
    "console": "integratedTerminal",

Press play! (literally, the play button in the debug menu)

With this method, you can now set break points, see print() statements, and step through code the way you would hope when writing python!

Posted on by:

drewmullen profile



Full-stack YAML engineer


markdown guide