use of com.google.cloud.compute.v1.InstancesScopedList in project java-docs-samples by GoogleCloudPlatform.
the class ListAllInstances method listAllInstances.
// List all instances in the specified project ID.
public static AggregatedListPagedResponse listAllInstances(String project) throws IOException {
// safely clean up any remaining background resources.
try (InstancesClient instancesClient = InstancesClient.create()) {
// Use the `setMaxResults` parameter to limit the number of results
// that the API returns per response page.
AggregatedListInstancesRequest aggregatedListInstancesRequest = AggregatedListInstancesRequest.newBuilder().setProject(project).setMaxResults(5).build();
InstancesClient.AggregatedListPagedResponse response = instancesClient.aggregatedList(aggregatedListInstancesRequest);
// automatically, requesting next pages as you iterate over the results.
for (Map.Entry<String, InstancesScopedList> zoneInstances : response.iterateAll()) {
// Instances scoped by each zone
String zone = zoneInstances.getKey();
if (!zoneInstances.getValue().getInstancesList().isEmpty()) {
// zoneInstances.getKey() returns the fully qualified address.
// Hence, strip it to get the zone name only
System.out.printf("Instances at %s: ", zone.substring(zone.lastIndexOf('/') + 1));
for (Instance instance : zoneInstances.getValue().getInstancesList()) {
System.out.println(instance.getName());
}
}
}
System.out.println("####### Listing all instances complete #######");
return response;
}
}
Aggregations