var/fact validation

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?