AWS Code Sample

The AWS Documentation website is getting a new look!
Try it now and let us know what you think. Switch to the new look >>

You can return to the original look by selecting English in the language selector above. demonstrates how to get a description of all EC2 instances associated with an AWS account.

/* * Copyright 2010-2019, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package aws.example.ec2; import; import; import; import; import; import; /** * Describes all EC2 instances associated with an AWS account */ public class DescribeInstances { public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); boolean done = false; DescribeInstancesRequest request = new DescribeInstancesRequest(); while(!done) { DescribeInstancesResult response = ec2.describeInstances(request); for(Reservation reservation : response.getReservations()) { for(Instance instance : reservation.getInstances()) { System.out.printf( "Found instance with id %s, " + "AMI %s, " + "type %s, " + "state %s " + "and monitoring state %s", instance.getInstanceId(), instance.getImageId(), instance.getInstanceType(), instance.getState().getName(), instance.getMonitoring().getState()); } } request.setNextToken(response.getNextToken()); if(response.getNextToken() == null) { done = true; } } } }

Sample Details

Service: ec2

Last tested: 2018-05-22

Author: soo-aws

Type: full-example

On this page: