I two groups of hosts: dc1 and dc2. Also combined to a DC group.

I need to pass a list of IP addresses of hosts from a foreign DC to a command. with_items doesn't work here at all.

Should look like this:

somescript -H -H

So there're 2 points: 1. Get list of hosts in group DC excluding ones from host primary group. Not sure if that's possible at all, so the dirty way is to set a remote_dc variable (or array). 2. Let's say we have a list of hosts from p.1: groups[remote_dc]. How to use it as a key fro hostvars[ key ]['ansible_eth1']['ipv4']['address'] and get result as a list?

For now I had to use a very dirty way: I've created a remote_addresses list for each DC group and iterated like this:

command: somescript -H {{ remote_addresses|join(' -H ') }}

So is there a proper way to implement p.1 and p.2 and omit manual creation of the ip addresses list?


The ansible documentation has this example:

A frequently used idiom is walking a group to find all IP addresses in that group:

{% for host in groups['app_servers'] %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}

It does approximately what you want. You can use it like this:

- name: Execute somescript
  command: >
    somescript {% for host in groups['app_servers'] %}
                  -H {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
               {% endfor %}

Now, you also want to exclude the host itself from the list of ip addresses. You can do this by modifying the {% for %} like this:

{% for host in groups['app_servers'] if host != ansible_host %}

Instead of ansible_host, you might need to use ansible_fqdn or ansible_nodename. You must check what works for you.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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