Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using with_items inside vars_files in an Ansible playbook

I'm currently making the transition from Puppet to Ansible and so far so good. Yet I want to automatize as much as possible.

I'm trying to use a with_items loop inside vars_files to load variable files based on a given list of items. Ansible complains about the syntax and I can't seem to find an example of a similar solution, only examples that use with_items inside tasks and roles.

For example:

vars_files:
  - ["vars/{{ item }}-{{ ansible_fqdn }}.yml", "vars/{{ item }}-{{ system_environment }}.yml", "vars/{{ item }}.yml"]
    with_items:
      - php
      - nginx

The goal here is to loop the second line for as long as there are items in with_items using an array to fallback on the next item if it can't find the given file (which works).

Not sure if this is at all possible, but I wanted to ask before taking another direction.

like image 727
Sebastiaan Luca Avatar asked Jul 02 '16 13:07

Sebastiaan Luca


1 Answers

with_items, or in general all loops, are a feature of tasks. vars_files though is no task. So it won't work the way you tried it and the short answer would be: It is not possible.

I don't know of a clean way to solve your exact problem. A custom vars plugin might be an option. But vars plugin work on a global level while your vars seem to be used in a role.

A custom lookup plugin might be a solution if solving this on task level is an option for you. The lookup plugin takes your input, checks for presence of the files and returns an array of the files which need to be include. This then can be used with the include_vars module.

- include_vars: "{{ item }}"
  with_my_custom_plugin:
    - php
    - nginx

An ugly solution would be to combine the with_items loop with a with_first_found loop. Though, since you cannot directly nest loops, you need to work with an include.

- include: include_vars.yml
  with_items:
    - php
    - nginx

And inside include_vars.yml you then can use with_first_found with the include_vars module.

- include_vars: "{{ item }}"
  with_first_found:
    - vars/{{ item }}-{{ ansible_fqdn }}.yml
    - vars/{{ item }}-{{ system_environment }}.yml
    - vars/{{ item }}.yml
like image 113
udondan Avatar answered Sep 27 '22 20:09

udondan