如何在aws java sdk中获取新创建的EC2实例的实例引用?

时间:2014-09-19 16:34:13

标签: java amazon-web-services amazon-ec2

假设我有几个正在运行的EC2实例。现在我使用这个java代码启动一个新实例:

RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
        .withInstanceType("m1.small")
        .withImageId("some-ami")
        .withMinCount(1)
        .withMaxCount(1)
        .withKeyName("some-key")
        ;
RunInstancesResult runInstancesResule = ec2.runInstances(runInstancesRequest);

我知道我可以迭代整个实例列表来查找pending实例,但这看起来很愚蠢。有没有更简单的方法来获得对这个新创建的EC2实例的Instance引用?

2 个答案:

答案 0 :(得分:0)

由于RunInstancesRequest一次可以启动多个实例,因此它会存储在List中成功启动的实例。即使只启动了一个实例,您仍然需要从列表中读取它,可以使用runInstancesResule变量访问它。要获取列表中的第一个实例,只需使用以下内容:

Instance myInstance = runInstancesResule.getReservation().getInstances().get(0);

然后,您可以使用各种与实例相关的命令来获取有关该实例的信息(更多信息here)。例如:

String myInstanceID = myInstance.getInstanceId();

修改:

使用DescribeInstancesRequest类可以使用相同的概念检索所有实例,如下所示:

DescribeInstancesRequest describeInstanceRequest = new DescribeInstancesRequest();
DescribeInstancesResult describeInstanceResult = ec2.describeInstances(describeInstanceRequest);
List<Instance> myInstances = describeInstanceResult.getReservation().getInstances();

注意:这还包括已停止但未终止的实例,因此您需要检查实例状态以确定实例是否实际运行。

答案 1 :(得分:0)

我创建了两个方法,将启动一个或多个EC2实例,第二个方法将根据实例ID检索实例:

要求EC2:

public List<Instance> requestEC2(AmazonEC2 amazonEC2, String instanceName, String imageId, String instanceType, String securityGroupName, int count) {
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
        TagSpecification tagSpecification = new TagSpecification();
        tagSpecification.withResourceType(ResourceType.Instance).withTags(new Tag().withKey("Name").withValue(instanceName));
        runInstancesRequest.withImageId(imageId).withInstanceType(instanceType).withMinCount(1).withMaxCount(count).withSecurityGroups(securityGroupName).withTagSpecifications(tagSpecification);
        RunInstancesResult runInstancesResult = amazonEC2.runInstances(runInstancesRequest);
        return runInstancesResult.getReservation().getInstances();
    }

检索EC2:

public List<Instance> getEC2InstanceDetails(AmazonEC2 amazonEC2, List<String> instanceIds){
        List<Instance> instanceList = new ArrayList<>();
        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
        describeInstancesRequest.setInstanceIds(instanceIds);
        DescribeInstancesResult describeInstancesResult = amazonEC2.describeInstances(describeInstancesRequest);
        for(Reservation reservation : describeInstancesResult.getReservations()){
            for(Instance instance : reservation.getInstances()) {
                instanceList.add(instance);
            }
        }
        return instanceList;
    }