AmazonEC2Client describeInstances() returns zero Reservations in Java

641 views Asked by At

While running "aws ec2 describe-instances" in command line, It gives list of all ec2 Instances but with Java AWS-SDK it's gives zero Reservations. Please see below code snippet,

 AmazonEC2 ec2;
 if (ec2 == null) {
    AWSCredentialsProviderChain credentialsProvider = new 
    AWSCredentialsProviderChain(
        new InstanceProfileCredentialsProvider(),
        new ProfileCredentialsProvider("default"));

      ec2 = new AmazonEC2Client(credentialsProvider);
  }

 for (Reservation reservation : ec2.describeInstances().getReservations()) {
         for (Instance instance : reservation.getInstances()) {
                System.out.println("TAG" + instance.getInstanceId());

      } 
   }

`

2

There are 2 answers

0
guest On

The most likely cause is that it's not looking in the correct region.

Another possibility is that it throws an exception that you don't see. To verify that this is not the case, you need to insert some logging statements. At the very least, one before and after the for loop.

0
Akshay Shinde On

This is the code in Java 8 which I use to describe all instances from all the regions:

    amazonEC2.describeRegions().getRegions().forEach(region -> {
        System.out.println("Region : " + region.getRegionName());

        amazonEC2 = AmazonEC2ClientBuilder.standard().withCredentials(awsprovider).withRegion(region.getRegionName()).build();

        amazonEC2.describeInstances().getReservations().forEach(reservation -> {
            reservation.getInstances().forEach(instance -> {
                System.out.println(instance.getInstanceId());
            });
        });
    });

Thanks, Akshay