Question

I am trying to retrieve all the instances running in my AWS account (say instance id, etc). I use the following code. I am not able to print the instance ids. When I debug, I am just getting null values. But I have three instances running on AWS. Can someone point out what I am doing wrong here?

 DescribeInstancesResult result = ec2.describeInstances();

 List<Reservation> reservations = result.getReservations();

 for (Reservation reservation : reservations) {
      List<Instance> instances = reservation.getInstances();

      for (Instance instance : instances) {
           System.out.println(instance.getInstanceId());
      }
 } 
Was it helpful?

Solution

The most common cause for issues like this is a missing region specification when initializing the client, see section To create and initialize an Amazon EC2 client within Create an Amazon EC2 Client for details:

Specifically, step 2 only creates an EC2 client without specifying the region explicitly:

2) Use the AWSCredentials object to create a new AmazonEC2Client instance, as follows:

amazonEC2Client = new AmazonEC2Client(credentials);

This yields a client talking to us-east-1 - surprisingly, the AWS SDKs and the AWS Management Console use different defaults even as outlined in step 3, which also shows how to specify a different endpoint:

3) By default, the service endpoint is ec2.us-east-1.amazonaws.com. To specify a different endpoint, use the setEndpoint method. For example:

amazonEC2Client.setEndpoint("ec2.us-west-2.amazonaws.com");

The AWS SDK for Java uses US East (N. Virginia) as the default region if you do not specify a region in your code. However, the AWS Management Console uses US West (Oregon) as its default. Therefore, when using the AWS Management Console in conjunction with your development, be sure to specify the same region in both your code and the console. [emphasis mine]

The differing defaults are easy to trip over, and the respective default in the AWS Management Console has in fact changed over time - as so often in software development, I recommend to always be explicit about this in your code to avoid such subtle error sources.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top