Search in sources :

Example 1 with InstancesScopedList

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;
    }
}
Also used : InstancesScopedList(com.google.cloud.compute.v1.InstancesScopedList) Instance(com.google.cloud.compute.v1.Instance) AggregatedListPagedResponse(com.google.cloud.compute.v1.InstancesClient.AggregatedListPagedResponse) InstancesClient(com.google.cloud.compute.v1.InstancesClient) AggregatedListInstancesRequest(com.google.cloud.compute.v1.AggregatedListInstancesRequest) Map(java.util.Map)

Aggregations

AggregatedListInstancesRequest (com.google.cloud.compute.v1.AggregatedListInstancesRequest)1 Instance (com.google.cloud.compute.v1.Instance)1 InstancesClient (com.google.cloud.compute.v1.InstancesClient)1 AggregatedListPagedResponse (com.google.cloud.compute.v1.InstancesClient.AggregatedListPagedResponse)1 InstancesScopedList (com.google.cloud.compute.v1.InstancesScopedList)1 Map (java.util.Map)1