I have a very simple question, but I fail to find an answer. Hopefully you can help me out.
In my playbook, I have a lot of conditional tasks. I use the when: test quite often. In some cases the conditional can get quite long and difficult to read. I would like to be able to store a conditional in a variable so that I don’t have to repeat the components of it.
For instance:
tasks:
name: determine stat of /tmp/blip
stat: path=/tmp/blip
register: blip
name: test directory
when: blip.stat.isdir is defined and blip.stat.isdir == true
debug: msg=“/tmp/blip is a directory”
name: create previous link
when: previous.stat.exists and previous.stat.islnk and not (blip.stat.isdir is defined and blip.stat.isdir == true)
debug: msg=“make link to previous directory”
I would like it to look more like
tasks:
name: determine stat of /tmp/blip
stat: path=/tmp/blip
register: blip
name: test directory
when: {{dir_is_there}}
debug: msg=“/tmp/blip is a directory”
name: create previous link
when: {{ previous_link_exists}} and not ({dir_is_there}}
debug: msg=“make link to previous directory”
What is the best way to put parts or complete conditinoals in a variable (or something) to reduce code duplication and to enhance readability? I am sure it is possible in ansible, and I can think of a way to do it, but I am not sure I know all the options to choose the best solution.
vars:
blip_dir: "{{ blip.stat.isdir is defined and blip.stat.isdir == true }}"
not_blip_dir: "{{ not blip_dir }}"
...
when: blip_dir|bool
...
when: previous.stat.exists and previous.stat.islnk and not_blip_dir|bool
my problem is that I want to do this in the tasks/main.yml of a certain role. It seems it is not possible to define vars on the same level as the tasks:
vars:
file: /tmp/zb
link: blip.stat.exists and blip.stat.islink
name: bepaal stat van file {{file}}
stat: path={{file}}
register: blip
name: is exists true?
when: blip.stat.exists
debug: msg=“blip.stat.isdir exists”
Obviously this syntax is not OK (ERROR: vars is not a legal parameter in an Ansible task or handler). Because I want to do this to enhance readability, the only solution I see for now, moving it to the playbook itself, is not much of a good idea.
Is it possible to have var definition in the role file itself in some way?
Hi Brian,
it was not my intention to put vardefs in another file, I like to have related code in the same file not far from each other.
But I will certainly give it a try, just to see how it works. So the definition goes in rolename/vars/main.yml.
Another option I was thinking of is the use of registered variables, that have the advantage that they ‘live’ in the same file, but have the drawback that the conditional has to be rewritten using a shell command.