1

What I'm looking for is a task (or tasks) to read whatever .yml files exist in a specified folder and combine them into a file containing all the variables. For example:

pets/steves_pets.yml:

cats:
  - spot
  - snowy
hamsters:
  - mephistopheles

And

pets/jacks-pets.yml:

dogs:
  - rex
  - woof
hamsters:
  - prometheus

Becomes

wherever/all-pets.yml:

cats:
  - spot
  - snowy
dogs:
  - rex
  - woof
hamsters:
  - mephistopheles
  - prometheus

In fact it's not even necessary to generate an all-pets.yml - as long as the full combined list is available to Ansible for use in roles / tasks. But a combined list file approach would be fine if easier.

Any pointers would be greatly appreciated!

2 Answers 2

0

Sounds like you want the combine filter.

You could read each file into a specific variable, then use the combine filter to create all-pets. At that point, it would be in memory of course, so you might want to use the answer to this question to write it to a file:

- name: Read vars
  include_vars:
    file: "pets/{{ item }}_pets.yml"
    var: "{{ item }}"
  loop:
    - steves
    - jacks

- name: Combine vars
  set_fact:
    all_pets: {{ steves | combine(jacks) }}


- name: Write the file
  copy:
    content: "{{ all_pets | to_yaml }}"
    dest: pets/all_pets.yml
6
  • Many thanks for this but the folder could actually contain a large number of files so can't really type out each - ideally it should just load every file in the folder.
    – Sam
    Jul 31, 2019 at 7:21
  • 1
    In that case you can use a fileglob in the include_vars but the same strategy should hold for combining the cars. However if there are so many files, perhaps a vars plugin should be considered for combining them efficiently. It's a cost benefit trade-off Jul 31, 2019 at 7:25
  • Thanks Bruce, think I've got it (maybe) for with_fileglob in the first task and the third looks straightforward enough, but how do I use the combine bit if not specifying steves etc?
    – Sam
    Jul 31, 2019 at 9:33
  • You should be able to use loop control to reference the individual vars during the loop - docs.ansible.com/ansible/latest/user_guide/… Jul 31, 2019 at 9:47
  • 1
    In this particular case, you might be able to obtain what you want using hash_behavior=merge in ansible.cfg Dec 29, 2019 at 10:57
0

I think you can just include_vars at directory level with dir

tasks:
  - name: "Read my pets from pets folder"
    include_vars:
      dir: "pets"
      name: all_pets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.