or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/cloud.google.com/go/compute@v1.53.0
tile.json

tessl/golang-cloud-google-com--go--compute

tessl install tessl/golang-cloud-google-com--go--compute@1.53.0

Go client library for Google Cloud Compute Engine API providing programmatic access to manage virtual machines, disks, networks, and other compute resources

index.mddocs/

Google Cloud Compute Go Client

The cloud.google.com/go/compute package provides the official Go client library for Google Cloud's Compute Engine API. It offers comprehensive, type-safe access to manage virtual machines, persistent disks, VPC networks, load balancers, and all other Google Compute Engine resources through a RESTful API.

The package includes 109 specialized client types covering every Compute Engine resource, with over 2,669 protocol buffer types for requests and responses, providing complete coverage of the Google Compute Engine API surface.

Package Information

  • Package Name: cloud.google.com/go/compute
  • Package Type: golang
  • Language: Go
  • Installation: go get cloud.google.com/go/compute@v1.53.0

Core Imports

import (
    compute "cloud.google.com/go/compute/apiv1"
    "cloud.google.com/go/compute/apiv1/computepb"
    "cloud.google.com/go/compute/metadata"
)

The package is organized into three main subpackages:

  • apiv1: Stable API with 109 client types for managing GCE resources
  • apiv1/computepb: Protocol buffer types for requests, responses, and resources
  • metadata: Client for accessing instance metadata from within GCE instances

Basic Usage

Creating a Client

All clients follow a consistent creation pattern with RESTful constructors:

import (
    "context"
    compute "cloud.google.com/go/compute/apiv1"
)

ctx := context.Background()
client, err := compute.NewInstancesRESTClient(ctx)
if err != nil {
    // handle error
}
defer client.Close()

Managing Instances

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

// List instances in a zone
listReq := &computepb.ListInstancesRequest{
    Project: "my-project",
    Zone:    "us-central1-a",
}
it := client.List(ctx, listReq)
for {
    instance, err := it.Next()
    if err == iterator.Done {
        break
    }
    if err != nil {
        // handle error
    }
    // process instance
}

// Get a specific instance
getReq := &computepb.GetInstanceRequest{
    Project:  "my-project",
    Zone:     "us-central1-a",
    Instance: "my-instance",
}
instance, err := client.Get(ctx, getReq)

// Start an instance
startReq := &computepb.StartInstanceRequest{
    Project:  "my-project",
    Zone:     "us-central1-a",
    Instance: "my-instance",
}
op, err := client.Start(ctx, startReq)
if err != nil {
    // handle error
}
// Wait for operation to complete
err = op.Wait(ctx)

Accessing Instance Metadata

From within a GCE instance, access metadata using the metadata package:

import "cloud.google.com/go/compute/metadata"

if metadata.OnGCE() {
    projectID, err := metadata.ProjectID()
    zone, err := metadata.Zone()
    instanceName, err := metadata.InstanceName()
    internalIP, err := metadata.InternalIP()
}

Package-Level Functions

// DefaultAuthScopes returns the default OAuth2 scopes for Compute API
func DefaultAuthScopes() []string

Capabilities

Instance Management

Comprehensive control over virtual machine instances including creation, lifecycle management, disk attachment, network configuration, and advanced operations like screenshots and console output.

Key operations: Create, start, stop, reset, suspend/resume instances; manage disks, network interfaces, metadata, labels, and scheduling.

Instances Client Documentation

Disk Management

Manage persistent disks with support for snapshots, resizing, replication, and resource policies.

Key operations: Create, resize, snapshot, and manage disk lifecycle; configure async replication; apply resource policies.

Disks Client Documentation

Network Management

Configure VPC networks, subnets, firewall rules, routes, and Cloud Router instances for comprehensive network topology control.

Key operations: Create VPC networks and subnets; configure VPC peering; manage firewall rules; set up custom routes.

Network Clients Documentation

Load Balancing

Configure and manage Google Cloud Load Balancers with support for HTTP(S), SSL/TCP proxies, backend services, health checks, and URL routing.

Key operations: Configure backend services; set up health checks; manage target proxies; define URL maps and routing rules.

Load Balancing Clients Documentation

Storage Resources

Manage VM images, disk snapshots, and storage pools for organizing and optimizing storage resources.

