简体   繁体   English

如何在Java中获取当前的EC2实例状态

[英]How to get current EC2 instance state in Java

I'm looking for some code that will return the current instance state regardless of whether the instance is currently running or not. 我正在寻找一些将返回当前实例状态的代码,而不管实例当前是否在运行。 I found some code that will return the desired result on a running instance, but when trying to find one that will work on stopped instances, I was overwhelmed by a number of similar looking classes that appeared to perform a similar operation, but in the end, did not work or were poorly documented. 我发现一些代码可以在正在运行的实例上返回期望的结果,但是当试图找到一个可以在停止的实例上运行的代码时,我被许多看起来执行类似操作的类看上去不知所措,但是最后,无法正常工作或记录不良。

Anyway, the running instance version of the code is below: 无论如何,代码的运行实例版本如下:

public Integer getInstanceStatus(String instanceId) {
    DescribeInstanceStatusRequest describeInstanceRequest = new DescribeInstanceStatusRequest().withInstanceIds(instanceId);
    DescribeInstanceStatusResult describeInstanceResult = ec2.describeInstanceStatus(describeInstanceRequest);
    List<InstanceStatus> state = describeInstanceResult.getInstanceStatuses();
    return state.get(0).getInstanceState().getCode();
}

So I'm basically looking for the equivalent that does not have the DescribeInstanceStatus 's restriction that requires the instance to be running. 所以我基本上是在寻找没有DescribeInstanceStatus限制的要求实例正在运行的等效对象。 I'd assume this is possible since the getCode() documentation shows it as being able to return the value 80 which denotes a stopped instance. 我认为这是可能的,因为getCode()文档将其显示为能够返回表示已停止实例的值80。

And once again, I answer my own question... Though I am open to other suggestions. 再一次,我回答自己的问题...尽管我愿意接受其他建议。

public Integer getInstanceStatus(String instanceId) {
    DescribeInstancesRequest describeInstanceRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
    DescribeInstancesResult describeInstanceResult = ec2.describeInstances(describeInstanceRequest);
    InstanceState state = describeInstanceResult.getReservations().get(0).getInstances().get(0).getState();
    return state.getCode();
}

If you set withIncludeAllInstances(true) on your request then you can get states for the not running instances. 如果在请求中设置withIncludeAllInstances(true) ,则可以获取未运行实例的状态。

DescribeInstanceStatusResult result = ec2.describeInstanceStatus(new DescribeInstanceStatusRequest()
                .withInstanceIds(instanceIds).withIncludeAllInstances(true));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM