使用java sdk查找新创建的AWS实例的ID和IP地址?

时间:2012-08-01 12:54:39

标签: java amazon-web-services

我使用aws java sdk创建我的实例,我的函数看起来像这样

private static void createInstance()
            throws AmazonServiceException, AmazonClientException, InterruptedException
    {
     RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
            .withInstanceType("m1.small")
            .withImageId("my_ami")
            .withMinCount(1)
            .withMaxCount(1)
            .withKeyName("my_key")
            ;
    RunInstancesResult runInstances = ec2.runInstances(runInstancesRequest);
    }

找到所有正在运行的实例的IP地址,如下所示:

public static ArrayList<String> findIPs(){

         ArrayList<String> myArr = new ArrayList<String>();

         DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
         List<Reservation> reservations = describeInstancesRequest.getReservations();
         Set<Instance> instances = new HashSet<Instance>();

         for (Reservation reservation : reservations) {
             instances.addAll(reservation.getInstances());
            if(reservation.getInstances().get(0).getPrivateIpAddress()!= null) 
            {


                    myArr.add(reservation.getInstances().get(0).getPrivateIpAddress());


            }


         }
         return myArr;
    }

我想知道最近创建的实例ID和IP地址。有人可以指导我如何找到最近创建的AWS实例的ID和IP地址。谢谢

1 个答案:

答案 0 :(得分:1)

看来你已经90%了......

在Reservation上调用getInstances()会获得所有实例的列表。然后在每个实例上调用getLaunchTime()以获取其启动时间。

这对你有用吗?