我正在尝试使用RunInstancesRequest获取AWS EC2实例详细信息。为此,我遵循了AWS doc https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-ec2-instances.html。
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.withImageId(imageId).withInstanceType(instanceType).withMinCount(1).withMaxCount(count).withSecurityGroups(securityGroupName);
RunInstancesResult runInstancesResult = amazonEC2.runInstances(runInstancesRequest);
String instance_id = runInstancesResult.getReservation().getReservationId();
//waiting for 2 minute
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.setInstanceIds(Arrays.asList(instance_id));
DescribeInstancesResult describeInstancesResult = amazonEC2.describeInstances(describeInstancesRequest);
for(Reservation reservation : describeInstancesResult.getReservations()){
for(Instance instance : reservation.getInstances()) {
System.out.println(instance.getPublicDnsName());
}
}
在这里,我可以启动并运行AWS EC2实例,但我遇到的问题是我无法使用RunInstancesResult对象获取EC2详细信息。根据AWS文档,似乎instance_id是reservation_id,但我认为并非如此。由于instance_id以"i-"
开头,而reservation_id以"r-"
开头。
如何才能获得使用API创建的仅一个EC2的详细信息?当我将RunInstancesResult
对象作为先前API的输出时因此问题:如何使用RunInstancesRequest获取AWS EC2实例详细信息?
答案 0 :(得分:1)
预订是启动实例的请求。例如,您可以使用一个启动请求来创建两个实例。因此,预留包含多个实例。
如果查看响应对象,您将看到Reservation确实包含多个实例,例如:
{
"OwnerId": "123456789012",
"ReservationId": "r-08626e73c547023b1",
"Groups": [
{
"GroupName": "MySecurityGroup",
"GroupId": "sg-903004f8"
}
],
"Instances": [
{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": null,
"RootDeviceType": "ebs",
"State": {
"Code": 0,
"Name": "pending"
},
"EbsOptimized": false,
"LaunchTime": "2013-07-19T02:42:39.000Z",
"ProductCodes": [],
"StateTransitionReason": null,
"InstanceId": "i-1234567890abcdef0",
"ImageId": "ami-1a2b3c4d",
"PrivateDnsName": null,
"KeyName": "MyKeyPair",
etc.
答案 1 :(得分:0)
AWS doc中创建了一些小混淆。他们将预留ID称为instance_id。更改了我的代码中的以下更改后,能够过滤掉实例:
String instance_id = runInstancesResult.getReservation().getInstances()..get(0).getInstanceId();