I have done some research (i.e. looking at the sample code posted here Managing Amazon EC2 Instances) but there is only a sample code for getting the Amazon EC2 instances for your account and region.
I tried to modify the sample and here is what I came up with:
private static AmazonEC2 getEc2StandardClient() { // Using StaticCredentialsProvider final String accessKey = "access_key"; final String secretKey = "secret_key"; BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); return AmazonEC2ClientBuilder.standard() .withRegion(Regions.AP_NORTHEAST_1) .withCredentials(new AWSStaticCredentialsProvider(credentials)) .build(); } public static void getInstanceInfo(String instanceId) { final AmazonEC2 ec2 = getEc2StandardClient(); DryRunSupportedRequest<DescribeInstancesRequest> dryRequest = () -> { DescribeInstancesRequest request = new DescribeInstancesRequest() .withInstanceIds(instanceId); return request.getDryRunRequest(); }; DryRunResult<DescribeInstancesRequest> dryResponse = ec2.dryRun(dryRequest); if(!dryResponse.isSuccessful()) { System.out.println("Failed to get information of instance " + instanceId); } DescribeInstancesRequest request = new DescribeInstancesRequest() .withInstanceIds(instanceId); DescribeInstancesResult response = ec2.describeInstances(request); Reservation reservation = response.getReservations().get(0); Instance instance = reservation.getInstances().get(0); System.out.println("Instance id: " + instance.getInstanceId(), ", state: " + instance.getState().getName() + ", public ip: " + instance.getPublicIpAddress() + ", private ip: " + instance.getPrivateIpAddress()); }
It is working fine but I wonder if it's the best practice to get info from a single instance.