Get EC2 public IP

Hello,

I’ve run into a situation where I need to define a variable of EC2 public IPs so I can pass them into my cassandra nodes as seeds.

The problem being, I don’t know a good way to get the public IPs. I currently use static inventory (blank, just for groups) and dynamic inventory (ec2.py).

So Ideally, I’d be able to do something like

cassandra_seeds: “{{ hostvars[groups[‘tag_service_az_cassandra-a’][ansible_ec2_public_ipv4] }}”

however, this doesn’t work. ‘ansible_ec2_public_ipv4’ is only present when ec2_facts has been run. ec2_facts can only be run on the instance ansible is currently provisioning and I need the cassandra_seeds variable across all my cassandra instances.

Another idea was:

cassandra_seeds: “{% for host in groups[‘tag_service_az_cassandra-a’] %} {{hostvars[host].ansible_ec2_public_ipv4 }} {% end for %}”

Again, this falls apart because ansible_ec2_public_ipv4 isn’t present. None of the ansible_ facts gathered have the public ip, only ec2_facts has it.

I realize I could change ec2.ini to return public ip for vpc instances, but that would break all of my other plays… I need private ips everywhere else, this is the only instance where I need to use public ips.

The only potential solution I have figured out would be to write a record to route53 for this express purpose of recording the public ip, but that seems like a failure on using ansible correctly.

This seems like it should be really easy, What am I missing?

Instead of modifying ec2_facts, perhaps you want to modify the ec2
dynamic inventory plugin to return the information you need?

-Toshio

While I agree, that does sound like an idea, the problem with it is that I need both, the private IP and public IP. The public IP is used on each node for broadcast_address, the private IP is used on each node for listen_address. In addition, each node needs a variable passed to it: cassandra_seeds
Cassandra_seeds is a list of public IPs in the form of ,,.

While it would be trivial to change the vpc_destination_variable to ip_address, then i wouldn’t be able to use the private IPs everywhere I need them.

Perhaps if I used two copies of the EC2 dynamic inventory script? is that even possible?

It is possible by specifying a directory as your inventory and then
placing both inventory scripts into the directory.

However, I was thinking that you could modify the script to return
both the public and the private IP in separate fields. Is that not
possible?

The script should be able to even build up the cassandra_seeds
variable for you and return it in, for instance, a group variable for
the hosts that need to have the seed set so that you don't have to do
as much work with jinja filters to build up the variable inside of
your playbook.

-Toshio "ec2 newbie" Kuratomi