client

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 12, 2026 License: MPL-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package client provides configured HCP Terraform API clients and raw request helpers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FetchLog

func FetchLog(logURL string) (string, error)

FetchLog fetches the raw log content from an archivist log-read-url. The URL is self-authenticating so no additional auth headers are needed.

func IsResolvableSegment

func IsResolvableSegment(segment string) bool

IsResolvableSegment returns true if the segment is a resource type that supports name-to-ID resolution via the API.

func LooksLikeID

func LooksLikeID(segment, value string) bool

LooksLikeID returns true if the value already appears to be an ID for the given resource segment, based on known prefixes.

func NewVar

func NewVar(key, value, category string, sensitive bool) *models.VarsEnvelope

NewVar creates a new models.VarsEnvelope for creating a variable from parameters.

func NewVarset

func NewVarset(variableSetName string) *models.VarsetsEnvelope

NewVarset creates a new models.VarsetsEnvelope for creating a variable set from parameters.

func ParsePathParams

func ParsePathParams(path string) map[string]string

ParsePathParams returns a map of param names to their preceding path segments. For example, "/workspaces/{workspace_id}/runs" returns {"workspace_id": "workspaces"}.

func ResolvePathParams

func ResolvePathParams(path string, params map[string]string) (string, error)

ResolvePathParams replaces all {param} placeholders in a URL path with values from the params map. Any unresolved params are returned as an error.

func ResolveURL

func ResolveURL(base url.URL, path string) (*url.URL, error)

ResolveURL resolves an absolute or base-relative API path against base. Query parameters and fragments in path are preserved.

func SummarizeAPIErrors

func SummarizeAPIErrors(body []byte) string

SummarizeAPIErrors attempts to extract meaningful error messages from typical API error responses.

Types

type Client

type Client struct {
	// TFE is the underlying go-tfe client.
	TFE *tfe.Client
	// HTTP is the shared HTTP client used for raw requests.
	Adapter *tfe.TFERequestAdapter
	// BaseURL is the resolved API base URL.
	BaseURL *url.URL
	// DefaultHeaders are applied to every request.
	DefaultHeaders http.Header
}

Client wraps the configured HCP Terraform API clients and request helpers.

func New

func New(ctx context.Context, address, token string, defaultHeaders http.Header) (*Client, error)

New constructs a configured API client from an API address and token. If logger is non-nil, retry attempts are logged at debug level.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *Request) (*http.Response, error)

Do sends a low-level request and returns the response. It is the callers responsibility to close the response body.

func (*Client) SetLogger

func (c *Client) SetLogger(logger hclog.Logger)

SetLogger wraps the HTTP transport to log all requests and responses at the debug level.

func (*Client) SetTelemetry

func (c *Client) SetTelemetry(tel *telemetry.Telemetry)

SetTelemetry wraps the HTTP transport to emit network telemetry about outgoing requests.

type Diagnostic

type Diagnostic struct {
	Severity string             `json:"severity"`
	Summary  string             `json:"summary"`
	Detail   string             `json:"detail"`
	Address  string             `json:"address,omitempty"`
	Range    *DiagnosticRange   `json:"range,omitempty"`
	Snippet  *DiagnosticSnippet `json:"snippet,omitempty"`
}

Diagnostic represents a Terraform diagnostic message.

func ParseDiagnostics

func ParseDiagnostics(logContent string) []Diagnostic

ParseDiagnostics attempts to extract diagnostics from log output. It detects structured logs (JSON lines after the first 3 lines) and parses them.

type DiagnosticRange

type DiagnosticRange struct {
	Filename string         `json:"filename"`
	Start    SourceLocation `json:"start"`
	End      SourceLocation `json:"end"`
}

DiagnosticRange represents the source location of a diagnostic.

type DiagnosticSnippet

type DiagnosticSnippet struct {
	Context              *string `json:"context"`
	Code                 string  `json:"code"`
	StartLine            int     `json:"start_line"`
	HighlightStartOffset int     `json:"highlight_start_offset"`
	HighlightEndOffset   int     `json:"highlight_end_offset"`
}

DiagnosticSnippet contains the source code context for a diagnostic.

type PolicyEvalResult

type PolicyEvalResult struct {
	PolicyKind    string          `json:"policy_kind"` // "opa" or "sentinel"
	Status        string          `json:"status"`
	PolicySetName string          `json:"policy_set_name"`
	Outcomes      []PolicyOutcome `json:"outcomes,omitempty"`
	Error         string          `json:"error,omitempty"`
}

