On reboot, the IP address of an amazon instance changes. How to find the new IP address using java API?
Assuming you don't want to assign an Elastic IP address (and there are reasons why this is not always a solution) then simply call DescribeInstances
on the rebooted instance, which returns a bunch of information including Public IP Address.
Here's the AWS EC2 Java API Documentation on the topic.
curl http://169.254.169.254/latest/meta-data/public-ipv4
In order to fetch the public IP of the instance you first need to get the instance id of that instance. You can get the instance id of the instance by using the following java code.
List<Instance> instances = runInstancesResult.getReservation().getInstances();
String instanceId = instances.get(0).toString().substring(13, 23);
And now in order to get the public IP you can use the following java code.
public void fetchInstancePublicIP() {
DescribeInstancesRequest request = new DescribeInstancesRequest().withInstanceIds("i-d99ae7d2");
DescribeInstancesResult result= ec2.describeInstances(request);
List <Reservation> list = result.getReservations();
for (Reservation res:list) {
List <Instance> instanceList= res.getInstances();
for (Instance instance:instanceList){
System.out.println("Public IP :" + instance.getPublicIpAddress());
System.out.println("Public DNS :" + instance.getPublicDnsName());
System.out.println("Instance State :" + instance.getState());
System.out.println("Instance TAGS :" + instance.getTags());
}
}
}
They have util class which facilitates access to EC2 metadata. For instance
EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicHostname();
EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicIPv4s();