output

package
v1.206.2 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package output provides functionality to format and export Terraform outputs in various formats suitable for CI/CD workflows, scripts, and configuration files.

Index

Constants

View Source
const DefaultFileMode = 0o644

DefaultFileMode is the file mode for output files.

View Source
const DefaultFlattenSeparator = "_"

DefaultFlattenSeparator is the default separator for flattening nested keys.

Variables

ScalarOnlyFormats are formats that only support scalar values (not maps/lists).

View Source
var SupportedFormats = []string{"json", "yaml", "hcl", "env", "dotenv", "bash", "csv", "tsv", "table", "github"}

SupportedFormats lists all supported output formats.

Functions

func ExecuteWithSections

func ExecuteWithSections(
	atmosConfig *schema.AtmosConfiguration,
	component, stack string,
	sections map[string]any,
	authContext *schema.AuthContext,
) (map[string]any, error)

ExecuteWithSections retrieves terraform outputs using pre-loaded sections. This is used when the caller already has sections from describing a component and wants to execute terraform output directly without re-describing.

func FormatOutputs

func FormatOutputs(outputs map[string]any, format Format) (string, error)

FormatOutputs converts terraform outputs map to the specified format.

func FormatOutputsWithOptions

func FormatOutputsWithOptions(outputs map[string]any, format Format, opts FormatOptions) (string, error)

FormatOutputsWithOptions converts terraform outputs map to the specified format with options.

func FormatSingleValue

func FormatSingleValue(key string, value any, format Format) (string, error)

FormatSingleValue formats a single terraform output value. For scalar formats (env, dotenv, bash, csv, tsv), complex values (maps/lists) are not supported. For structured formats (json, yaml, hcl), any value type is supported.

func FormatSingleValueWithOptions

func FormatSingleValueWithOptions(key string, value any, format Format, opts FormatOptions) (string, error)

FormatSingleValueWithOptions formats a single terraform output value with options.

func GetComponentInfo

func GetComponentInfo(component, stack string) string

GetComponentInfo returns a formatted string for logging purposes.

func GetComponentOutputs

func GetComponentOutputs(
	atmosConfig *schema.AtmosConfiguration,
	component string,
	stack string,
	skipInit bool,
	authManager any,
) (map[string]any, error)

GetComponentOutputs retrieves all terraform outputs for a component in a stack. This is used by the --format flag to get all outputs at once for formatting.

Parameters:

  • atmosConfig: Atmos configuration pointer
  • component: Component identifier
  • stack: Stack identifier
  • skipInit: If true, skip terraform init (assumes already initialized)
  • authManager: Optional auth manager for YAML functions that need AWS access (may be nil)

Returns:

  • outputs: Map of all terraform output values
  • error: Any error that occurred during retrieval

func GetComponentOutputsWithExecutor

func GetComponentOutputsWithExecutor(
	exec *Executor,
	atmosConfig *schema.AtmosConfiguration,
	component string,
	stack string,
	skipInit bool,
	authManager any,
) (map[string]any, error)

GetComponentOutputsWithExecutor retrieves all terraform outputs using a specific executor. Use this when you need to provide a custom executor instance.

func GetOutput

func GetOutput(
	atmosConfig *schema.AtmosConfiguration,
	stack string,
	component string,
	output string,
	skipCache bool,
	authContext *schema.AuthContext,
	authManager any,
) (any, bool, error)

GetOutput retrieves a specific terraform output for a component in a stack. This is the main entry point for getting individual outputs, used by YAML functions like !terraform.output.

Parameters:

  • atmosConfig: Atmos configuration pointer
  • stack: Stack identifier
  • component: Component identifier
  • output: Output variable key to retrieve
  • skipCache: Flag to bypass cache lookup
  • authContext: Authentication context for credential access (may be nil)
  • authManager: Optional auth manager for nested operations that need authentication

Returns:

  • value: The output value (may be nil if the output exists but has a null value)
  • exists: Whether the output key exists in the terraform outputs
  • error: Any error that occurred during retrieval

func GetStaticRemoteStateOutput

func GetStaticRemoteStateOutput(
	atmosConfig *schema.AtmosConfiguration,
	component string,
	stack string,
	remoteStateSection map[string]any,
	output string,
) (any, bool, error)

GetStaticRemoteStateOutput extracts a specific output from static remote state. This is exported for use by terraform_state_utils.go and other callers that need to extract values from static remote state sections.

func IsComplexValue

func IsComplexValue(value any) bool

IsComplexValue returns true if the value is a map or slice (not a scalar).

func IsComponentProcessable

func IsComponentProcessable(sections map[string]any) (enabled bool, abstract bool)

IsComponentProcessable determines if a component should be processed for terraform output. Returns (enabled, abstract) flags from the component's metadata and vars sections.

func NewSpinner

func NewSpinner(message string) *tea.Program

NewSpinner creates a tea.Program that displays an animated spinner with the provided message. It applies the current UI spinner style. If stdout lacks TTY support, the program is configured without a renderer and without input; a debug message is logged and the message is written to stderr as a fallback.

func RetryOnWindows

func RetryOnWindows(fn func() error) error

RetryOnWindows is the exported version for use by other packages. On non-Windows platforms, it immediately executes the function.

func RunSpinner

func RunSpinner(p *tea.Program, spinnerChan chan struct{}, message string)

RunSpinner executes the spinner program in a goroutine.

func SetDefaultExecutor

func SetDefaultExecutor(exec *Executor)

SetDefaultExecutor sets the default executor used by package-level functions. This must be called from internal/exec during initialization to break the circular dependency.

func StopSpinner

func StopSpinner(p *tea.Program, spinnerChan chan struct{})

StopSpinner stops the spinner program and waits for the completion.

func ValidateBackendConfig

func ValidateBackendConfig(config *ComponentConfig, component, stack string) error

ValidateBackendConfig validates that backend configuration is complete for backend generation.

func ValidateSingleValueFormat

func ValidateSingleValueFormat(value any, format Format) error

ValidateSingleValueFormat checks if a format supports a single complex value. CSV/TSV formats do not support single complex values (maps/lists).

func WriteToFile

func WriteToFile(filePath string, content string) error

WriteToFile writes content to a file, creating it if it doesn't exist or appending to it if it does.

Types

type BackendGenerator

type BackendGenerator interface {
	// GenerateBackendIfNeeded generates backend.tf.json if auto-generation is enabled.
	GenerateBackendIfNeeded(config *ComponentConfig, component, stack string, authContext *schema.AuthContext) error
	// GenerateProvidersIfNeeded generates providers_override.tf.json if providers are configured.
	GenerateProvidersIfNeeded(config *ComponentConfig, authContext *schema.AuthContext) error
}

BackendGenerator handles backend and provider file generation.

type ComponentConfig

type ComponentConfig struct {
	// Executable is the path to the terraform/opentofu executable.
	Executable string
	// Workspace is the terraform workspace name.
	Workspace string
	// ComponentPath is the path to the component directory.
	ComponentPath string
	// BackendType is the backend type (e.g., "s3", "gcs", "azurerm").
	BackendType string
	// Backend contains the backend configuration.
	Backend map[string]any
	// Providers contains provider overrides.
	Providers map[string]any
	// Env contains environment variables from the component.
	Env map[string]any
	// AutoGenerateBackend indicates whether to auto-generate backend.tf.json.
	AutoGenerateBackend bool
	// InitRunReconfigure indicates whether to run init with -reconfigure.
	InitRunReconfigure bool
}

ComponentConfig holds validated configuration for terraform output execution.

func ExtractComponentConfig

func ExtractComponentConfig(atmosConfig *schema.AtmosConfiguration, sections map[string]any, component, stack string) (*ComponentConfig, error)

ExtractComponentConfig extracts and validates component configuration from sections. Returns an error with appropriate sentinel if required fields are missing. The autoGenerateBackend and initRunReconfigure flags are read directly from atmosConfig.

type ComponentDescriber

type ComponentDescriber interface {
	// DescribeComponent returns the component configuration sections.
	DescribeComponent(params *DescribeComponentParams) (map[string]any, error)
}

ComponentDescriber abstracts component description to break circular dependency with internal/exec.

type DescribeComponentParams

type DescribeComponentParams struct {
	AtmosConfig          *schema.AtmosConfiguration // Optional: Use provided config instead of initializing new one.
	Component            string
	Stack                string
	ProcessTemplates     bool
	ProcessYamlFunctions bool
	Skip                 []string
	AuthManager          any
}

DescribeComponentParams contains parameters for describing a component.

type EnvironmentSetup

type EnvironmentSetup interface {
	// SetupEnvironment prepares environment variables for terraform execution.
	SetupEnvironment(config *ComponentConfig, authContext *schema.AuthContext) (map[string]string, error)
}

EnvironmentSetup handles environment variable configuration for terraform execution.

type Executor

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

Executor orchestrates terraform output retrieval with dependency injection.

func GetDefaultExecutor

func GetDefaultExecutor() *Executor

GetDefaultExecutor returns the default executor, or nil if not set.

func NewExecutor

func NewExecutor(describer ComponentDescriber, opts ...ExecutorOption) *Executor

NewExecutor creates an Executor with the required ComponentDescriber and optional configurations.

func (*Executor) ExecuteWithSections

func (e *Executor) ExecuteWithSections(
	atmosConfig *schema.AtmosConfiguration,
	component, stack string,
	sections map[string]any,
	authContext *schema.AuthContext,
) (map[string]any, error)

ExecuteWithSections retrieves terraform outputs using pre-loaded sections. This is used when the caller already has sections from ExecuteDescribeComponent.

func (*Executor) GetAllOutputs

func (e *Executor) GetAllOutputs(
	atmosConfig *schema.AtmosConfiguration,
	component string,
	stack string,
	skipInit bool,
	authManager any,
) (map[string]any, error)

GetAllOutputs retrieves all terraform outputs for a component in a stack. This is used by the --format flag to get all outputs at once for formatting.

func (*Executor) GetOutput