PolicyEvalResult holds the outcome of a policy evaluation (OPA/Sentinel via task stages).

type PolicyOutcome

type PolicyOutcome struct {
	PolicyName       string   `json:"policy_name"`
	EnforcementLevel string   `json:"enforcement_level"` // "advisory", "mandatory", "hard-mandatory", "soft-mandatory"
	Status           string   `json:"status"`            // "passed", "failed"
	Description      string   `json:"description,omitempty"`
	Output           []string `json:"output,omitempty"` // denial reason strings
}

PolicyOutcome represents a single policy's result within a policy set.

type Request

type Request struct {
	// Method is the HTTP method to use.
	Method string
	// URL is the fully resolved request URL.
	URL *url.URL
	// Headers are additional HTTP headers for the request.
	Headers http.Header
	// Body is the raw request payload.
	Body []byte
}

Request describes a raw HTTP request to send to the API.

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

Resolver abstracts helpers for resolving resources by name, with options for creating the the resource if it does not exist.

func NewResolver

func NewResolver(client *Client, createIfNotFound, dryRun bool) *Resolver

NewResolver creates a new Resolver.

func (Resolver) CurrentRunForWorkspace

func (r Resolver) CurrentRunForWorkspace(ctx context.Context, organization, id string) (string, error)

CurrentRunForWorkspace resolves the current run for a given workspace, which can be identified by either ID or name (with organization).

func (Resolver) Project

func (r Resolver) Project(ctx context.Context, organization, name string) (*string, error)

Project resolves a project by organization + name.

func (Resolver) ResolveFromName

func (r Resolver) ResolveFromName(ctx context.Context, resourceType, org, name string) (*string, error)

ResolveFromName resolves a resource ID from a name, based on the resource type. If the resource type is not recognized, the name is returned as-is.

func (Resolver) RunOrCurrentRun

func (r Resolver) RunOrCurrentRun(ctx context.Context, organization, resourceType, id string) (string, error)

RunOrCurrentRun resolves a run ID. If resourceType is "runs", id is returned directly. If resourceType is "workspaces", id is treated as a workspace ID or name and the current run is returned.

func (Resolver) Team

func (r Resolver) Team(ctx context.Context, organization, name string) (*string, error)

Team resolves a team by organization + name.

func (Resolver) VariableSet

func (r Resolver) VariableSet(ctx context.Context, organization, name string) (*string, error)

VariableSet resolves a variable set by organization + name.

func (Resolver) Workspace

func (r Resolver) Workspace(ctx context.Context, organization, name string) (*models.Workspaces, error)

Workspace resolves a workspace ID by name and organization.

type RunSummary

type RunSummary struct {
	RunID             string             `json:"run_id"`
	Status            string             `json:"status"`
	Message           string             `json:"message"`
	Phase             string             `json:"phase,omitempty"`
	Diagnostics       []Diagnostic       `json:"diagnostics,omitempty"`
	RawLog            string             `json:"raw_log,omitempty"`
	PolicyCheckLog    string             `json:"policy_check_log,omitempty"`
	PolicyCheckScope  string             `json:"policy_check_scope,omitempty"`  // "organization" or "workspace"
	PolicyCheckStatus string             `json:"policy_check_status,omitempty"` // "hard_failed", "soft_failed", "errored"
	PolicyEvaluations []PolicyEvalResult `json:"policy_evaluations,omitempty"`
	TaskResults       []TaskResult       `json:"task_results,omitempty"`
}

RunSummary is the result of inspecting a Terraform Cloud run.

func NewRunSummary

func NewRunSummary(ctx context.Context, c *Client, runID string) (*RunSummary, error)

NewRunSummary fetches a run and returns a summary of its status. If the run has errored, it fetches the relevant log and extracts diagnostics. Additionally, it probes policy checks and run task stages for failures. All failures are surfaced in the RunSummary result.

type SourceLocation

type SourceLocation struct {
	Line   int `json:"line"`
	Column int `json:"column"`
	Byte   int `json:"byte"`
}

SourceLocation represents a position in a source file.

type TaskResult

type TaskResult struct {
	TaskName         string `json:"task_name"`
	Status           string `json:"status"`
	Message          string `json:"message,omitempty"`
	URL              string `json:"url,omitempty"`
	EnforcementLevel string `json:"enforcement_level"` // "advisory" or "mandatory"
	Stage            string `json:"stage"`             // "pre_plan", "post_plan", "pre_apply", "post_apply"
}

TaskResult holds the outcome of a run task.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL