List instance templates in a project

Get a list of instance templates defined in a project.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Go API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/api/iterator"
)

// listInstanceTemplates prints a list of InstanceTemplate objects available in a project.
func listInstanceTemplates(w io.Writer, projectID string) error {
	// projectID := "your_project_id"

	ctx := context.Background()
	instanceTemplatesClient, err := compute.NewInstanceTemplatesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstanceTemplatesRESTClient: %w", err)
	}
	defer instanceTemplatesClient.Close()

	req := &computepb.ListInstanceTemplatesRequest{
		Project: projectID,
	}

	it := instanceTemplatesClient.List(ctx, req)
	for {
		instance, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s %s\n", instance.GetName(), instance.GetProperties().GetMachineType())
	}

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Java API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.compute.v1.InstanceTemplate;
import com.google.cloud.compute.v1.InstanceTemplatesClient;
import com.google.cloud.compute.v1.InstanceTemplatesClient.ListPagedResponse;
import java.io.IOException;

public class ListInstanceTemplates {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // projectId: project ID or project number of the Cloud project you use.
    String projectId = "your-project-id";
    listInstanceTemplates(projectId);
  }

  // Get a list of InstanceTemplate objects available in a project.
  public static ListPagedResponse listInstanceTemplates(String projectId) throws IOException {
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {
      int count = 0;
      System.out.println("Listing instance templates...");
      ListPagedResponse templates = instanceTemplatesClient.list(projectId);
      for (InstanceTemplate instanceTemplate : templates.iterateAll()) {
        System.out.printf("%s. %s%n", ++count, instanceTemplate.getName());
      }
      return templates;
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Node.js API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';

const compute = require('@google-cloud/compute');

// Print a list of instance template objects available in a project.
async function listInstanceTemplates() {
  const instanceTemplatesClient = new compute.InstanceTemplatesClient();

  const instanceTemplates = instanceTemplatesClient.listAsync({
    project: projectId,
  });

  for await (const instanceTemplate of instanceTemplates) {
    console.log(` - ${instanceTemplate.name}`);
  }
}

listInstanceTemplates();

Python

Before trying this sample, follow the Python setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Python API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import compute_v1


def list_instance_templates(project_id: str) -> Iterable[compute_v1.InstanceTemplate]:
    """
    Get a list of InstanceTemplate objects available in a project.

    Args:
        project_id: project ID or project number of the Cloud project you use.

    Returns:
        Iterable list of InstanceTemplate objects.
    """
    template_client = compute_v1.InstanceTemplatesClient()
    return template_client.list(project=project_id)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.