How to find the IP address of an amazon EC2 instance on reboot

前端 未结 10 1294
长发绾君心
长发绾君心 2020-12-12 13:50

On reboot, the IP address of an amazon instance changes. How to find the new IP address using java API?

相关标签:
10条回答
  • 2020-12-12 14:11

    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.

    0 讨论(0)
  • 2020-12-12 14:13
    curl http://169.254.169.254/latest/meta-data/public-ipv4
    
    0 讨论(0)
  • 2020-12-12 14:16

    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());
             }     
        }
    }
    
    0 讨论(0)
  • 2020-12-12 14:20

    They have util class which facilitates access to EC2 metadata. For instance

    EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicHostname();
    EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicIPv4s();
    
    0 讨论(0)
提交回复
热议问题