ansible 2.4 api and the all.yml file

Hi,

I’m using ansible 2.4.1 to run a couple of playbooks behind a text UI. At the time the script starts, group_vars/all.yml doesn’t exist - I run a dynamic playbook within the script to gather some facts to define the all.yml.

My problem is that within the same script, once the all.yml is created I attempt a static playbook, but am finding that because all.yml didn’t exist when the main ansible modules were imported the contents of the all.yml I created are ignored.

Is there a way to update the vars to include the new all.yml, so the 2nd playbook will have access to them?

I tried adding them to the variablemanager instance via extra_vars and even _vars_cache but neither worked.

Any help appreciated!

PC

Some further testing

If I switch the playbook to one that simple dumps all vars on a host, I can see that

  • when I start without any yml files in group_vars, and run my script, the dump on each host contains the vars set by the yml files created by the script…apart from the content in all.yml
  • when I start with all.yml already in place, the dump shows all variables

Is group_vars/all.yml perhaps treated differently?

Have a look here:

http://docs.ansible.com/ansible/latest/meta_module.html

meta: refresh_inventory

is what you need.

Hi,

I’d already tried a InventoryManager instance refresh_inventory call within my code, which didn’t work. I added the meta call to a test playbook, and see the same thing i.e. the vars from all.yml are not present, but the vars from the other group_vars are.

I hit a similar issue a while back and found https://github.com/ansible/ansible/issues/24987 which explains why refresh_inventory doesn’t cover this case.

Based on that, I ended up using include_vars to explicitly include the variables onto the hosts after creating the yml file. E.g.

  • hosts: localhost
    gather_facts: false
    tasks:

use stat module to determine if “{{ inventory_dir }}/group_vars/all.yml” exists

create all.yml when it doesn’t

  • hosts: all
    gather_facts: false
    tasks:
  • include_vars:
    file: “{{ inventory_dir }}/group_vars/all.yml”
    when: hostvars[‘localhost’]… #whatever you registered in the top host so this only happens if all.yml was created

Bit of a hack, but it works. If you set up the when’s properly then it becomes idempotent and safe to include multiple times.

Hope that helps.

Thanks Ed.

Looks like include_vars provides me with a workaround. For my use case, I ‘patch’ the main playbook with the additional include_vars task, run the play, and then remove the patch after the play completes.

Thanks again!