# var/fact validation

**URL:** <https://forum.ansible.com/t/var-fact-validation/29876>\
**Category:** Ansible Developer\
**Created:** [March 13, 2019, 8:47pm UTC](https://forum.ansible.com/t/var-fact-validation/29876 "2019-03-13T20:47:00Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Justin\_DynamicD](https://avatars.discourse-cdn.com/v4/letter/j/97f17d/32.png) [@Justin\_DynamicD](https://forum.ansible.com/u/Justin_DynamicD)\
**Post date:** [March 13, 2019, 8:47pm UTC](https://forum.ansible.com/t/var-fact-validation/29876/1 "2019-03-13T20:47:00Z")

</div>

I’ve gotten in a habit of creating a simple dictionary of expected variables when making a role so that it fails early. Something like this:

`

- name: “Validate Variables”  
vars:  
required\_vars:
- name: foo  
msg: “var foo must be defined!”
- name: bar  
msg: “var bar must be defined!”  
fail:  
msg: “{{ item[‘msg’] }}”  
when: vars[item[‘name’]] is undefined  
loop: “{{ required\_vars }}”

`

This works all and well, but I’d like to up my game: include a requirements attribute so that I can also validate the contents. The problem is the when statement. So as an example

`

- name: “Validate Variables”  
vars:  
required\_vars:
- name: foo  
valid: is string  
msg: “var foo must be defined!”
- name: bar  
valid: is integer  
msg: “var bar must be defined!”  
fail:  
msg: “{{ item[‘msg’] }}”  
when:
- vars[item[‘name’]] is undefined
- not (vars[item[‘name’]] vars[item[‘valid’]])  
loop: “{{ required\_vars }}”

`

now we have issues. While I can easily inject a name to check against … the moment I want the check itself to be a variable I have a problem. I could create multiple fail loops for each type of variable, but at that point I’ve build a lot of scaffolding for what should be a simple parameters check.

Is there a better way to validate parameters before the run of a role?
