go-tfe Go SDK

repository·main·Indexed 42 days ago

https://github.com/hashicorp/go-tfe

The official Go SDK client for HCP Terraform and Terraform Enterprise. It provides a type-safe, path-based interface to interact with the Terraform V2 API, featuring support for request streaming via GetStream, custom HTTP middleware, and comprehensive error handling through the APIError type.

Tokens
5.4K
Snippets
20
Records
26
Agent score
54%

What's inside go-tfe

  1. Understand the Path-based Interface

    main

    The client uses a path-based naming convention for its API surface. Every interface starting with API follows a pattern where you chain path segments followed by the operation method (e.g., Get, Post, Patch, Delete).

    • Unparameterized paths: client.API.Account().Details().Get(ctx, nil) maps to GET /account/details.
    • Parameterized paths: client.API.Organizations().ByOrganization_name("foo").Projects().Post(ctx, body, nil) maps to POST /organizations/{organization_name}/projects.
  2. Build and run the go-tfe CLI examples

    main

    The v2/examples directory contains runnable examples of the SDK client. You can build the example CLI tool using go build. Once built, you can explore available subcommands using the --help flag.

    # Build the example client
    $ go build -o tfe cmd/tfe/main.go
    
    # Explore subcommands
    $ ./tfe account --help
  3. Upgrade from v1 to v2

    main

    The v2 module introduces completely new interfaces. While v1 and v2 can be imported into the same project simultaneously, significant behavioral changes exist:

    • Configuration: The v2 module is no longer sensitive to environment variables. You must configure the client using the NewClient function.
    • Initialization: v2 no longer performs an initial request to decode and store platform configuration.
    • Mocks: v2 does not include up-to-date mocks. If you require mocks for testing, you may need to use the mocks found in the v1 mocks module.

    To upgrade, fetch the v2 module using the following command (replace VERSION with your desired version):

    go get github.com/hashicorp/go-tfe/v2@VERSION
    $ go get github.com/hashicorp/go-tfe/v2@VERSION
  4. Configure environment variables for go-tfe examples

    main

    To run the examples, you must provide authentication and connection details via the following environment variables:

    • TFE_TOKEN: Your HCP Terraform or Terraform Enterprise API token.
    • TFE_ADDRESS: The URL of your Terraform Cloud/Enterprise instance (e.g., https://app.terraform.io).
    $ TFE_TOKEN=example TFE_ADDRESS=https://app.eu.terraform.io ./tfe account details
  5. Inspect Response Headers

    main

    To access HTTP response headers, you must use kiota-http-go to create a HeadersInspectionOptions object and include it in the request's Options slice.

    import (
    	"github.com/microsoft/kiota-abstractions-go"
    	khttp "github.com/microsoft/kiota-http-go"
    )
    
    // 1. Create the HeadersInspectionRequestOption
    inspectionOptions := khttp.NewHeadersInspectionOptions()
    inspectionOptions.InspectResponseHeaders = true
    
    // 2. Add the option to the RequestConfiguration
    req := abstractions.RequestConfiguration[abstractions.DefaultQueryParameters]{
    	Options: []abstractions.RequestOption{inspectionOptions},
    }
    
    // 3. Execute the request
    _, err = client.API.Account().Details().Get(ctx, &req)
    
    // 4. Access the headers
    headers := inspectionOptions.GetResponseHeaders()
    for _, key := range headers.ListKeys() {
    	log.Printf("%s: %v", key, headers.Get(key))
    }
  6. Construct Request Bodies for POST/PATCH operations

    main

    For endpoints that accept a request body, you must construct the appropriate data envelope and parse values for type enums using the provided models package. All operations follow a similar pattern of setting attributes on a data object and wrapping it in an envelope.

    // Example: Creating a variable envelope
    func NewVar(key, value, category string, sensitive bool) *models.VarsEnvelope {
    	hcl := false
    	attrib := &models.Vars_attributes{}
    	attrib.SetKey(&key)
    	attrib.SetValue(&value)
    	attrib.SetSensitive(&sensitive)
    	attrib.SetHcl(&hcl)
    	attrib.SetCategory(mustParseCategory(category))
    
    	data := &models.Vars{}
    	data.SetAttributes(attrib)
    
    	body := &models.VarsEnvelope{}
    	body.SetData(data)
    
    	return body
    }
  7. Access API resources via Client.API and Client.Meta

    main

    The Client struct is the primary entry point and organizes functionality into two main namespaces:

    1. API: An *api.ApiClient used to access the core Terraform Enterprise API resources.
    2. Meta: A Meta struct containing APIs that provide metadata about the TFE instance itself, such as IPRanges and OpenAPI definitions.

    Example structure:

    // Accessing core API
    client.API.Workspaces.Get(...)
    
    // Accessing metadata
    client.Meta.IPRanges.List(...)
  8. Use GetStream for low-memory data retrieval

    main
    While standard API methods in go-tfe return deserialized structs or buffered []byte slices, GetStream bypasses this buffering. It uses the client's configured middleware and authentication to execute the request and returns the raw HTTP response. This allows you to stream data directly from the network to your destination (e.g., a file or a processing pipe) using io.Reader interfaces.
  9. Initialize the TFE client

    main

    Use tfe.NewClient with a *tfe.Config object to initialize the client. At a minimum, you must provide a Token for authentication. The Address defaults to https://app.terraform.io if not specified.

    client, err := tfe.NewClient(&tfe.Config{
    	Token:   os.Getenv("TFE_TOKEN"),
    	Address: os.Getenv("TFE_ADDRESS"),
    })
  10. Use Query Parameters in GET requests

    main

    To add query parameters to a GET request, use the RequestConfiguration type provided by kiota-abstractions-go. Each operation defines its own specific query parameter type based on its path.

    import (
    	"github.com/hashicorp/go-tfe/v2/api/organizations"
    	abstractions "github.com/microsoft/kiota-abstractions-go"
    )
    
    // Include subscriptions in the response by setting the include query parameter
    includeSubscriptions := organizations.SUBSCRIPTION_GETINCLUDEQUERYPARAMETERTYPE
    req := abstractions.RequestConfiguration[organizations.OrganizationsRequestBuilderGetQueryParameters]{
    	QueryParameters: &organizations.OrganizationsRequestBuilderGetQueryParameters{
    		Include: &includeSubscriptions,
    	},
    }
    
    response, err := client.API.Organizations().Get(ctx, &req)
  11. Configure the Client via Config struct

    main

    The Config struct allows you to customize the behavior of the API client. Key configuration options include:

    • Address: The base URL of the Terraform Enterprise API (defaults to https://app.terraform.io).
    • BasePath: The API base path (defaults to /api/v2).
    • Token: The API token required for authentication (mandatory).
    • Headers: Custom http.Header values to be included in every request.
    • RetryRateLimited: Enables automatic retries for rate-limited requests.
    • RetryServerErrors: Enables retry logic for server-side errors.
    • RetryMaxRetries: The maximum number of retry attempts (defaults to 5).
    • RetryHook: A RetryHookCallback function invoked before each retry.
    • HTTPTransport: An optional http.RoundTripper to use as the base transport.