---
# For Amazon EC2 hosts, use the ec2 fact
- hosts: external-ip:&amazon
  tasks:
    - set_fact: external_hostname="{{ansible_ec2_public_hostname}}"

# For non-EC2 hosts, use a detected external IP address

- hosts: external-ip:!amazon:&apt
  sudo: yes
  tasks:
    - name: Install curl
      apt: name=curl state=present

- hosts: external-ip:!amazon
  tasks:
    - name: get host's external IP address
      command: curl --silent --fail http://169.254.169.254/latest/meta-data/public-ipv4
      register: host_external_ip

    - set_fact: external_hostname="{{host_external_ip.stdout}}"


---
# For Amazon EC2 hosts, use the ec2 fact
- hosts: external-ip:&amazon
  tasks:
    - set_fact: external_hostname="{{ansible_ec2_public_hostname}}"

# For non-EC2 hosts, use a detected external IP address

- hosts: external-ip:!amazon:&apt
  sudo: yes
  tasks:
    - name: Install curl
      apt: name=curl state=present

- hosts: external-ip:!amazon
  tasks:
    - name: get host's external IP address
      # See http://www.commandlinefu.com/commands/view/5427/get-your-external-ip-address
      # for alternatives to this command
      command: curl --silent --fail http://ifconfig.me/ip
      register: host_external_ip

    - set_fact: external_hostname="{{host_external_ip.stdout}}"


Use a more general method to detect external IP address. Existing method only worked for Amazon instances.
Use a more general method to detect external IP address.
Existing method only worked for Amazon instances.