func (e *Executor) GetOutput(
	atmosConfig *schema.AtmosConfiguration,
	stack string,
	component string,
	output string,
	skipCache bool,
	authContext *schema.AuthContext,
	authManager any,
) (any, bool, error)

GetOutput retrieves a specific terraform output for a component in a stack.

type ExecutorOption

type ExecutorOption func(*Executor)

ExecutorOption configures the Executor.

func WithRunnerFactory

func WithRunnerFactory(factory RunnerFactory) ExecutorOption

WithRunnerFactory sets a custom runner factory (for testing).

func WithStaticRemoteStateGetter

func WithStaticRemoteStateGetter(getter StaticRemoteStateGetter) ExecutorOption

WithStaticRemoteStateGetter sets a custom static remote state getter.

type Format

type Format string

Format represents output format types.

const (
	// FormatJSON outputs as JSON object: {"key": "value"}.
	FormatJSON Format = "json"
	// FormatYAML outputs as YAML: key: value.
	FormatYAML Format = "yaml"
	// FormatHCL outputs as HCL: key = "value".
	FormatHCL Format = "hcl"
	// FormatEnv outputs as env vars: key=value (GitHub Actions style).
	FormatEnv Format = "env"
	// FormatDotenv outputs as dotenv: key='value'.
	FormatDotenv Format = "dotenv"
	// FormatBash outputs as bash exports: export key='value'.
	FormatBash Format = "bash"
	// FormatCSV outputs as CSV: key,value.
	FormatCSV Format = "csv"
	// FormatTSV outputs as TSV: key<tab>value.
	FormatTSV Format = "tsv"
	// FormatTable outputs as a styled table with Key/Value columns.
	FormatTable Format = "table"
	// FormatGitHub outputs for GitHub Actions $GITHUB_OUTPUT file.
	// Uses KEY=value for simple values, heredoc syntax for multiline values.
	FormatGitHub Format = "github"
)

type FormatOptions

type FormatOptions struct {
	// Uppercase converts keys to uppercase (useful for environment variables).
	Uppercase bool
	// Flatten recursively expands nested maps and arrays into flat key/value pairs.
	// For example, {"config": {"host": "localhost"}} becomes {"config_host": "localhost"}.
	// Arrays are flattened with numeric indices: {"hosts": ["a", "b"]} becomes {"hosts_0": "a", "hosts_1": "b"}.
	Flatten bool
	// FlattenSeparator is the separator used when flattening nested keys (default: "_").
	FlattenSeparator string
	// AtmosConfig provides configuration for syntax highlighting and color preferences.
	AtmosConfig *schema.AtmosConfiguration
}

FormatOptions provides options for output formatting.

func (FormatOptions) GetFlattenSeparator

func (o FormatOptions) GetFlattenSeparator() string

GetFlattenSeparator returns the flatten separator, using the default if not set.

type OutputOptions

type OutputOptions struct {
	// QuietMode suppresses terraform init/workspace output (sends to io.Discard).
	// Use this when formatting output for scripts to avoid polluting stdout/stderr.
	// If an error occurs, captured stderr is included in the error message.
	QuietMode bool
}

OutputOptions configures behavior for terraform output retrieval.

type RunnerFactory

type RunnerFactory func(workdir, executable string) (TerraformRunner, error)

RunnerFactory creates TerraformRunner instances.

type StaticRemoteStateGetter

type StaticRemoteStateGetter interface {
	// GetStaticRemoteStateOutputs returns static remote state outputs if configured.
	GetStaticRemoteStateOutputs(sections *map[string]any) map[string]any
}

StaticRemoteStateGetter abstracts static remote state retrieval.

type TerraformRunner

type TerraformRunner interface {
	// Init runs terraform init with the given options.
	Init(ctx context.Context, opts ...tfexec.InitOption) error
	// WorkspaceNew creates a new terraform workspace.
	WorkspaceNew(ctx context.Context, workspace string, opts ...tfexec.WorkspaceNewCmdOption) error
	// WorkspaceSelect selects an existing terraform workspace.
	WorkspaceSelect(ctx context.Context, workspace string) error
	// Output retrieves terraform outputs.
	Output(ctx context.Context, opts ...tfexec.OutputOption) (map[string]tfexec.OutputMeta, error)
	// SetStdout sets the stdout writer.
	SetStdout(w io.Writer)
	// SetStderr sets the stderr writer.
	SetStderr(w io.Writer)
	// SetEnv sets environment variables for terraform commands.
	SetEnv(env map[string]string) error
}

TerraformRunner abstracts terraform-exec operations for testability.

type WorkspaceManager

type WorkspaceManager interface {
	// CleanWorkspace removes the .terraform/environment file to ensure clean workspace state.
	CleanWorkspace(atmosConfig *schema.AtmosConfiguration, componentPath string)
	// EnsureWorkspace creates or selects the specified workspace.
	EnsureWorkspace(ctx context.Context, runner TerraformRunner, workspace, backendType, component, stack string, stderrCapture *quietModeWriter) error
}

WorkspaceManager handles terraform workspace operations.

Jump to

Keyboard shortcuts

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