How to validate ansible variables - any condition you like, with proper error messages

There is a builtin action plugin to validate ansible variables (for the role)
ansible.builtin.validate_argument_spec

But this is sometimes very limited. It is not clear how to add condition like (0 < a, a > 100). It is impossible to add conditions to nested values for dict or list (or I do not know how to do that).

That is why I’ve created capable.core212.validate_vars - action plugin that validates ansible variables.

Main differences:

  • Strict types - int, str and types that allow coercion - str_int, str_bool
  • Custom validation conditions with this keyword
  • mutually_exclusive, required_together, required_one_of, required_if, required_by but for ansible variables (not module arguments)

Let’s start with simpliest example - validate that int value is between 0 and 100

- capable.core212.validate_vars:
    custom_validation_score:
      type: int
      custom_validation:
        - condition: custom_validation_score >= 0 and custom_validation_score <= 100
          error_message: "Score must be between 0 and 100."
  vars:
    custom_validation_score: 85

But what if we have a list of users with score

users:
   - name: alice
     score: 50
   - name: bob
     score: 200

How validate that for all users score is within 0 and 100?

- capable.core212.validate_vars:
    users:
      type: list
      elements:
          type: dict
          options:
              name: 
                 type: str
              score:
                 type: int
                 custom_validation:
                    - condition: this >= 0 and this <= 100
                      error_message: "Score must be between 0 and 100 for all users"
  vars:
    users:
      - name: alice
        score: 50
      - name: bob
        score: 200

Here we validate that users is a list, each element of this list is a dict, and dict has at least name and score attributes, and score for each user is within 0 and 100.
Pay special attention to use of this keyword (only available for this plugin, not generic ansible feature). Using this allow to have validations for nested data (in this case or scores of each users)

There are more features and possible validatation patterns for this plugin. I will followup with them in this topic. So it is not overwhelming to see everything all at once.

PS here is a proper link to documentation
https://capable-core.github.io/collections/capable/core212/modules/validate_vars/