Key operations: Import and manage VM images; create and manage disk snapshots; organize storage in pools.

Storage Clients Documentation

Security

Configure Cloud Armor security policies, SSL certificates, and SSL/TLS policies to protect applications and enforce security standards.

Key operations: Define Cloud Armor rules; manage SSL certificates; configure TLS policies.

Security Clients Documentation

Regional Resources

Access regional versions of compute resources like regional managed instance groups, disks, backend services, and more.

Key operations: Manage region-scoped resources; configure regional high-availability setups.

Regional Clients Documentation

Operations Management

Track and manage long-running operations at global, regional, and zonal scopes.

Key operations: Poll operation status; wait for completion; retrieve operation metadata.

Operations Documentation

Additional Clients

Access to specialized resources including VPN gateways, interconnects, node groups, reservations, packet mirroring, and more.

Coverage: All 109 client types organized by category.

Other Clients Documentation

Protocol Buffer Types

Comprehensive type definitions for all API requests, responses, and resource representations.

Includes: 2,669+ types covering request patterns, resource types, configuration objects, enums, and list responses.

Types Documentation

Metadata Service

Access instance metadata from within GCE instances to retrieve project, instance, network, and service account information.

Key operations: Query instance details, network configuration, SSH keys, service account scopes.

Metadata Package Documentation

Client Patterns

All 109 clients follow consistent patterns:

Constructor Pattern

// Pattern for all clients
func New{ClientName}RESTClient(ctx context.Context, opts ...option.ClientOption) (*{ClientName}, error)

Common Client Methods

type Client interface {
    // Close the client connection
    Close() error

    // Get the gRPC connection (deprecated)
    Connection() *grpc.ClientConn
}

All clients expose a CallOptions field for configuring retry and timeout behavior per method.

Request Type Pattern

All API operations use typed request structs from the computepb package following consistent naming:

  • Get{Resource}Request - Retrieve a single resource
  • List{Resource}sRequest - List resources with pagination
  • AggregatedList{Resource}sRequest - List across zones/regions
  • Insert{Resource}Request - Create a new resource
  • Update{Resource}Request - Full update of a resource
  • Patch{Resource}Request - Partial update of a resource
  • Delete{Resource}Request - Delete a resource
  • {Action}{Resource}Request - Resource-specific actions

Iterator Pattern

List operations return iterators with standard methods:

type Iterator interface {
    // Next returns the next item or iterator.Done when exhausted
    Next() (*Resource, error)

    // PageInfo provides pagination control
    PageInfo() *iterator.PageInfo
}

Operation Pattern

Long-running operations return an Operation handle:

type Operation struct {
    // Check if operation completed
    Done() bool

    // Get operation name/ID
    Name() string

    // Block until operation completes
    Wait(ctx context.Context, opts ...gax.CallOption) error

    // Check operation status without blocking
    Poll(ctx context.Context, opts ...gax.CallOption) error
}

Authentication

Default OAuth2 Scopes

The package provides default authentication scopes:

scopes := compute.DefaultAuthScopes()
// Returns:
// - https://www.googleapis.com/auth/cloud-platform
// - https://www.googleapis.com/auth/compute
// - https://www.googleapis.com/auth/compute.readonly

Client Options

All clients accept option.ClientOption parameters for configuration:

  • Credentials configuration (API keys, service accounts, OAuth2 tokens)
  • Custom API endpoints
  • Custom HTTP/gRPC clients
  • Request/response logging
  • Timeout configuration
  • Custom user agent strings

Example with custom credentials:

import "google.golang.org/api/option"

client, err := compute.NewInstancesRESTClient(ctx,
    option.WithCredentialsFile("/path/to/credentials.json"),
)

Error Handling

All client methods return standard Go errors. Use the status package to extract detailed error information:

import "google.golang.org/grpc/status"

op, err := client.Insert(ctx, req)
if err != nil {
    if st, ok := status.FromError(err); ok {
        // Access error code and message
        code := st.Code()
        msg := st.Message()
    }
}

Beta API

The package includes a beta API version at cloud.google.com/go/compute/apiv1beta with the same structure as the stable API but with access to preview features. Use with caution in production environments as the beta API may have breaking changes.

import computebeta "cloud.google.com/go/compute/apiv1beta"