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

前端 未结 10 1331
长发绾君心
长发绾君心 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: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 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  list  = result.getReservations();
    
        for (Reservation res:list) {
             List  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());
             }     
        }
    }
    

提交回复
热议问题