Search code examples
amazon-web-servicesaws-sdkamazon-ami

How to obtain the Public IP Address on EC2 launch instance request?


I can't figure it out how I can do it:

runInstancesRequest.withImageId("ami-53170b32")
                .withInstanceType("t2.micro")
                .withMinCount(1)
                .withMaxCount(1)
                .withKeyName("mac")
                .withSecurityGroupIds("sg-49025d2d");

RunInstancesResult runInstancesResult =
                amazonEC2Client.runInstances(runInstancesRequest);

So far everything works fine. Now I want to get the Public IP Address from the recently started instance. How can I do that?

I tried:

runInstancesResult.getReservation().getInstances().get(0).getPublicIpAddress()

but the IP is always null.


Solution

  • When an instance is launched, it enters the Pending state and does not yet have a Public IP address. You will need to wait a little bit for it to be available.

    After a few seconds, call DescribeInstances with the Instance ID originally returned, then extract the PublicIpAddress.

    Here's a dump doing it from the 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", 
    ...
    }