我无法弄清楚我是如何做到的:
runInstancesRequest.withImageId("ami-53170b32")
.withInstanceType("t2.micro")
.withMinCount(1)
.withMaxCount(1)
.withKeyName("mac")
.withSecurityGroupIds("sg-49025d2d");
RunInstancesResult runInstancesResult =
amazonEC2Client.runInstances(runInstancesRequest);
到目前为止一切正常。现在我想从最近启动的实例中获取公共IP地址。我怎么能这样做?
我试过了:
runInstancesResult.getReservation().getInstances().get(0).getPublicIpAddress()
但IP始终为空。
答案 0 :(得分:7)
启动实例时,它会进入Pending
状态,但还没有公共IP地址。您需要等待一段时间才能使用。
几秒钟后,使用最初返回的实例ID调用DescribeInstances
,然后解压缩PublicIpAddress
。
这是从AWS Command-Line Interface (CLI):
执行转储的转储$ aws ec2 run-instances --image-id ami-1500742f ...
{
"OwnerId": "123456789012",
"ReservationId": "r-0d8cc4a12a94faba7",
"Groups": [],
"Instances": [
{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "",
"KernelId": "aki-c362fff9",
"State": {
"Code": 0,
"Name": "pending"
},
"EbsOptimized": false,
"LaunchTime": "2016-01-22T21:17:49.000Z",
"PrivateIpAddress": "172.31.12.208",
"ProductCodes": [],
"VpcId": "vpc-7d087014",
"StateTransitionReason": "",
"InstanceId": "i-0afe19e0d061b95b5",
...
}
$ aws ec2 describe-instances --instance-ids i-0afe19e0d061b95b5
{
"Reservations": [
{
"OwnerId": "123456789012",
"ReservationId": "r-0d8cc4a12a94faba7",
"Groups": [],
"Instances": [
{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "ec2-52-62-35-146.ap-southeast-2.compute.amazonaws.com",
"RootDeviceType": "ebs",
"State": {
"Code": 16,
"Name": "running"
},
"EbsOptimized": false,
"LaunchTime": "2016-01-22T21:17:49.000Z",
"PublicIpAddress": "52.62.35.146",
"PrivateIpAddress": "172.31.12.208",
...
}