How to get the public ip of ec2 instance

hii all
I have a script that almost I convert into Ansible playbook. Here is an issue where I want to get the Ansible host (target) public IP address for this in the script we are doing something like this.

IP=$(dig +short myip.opendns.com @resolver1.opendns.com)

cat > /tmp/orgconfig << EOF
MSIP=$(hostname -i)
VHOST_ALIAS=“${IP}:9001”

Optionally configure TLS/SSL for virtual host.

VHOST_SSL=y # Set to “y” to enable TLS/SSL on the virtual host.

KEYSTORE_JAR= # JAR file containing the cert and private key.

KEYSTORE_NAME= # Name of the keystore.

KEYSTORE_ALIAS= # The key alias.

KEY_PASSWORD= # The key password, if it has one.

Specify the analytics group.

AXGROUP=axgroup-001 # Default name is axgroup-001.

EOF
But here the challenge is even I am not able to create variables like

IP=$(dig +short myip.opendns.com @resolver1.opendns.com)
and also not able to find a way to get public IP address I want to use public IP in blockinfile.

Hello @rk23597

You can gather ec2 facts with module ec2_facts and use the fact ansible_ec2_public_ipv4 to get the public IP.

Check the examples in the link below:
https://docs.ansible.com/ansible/2.5/modules/ec2_instance_facts_module.html#return-values
Thanks,
KodeKloud Support