0

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());

      } 
   }

`

chank007
  • 240
  • 2
  • 8

2 Answers2

1

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.

guest
  • 11
  • 1
0

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