Java Get EC2 Private/Public IP and Instance ID

Imagine your have your Java application running on AWS EC2 and you want to get know your EC2 instance ID or EC2 private or public IP directly from your Java code. This may be achieved with AWS Java SDK.

And this is how you do it:

// Getting instance Id
String instanceId = EC2MetadataUtils.getInstanceId();

// Getting EC2 private IP
String privateIP = EC2MetadataUtils.getInstanceInfo().getPrivateIp();

// Getting EC2 public IP
AmazonEC2 awsEC2client = AmazonEC2ClientBuilder.defaultClient();
String publicIP = awsEC2client.describeInstances(new DescribeInstancesRequest()
	                    .withInstanceIds(instanceId))
                        .getReservations()
                        .stream()
                        .map(Reservation::getInstances)
                        .flatMap(List::stream)
                        .findFirst()
                        .map(Instance::getPublicIpAddress)
                        .orElse(null);

 

Please note that this approach requires Java 8 or higher.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.