0

I'm using Ansible to manage a fleet of dissimilar cloud linux servers. I built a script that pulls backups down to a backup server via rync over ssh. All of the host vars are managed in host_vars/example.com.yml files, each containing the following:

ansible_host: example.com
ansible_user: user
ansible_port: 22
ansible_ssh_private_key_file: "~/.ssh/id_ed25519"

They are grouped in the hosts file like so:

[webservers]
example.com
foo.com
bar.com

[backup]
backupserver.domain.com

I have a backup role for the backup group containing the backupserver.domain.com server comprising the rsync scripts, but I have to manually replicate the ansible host_vars into that backup role to generate an SSH config containing all the information already in the host_vars/*.yml files.

So my question is, within a role is it possible to iterate through the host variables of another host outside of the current host and group? Something like:

{% for item in var_hosts_group %}
Host {{ item.ansible_host }}
   Hostname {{ item.ansible_host }}
   User {{ item.ansible_user }}
   Port {{ item.ansible_port }}
   IdentityFile {{ item.ansible_ssh_private_key_file }}

{% endfor %}

Then an rsync script would be:

{% for item in var_hosts_group %}
rsync -a {{ item.ansible_host }}:/remotebackup /localbackup
{% endfor %}

This would enable me to generate the necessary templates/scripts for the webservers on the backup server and keep everything nice and DRY. Is this possible? Thanks!

1 Answers1

1

Q: "Is it possible to iterate through the host variables of another host outside of the current host and groups?"

(I have changed group/groups. A host can be a member of multiple groups.)

A: Yes. It is possible. hostvars is a dictionary of all hosts and their variables in the play, e.g

{% for item in ansible_play_hosts_all %}
Host {{ hostvars[item]['ansible_host'] }}
   Hostname {{ hostvars[item]['ansible_host'] }}
   User {{ hostvars[item]['ansible_user'] }}
   Port {{ hostvars[item]['ansible_port'] }}
   IdentityFile {{ hostvars[item]['ansible_ssh_private_key_file'] }}
{% endfor %}

"List of all the hosts that were targeted by the play"

  • If a host were not targeted by the play Ansible knows nothing about it, of course.

  • You will very probably want to delegate_to and run_once such a task.

Vladimir Botka
  • 3,791
  • 6
  • 17