Debugging an ansible module

Debugging an ansible module can be a pretty thankless task; luckily the team has provided some tools to make it a little easier. While it’s possible to attach a debugger (e.g. epdb), good old fashioned println debugging is normally enough.

If you just add a print statement to the module, and run it normally, then you’ll be disappointed to see that your output is nowhere to be seen. This is due to the way that ansible modules communicate, using stdin & stdout.

The secret is to run your module using the test-module script provided by the ansible team. You can then pass in the arguments to your module as a json blob:

hacking/test-module -m library/cloud/rax -a "{ \"credentials\": \"~/.rackspace_cloud_credentials\", \"region\": \"LON\", \"name\": \"app-prod-LON-%02d\", \"count\": \"2\", \"exact_count\": \"yes\", \"group\": \"app_servers\", \"flavor\": \"performance1-1\", \"image\": \"11b0cefc-d4ec-4f09-9ff6-f842ca97987c\", \"state\": \"present\", \"wait\": \"yes\", \"wait_timeout\": \"900\" }"

The output of this script can be a bit verbose, so if you’re only interested in your output it can be worthwhile commenting out the code that prints out the parsed output, and just keeping the raw version.

Adding instances to multiple host groups using the Ansible rax module

We use the Ansible rax module to create new instances of our “cloud servers”. It’s pretty easy to add them to one group:

- name: Build a Cloud Server
  tasks:
      local_action:
        module: rax
        name: rax-test1
        wait: yes
        state: present
        networks:
          - private
          - public
        group: app-servers

But it’s also quite handy to be able to place a server in multiple groups (e.g. test / production, different regions etc). There’s nothing in the documentation about this, but a bit of code spelunking reveals that a metadata key named “groups” can contain a comma-separated list of extra host groups:

- name: Build a Cloud Server
  tasks:
      local_action:
        module: rax
        name: rax-test1
        wait: yes
        state: present
        networks:
          - private
          - public
        group: app-servers
        meta:
            groups: test, london