Q:

How to know external ip address of ansible client

During deployment needed setup ufw firewall rule: enable access for hosts group servers from inventory. Target host is anazon ec2 instance, but it maybe placed at other provider.
I tried:
- name: Ufw rules
  ufw: rule=allow from_ip={{ hostvars[item]['ansible_eth0']['ipv4']['address'] }}
  with_items: groups['servers']
  notify: 
    - Restart ufw

file hosts:
..
[servers]
server1.site.com
server2.site.com
server3.site.com
..

But host server1.site.com, actually have host_vars:
"ansible_eth0": {
   "active": true, 
   "device": "eth0", 
     "ipv4": {
        "address": "10.x.x.x", 
         ...

Ip address 10.x.x.x, as I understand, is internal amazon network ip address.
If execute ping server1.site.com from outside ec2, I get:
64 bytes from server1.site.com (46.x.x.x): icmp_seq=1 ttl=56 time=49.5 ms
...

Executing ansible server1.site.com -m setup -i hosts | grep 46.x.x.x found nothing.
How to known external ip address of host from inventory group using ansible?
Or how setup ufw firewall using host names from inventory?

A:

I think your best bet is to use the lookup plugin written by @dsedivec (https://github.com/dsedivec/ansible-plugins).
Create a lookup_plugins/ directory at the top directory of your playbook.
Put dns.py in it 
curl https://raw.githubusercontent.com/dsedivec/ansible-plugins/master/lookup_plugins/dns.py > lookup_plugins/dns.py

And use it like so :
- name: Ufw rules
  ufw: rule=allow from_ip={{ lookup('dns', item) }}
  with_items: groups['servers']
  notify: 
    - Restart ufw

Good luck !

