Typical Test Variable Type

I am using an existing role, and I want to change it to expand its capabilities. Currently, one of the tasks is creating directories. These directories are passed as a variable containing a list of strings for this role, and then repeated in the statement with_items. However, I would prefer to pass a list of form dictionaries, for example. {name: foo, mode: 751}.

So far so good; I can simply edit the role to force this type of input. However, I also want to make it backward compatible with the old format, i.e. Where elements are strings.

Is there a way to check the type of a variable, and then based on this return different values ​​(or perform different tasks)? Perhaps using a Jinja2 filter? I briefly looked at the conditionals mentioned in the manual, but nothing caught my eye that could be used in this situation.

+4
source share
2 answers

You can use default()for backward compatibility.

- file:
    path: "{{ item.name | default(item) }}"
    mode: "{{ item.mode | default(omit) }}"
    state: directory
  with_items: your_list

If it itemhas a property name, use it, otherwise just use the element itself.

, dict. omit , file. , .

:

+4

, . , ( dicts).

- name: create dirs (strings)
  file:
    ...
  with_items: items
  when: string(items[0])

- name: create dirs (dicts)
  file:
    ...
  with_items: items
  when: not string(items[0])
+1

Source: https://habr.com/ru/post/1625364/


All Articles