Searching for eficient way to check group of variables

Hello,

I recently wrote role, that set up an openvz on centos host, including network configuration. For that purpose, I have variables ip, gateway, netmask, dns1 and dns2 in host_vars/.

Variables are mandatory, I cannot set up networking withnout them, so I`m checking them out. So far I have this code:

- fail: msg="You need to define ip, gateway, netmask, dns1 and dns2 in hosts_vars"
  when: ip is not defined

- fail: msg="You need to define ip, gateway, netmask, dns1 and dns2 in hosts_vars"

  when: gateway is not defined

- fail: msg="You need to define ip, gateway, netmask, dns1 and dns2 in hosts_vars"
  when: netmask is not defined

- fail: msg="You need to define ip, gateway, netmask, dns1 and dns2 in hosts_vars"
  when: dns1 is not defined

- fail: msg="You need to define ip, gateway, netmask, dns1 and dns2 in hosts_vars"

  when: dns2 is not defined

Somehow I think, Im pretty sure, Im missing some nicer way how to do it, is it possible to have it in one fail statement?

Regards
David Karban

In the latest 1.3, you can use the variable in a template like this:

{{ foo | mandatory }}

This will yell when you try to use the variable that is undefined.

You can also globally turn on “all variables must be defined” warnings in ansible.cfg
(see examples/ansible.cfg in the checkout)

Thanks, I will try it out!

Dne 5.7.2013 16:02 “Michael DeHaan” <michael@ansibleworks.com> napsal(a):

My approach:

(1) I use a single role variable that contains keys/value. E.g. for
the "webapp" role, I call it "webapp_args".

(2) Any globally defined variables (e.g. from host_vars), I copy into
a slot in webapp_args on each role invocation

(3) In the role, I check that webapp_args is defined

(4) In the role, I loop over mandatory items that must exist:

Example:

- name: Assert webapp_args
  fail: msg="required webapp_args parameters must be provided"
  when: webapp_args is not defined

- name: Assert required webapp_args parameters
  fail: msg="required webapp_args[{{item}}] must be provided"
  when: webapp_args[item] is not defined
  with_items:
    - app_name
    - app_path
    - app_port
    - ...

I hope someday there's a way to do that more automatically in the way
that roles work, but for now it's working fine for me.

You could probably do it with globals instead of a role argument
structure, but I personally dislike using globals in that way, so I
didn't do that myself.

-- David

Also:

  • fail: msg=variables not defined
    when: foo is not defined or bar is not defined or baz is not defined

should be valid.

Also:

- fail: msg=variables not defined
  when: foo is not defined or bar is not defined or baz is not defined

Hi Michael,

tested, works great, thanks !