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/’:

# 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:

- 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.

Cloud infrastructure enthousiast, open source developer, technical solution engineer at Google

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store