Host Variables Validation in Ansible

A very important part of any configuration management system, is the validation of the input data provided by the user. Before your deploy changes to your productive systems, you should check that you have no obvious mistakes in your configuration.

Ansible is a great configuration management system, but in the area of data validation it is a a bit lacking, in my opinion. There is the ‘assert’ module, but it becomes soon convulsed if you need to do things a little bit more complex than testing for the existence of a variable.

Fortunately, there is a way to do data validation using python, but it isn’t documented very well. Still, once you get the proper boilerplate, it works nicely.

You need to write a so called ‘action_plugin’, which is a python script that you need to place under ‘action_plugins’ in the same directory where your playbooks reside. For example: ‘action_plugins/validate_xxx.py’:

# action plugin for Ansible 2.x
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
    def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
result['changed'] = False
result['failed'] = False
        # put validation code here... you can for example use
# all this host variables in task_vars, and for example
# compare with task_vars['hostvars'], which contains all
# variables of all hosts
#
# if something is wrong, raise an error as follows:
# result['failed'] = True
# result['msg'] = 'Duplicate IP found: ...'
    return result

You then call the validation in a playbook like this:

tasks:
- name: validate xxx configuration
action: validate_xxx

I have, for example, implemented a validation script that verifies that the host being configured doesn’t have an IP configured also for another host (and it proved very useful :))

I hope this helps you validating your data and avoiding mistakes during deployment. Feedback is welcome, if you have any suggestions on how to implement this better.