DEV Community


Posted on

How to run simple tests against custom Ansible modules

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Test via CLI

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

python ./ 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/",
    "console": "integratedTerminal",
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)