I’m about to replace/template a great number of files in them and I’d like to have local backups first
The only requirement is that the files have to be fetched to an already established structure that mimics the inventory:
This task isn't actually using a loop in the Ansible sense. You need to
provide a list to iterate over using with_items: or similar. For a more
detailed explanation, see http://docs.ansible.com/playbooks_loops.html
(it has lots of examples).
That said, I don't know the best way to iterate over the hosts in a
subset of all your groups in quite the way you describe. Perhaps the
examples on the following page will prove helpful:
I'm sorry, my earlier answer was short-sighted. I started thinking about
loops because your Subject said "loop", but you were right to not use an
Ansible loop in the first place—at least not over groups/hosts.
As I understand it, trying to write a single task that loops over groups
and hosts isn't the way to do things in Ansible. One should write a task
that fetches the desired files, and run it against the desired hosts by
using the existing host-selection mechanism, as described in http://docs.ansible.com/intro_patterns.html
So you could do something like:
- name: fetch files from the server
fetch: src={{ item }}
dest=/backup/{{ group_names[0] }}/{{ inventory_hostname }}/{{ item | basename }}
with_items:
- /root/.bash_profile
- /some/other/file
Note that group_names is a list variable that contains the name of all
groups that the current host is in. If your hosts aren't in multiple
groups, this should not matter to you. If they are, then the backups
will be stored only in the directory of the first group by this task.
Let me explain:
There’s another layer of groups in the inventory to define in which datacentre a particular host is.
So in a group like dev-group1 we might have 2 machines in datacentre-A and other 2 hosts in datacentre-B.
In this case I’m not interested in where a box is. I need to refer to it by it’s role. (Not the ansible role, but what it does )
So that is why I had this arbitrary list of groups read from a variable. And that is still what I would need.
I’m thinking to make a play to define those vars and including another one so I can use the “with_items” construct.
If someone has come across something like this before, I would love to hear about it!