4

When launching new instance in AWS, the public IP address and DNS name is not returned as part of the response.

The machine created has public IP and DNS name assigned, as I can see in the web console, but the response to the SDK method call does not have the IP and DNS field values assigned.

I'm using following code:

output, err := ec2session.RunInstances(input)
...
if output.Instances[0].PublicIpAddress == nil {
    //... that is the case
}

I believe the assignment of the public ip address is somehow delayed, even if I can't notice that using the web console.

How do I obtain the public IP address and DNS name after creating the instance? Is polling DescribeInstances the right method to do it?

4

1 回答 1

1

RunInstances 方法可以在实例创建之前返回,因此尚未分配公网 IP 地址。

要获取地址,我们需要发出一个额外的 Describe... 请求,但不仅如此——我们需要等到实例创建完成。Go AWS 开发工具包中有多种 Wait* 方法用于此目的,它们使用 Descibe* 系列方法进行轮询,直到获得请求的状态。在这种情况下,您可以使用该WaitUntilInstanceExists方法(我使用的是 ..WithContext 版本的方法):

reservation, err := ec2session.RunInstancesWithContext(ctx, input)
if err != nil {
    log.Errorf("error creating instances %v", err)
    return nil, nil, err
}

if !q.needsPublicAddress() {
    return reservation, nil, nil
}

instanceIds := make([]*string, len(reservation.Instances))

for k, v := range reservation.Instances {
    instanceIds[k] = v.InstanceId
}

statusInput := ec2.DescribeInstancesInput{
    InstanceIds: instanceIds,
}

log.Debugf("waiting for instances to exist...")

instanceOkErr := ec2session.WaitUntilInstanceExistsWithContext(ctx, &statusInput)
if instanceOkErr != nil {
    log.Errorf("failed to wait until instances exist: %v", instanceOkErr)
    return nil, nil, instanceOkErr
}

log.Debugf("describing existing instances ...")

description, descriptionErr := ec2session.DescribeInstancesWithContext(ctx, &statusInput)
if descriptionErr  != nil {
    log.Errorf("failed to describe instances: %v", descriptionErr )
    return nil, nil, descriptionErr
}

return reservation, description, nil

在内部,它会发出多次 Describe... 请求,直到实例达到所需状态,然后可以使用 Describe... 请求获取实例状态。响应将包含分配给实例的公共 IP 地址。

于 2018-01-19T21:57:39.663 回答