Ansible - Role Argument Validation Dict

Viewed 150

I started using the role argument validation which was introduced in Ansible 2.11. For example an easy variable of type string looks like this in meta/argument_specs.yml:

argument_specs:
  main:
    short_description: "Checking firewall global policies"
    options:
      openwrt_firewall_default_forward:
        type: "str"
        choices:
          - "ACCEPT"
          - "REJECT"
          - "DROP"

But I have more complex variables than that, for example dicts. This is what the variables can look like:

openwrt_firewall_zoneshost:
  MGMT:
    forward: "REJECT"
    input: "ACCEPT"
    output: "ACCEPT"
      #log: 1
    interfaces:
      - "mgmt"
  SECURE:
    forward: "ACCEPT"
    input: "ACCEPT"
    output: "ACCEPT"
      #log: 1
    interfaces:
      - "secure"

or like this:

openwrt_firewall_ruleshost:
  "syslog logrx1":
    src: "*"
    dest: "RXFORELLE"
    dest_ip:
      - "{{ hostvars['alsomyhost.mydomain.de']['primary_ip6'] }}"
    dest_port: "514"
    target: "ACCEPT"
  "MGMT myhost":
    src: "MGMT"
    dest: "RXFORELLE"
    dest_ip:
      - "{{ hostvars['myhost.mydomain.de']['primary_ip6'] }}"
    proto: "tcp"
    dest_port: "22"
    target: "ACCEPT"

I would like to be able to validate those, meaning. Some of the attributes are mandatory like src or destination. Some others are optional, but if given I would like to make sure they are of the correct type.

Honestly I don't understand the documentation with reference to this very problem having dict variables. Could someone please outline what the validation structure would look like for those type of variables.

Reference: https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html#role-argument-validation

1 Answers

You can repeat options: in the definition of an option, these are sometimes called "suboptions", and within there you can use all the same fields to define what that dict should contain.

argument_specs:
  main:
    short_description: "Checking firewall global policies"
    options:
      openwrt_firewall_ruleshost:
        type: "dict"
        required: true
        options:
          src:
            required: true
            type: str  
Related