function

package
v1.203.0-test.7 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2025 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package function provides a format-agnostic function registry for Atmos.

This package implements a plugin-like architecture for YAML/HCL/JSON functions (e.g., !env, !exec, !terraform.output) that can be used across different configuration formats.

The registry pattern allows functions to be registered, looked up by name or alias, and filtered by execution phase (PreMerge or PostMerge).

Example usage:

// Register a function
fn := NewEnvFunction()
function.DefaultRegistry().Register(fn)

// Look up and execute
fn, err := function.DefaultRegistry().Get("env")
result, err := fn.Execute(ctx, "MY_VAR default_value", execCtx)

Index

Constants

View Source
const (
	// TagExec executes a shell command and returns the output.
	TagExec = "exec"

	// TagStore retrieves a value from a configured store.
	TagStore = "store"

	// TagStoreGet retrieves a value from a configured store (alternative syntax).
	TagStoreGet = "store.get"

	// TagTemplate processes a JSON template.
	TagTemplate = "template"

	// TagTerraformOutput retrieves a Terraform output value.
	TagTerraformOutput = "terraform.output"

	// TagTerraformState retrieves a value from Terraform state.
	TagTerraformState = "terraform.state"

	// TagEnv retrieves an environment variable value.
	TagEnv = "env"

	// TagInclude includes content from another file.
	TagInclude = "include"

	// TagIncludeRaw includes raw content from another file.
	TagIncludeRaw = "include.raw"

	// TagRepoRoot returns the git repository root path.
	TagRepoRoot = "repo-root"

	// TagRandom generates a random number.
	TagRandom = "random"

	// TagLiteral preserves values exactly as written, bypassing template processing.
	TagLiteral = "literal"

	// TagAwsAccountID returns the AWS account ID.
	TagAwsAccountID = "aws.account_id"

	// TagAwsCallerIdentityArn returns the AWS caller identity ARN.
	TagAwsCallerIdentityArn = "aws.caller_identity_arn"

	// TagAwsCallerIdentityUserID returns the AWS caller identity user ID.
	TagAwsCallerIdentityUserID = "aws.caller_identity_user_id"

	// TagAwsRegion returns the AWS region.
	TagAwsRegion = "aws.region"
)

Tag constants for Atmos configuration functions. These are the canonical function names used across all formats. In YAML they appear as !tag, in HCL as tag(), etc.

View Source
const YAMLTagPrefix = "!"

YAMLTagPrefix is the prefix used for YAML custom tags.

Variables

View Source
var (
	// ErrFunctionNotFound is returned when a function is not registered.
	ErrFunctionNotFound = errors.New("function not found")

	// ErrFunctionAlreadyRegistered is returned when attempting to register
	// a function with a name or alias that already exists.
	ErrFunctionAlreadyRegistered = errors.New("function already registered")

	// ErrInvalidArguments is returned when a function receives invalid arguments.
	ErrInvalidArguments = errors.New("invalid function arguments")

	// ErrExecutionFailed is returned when a function fails to execute.
	ErrExecutionFailed = errors.New("function execution failed")

	// ErrCircularDependency is returned when a circular dependency is detected.
	ErrCircularDependency = errors.New("circular dependency detected")

	// ErrSpecialYAMLHandling is returned when a function requires special YAML node handling.
	ErrSpecialYAMLHandling = errors.New("function requires special YAML node handling")
)

Functions

func AllTags

func AllTags() []string

AllTags returns all registered tag names.

func FromYAMLTag

func FromYAMLTag(tag string) string

FromYAMLTag extracts the function name from a YAML tag (e.g., "!env" -> "env").

func IsValidTag

func IsValidTag(tag string) bool

IsValidTag checks if the given tag name is registered.

func ProcessTemplateTagsOnly

func ProcessTemplateTagsOnly(input map[string]any) map[string]any

ProcessTemplateTagsOnly processes only !template tags in a data structure, recursively. It is used before merging to ensure !template strings are decoded to their actual types. This avoids type conflicts during merge (e.g., string vs list).

func RegisterDefaults

func RegisterDefaults()

RegisterDefaults registers all default function handlers with the global registry. This is called automatically when DefaultRegistry() is first accessed, but can also be called explicitly to ensure functions are registered.

func YAMLTag

func YAMLTag(name string) string

YAMLTag returns the YAML tag format for a function name (e.g., "env" -> "!env").

Types

type AwsAccountIDFunction

type AwsAccountIDFunction struct {
	BaseFunction
}

AwsAccountIDFunction implements the aws.account_id function.

func NewAwsAccountIDFunction

func NewAwsAccountIDFunction() *AwsAccountIDFunction

NewAwsAccountIDFunction creates a new aws.account_id function handler.

func (*AwsAccountIDFunction) Execute

func (f *AwsAccountIDFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the aws.account_id function. Usage:

!aws.account_id   - Returns the AWS account ID of the current caller identity

type AwsCallerIdentityArnFunction

type AwsCallerIdentityArnFunction struct {
	BaseFunction
}

AwsCallerIdentityArnFunction implements the aws.caller_identity_arn function.

func NewAwsCallerIdentityArnFunction

func NewAwsCallerIdentityArnFunction() *AwsCallerIdentityArnFunction

NewAwsCallerIdentityArnFunction creates a new aws.caller_identity_arn function handler.

func (*AwsCallerIdentityArnFunction) Execute

func (f *AwsCallerIdentityArnFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the aws.caller_identity_arn function. Usage:

!aws.caller_identity_arn   - Returns the ARN of the current caller identity

type AwsCallerIdentityUserIDFunction

type AwsCallerIdentityUserIDFunction struct {
	BaseFunction
}

AwsCallerIdentityUserIDFunction implements the aws.caller_identity_user_id function.

func NewAwsCallerIdentityUserIDFunction

func NewAwsCallerIdentityUserIDFunction() *AwsCallerIdentityUserIDFunction

NewAwsCallerIdentityUserIDFunction creates a new aws.caller_identity_user_id function handler.

func (*AwsCallerIdentityUserIDFunction) Execute

func (f *AwsCallerIdentityUserIDFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the aws.caller_identity_user_id function. Usage:

!aws.caller_identity_user_id   - Returns the user ID of the current caller identity

type AwsRegionFunction

type AwsRegionFunction struct {
	BaseFunction
}

AwsRegionFunction implements the aws.region function.

func NewAwsRegionFunction

func NewAwsRegionFunction() *AwsRegionFunction

NewAwsRegionFunction creates a new aws.region function handler.

func (*AwsRegionFunction) Execute

func (f *AwsRegionFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the aws.region function. Usage:

!aws.region   - Returns the AWS region from the current configuration

type BaseFunction

type BaseFunction struct {
	FunctionName    string
	FunctionAliases []string
	FunctionPhase   Phase
}

BaseFunction provides a reusable implementation of the Function interface. Embed this struct in concrete function types to inherit common behavior.

func (*BaseFunction) Aliases

func (f *BaseFunction) Aliases() []string

Aliases returns alternative names for the function.

func (*BaseFunction) Name

func (f *BaseFunction) Name() string

Name returns the primary function name.

func (*BaseFunction) Phase

func (f *BaseFunction) Phase() Phase

Phase returns when this function should be executed.

type EnvFunction

type EnvFunction struct {
	BaseFunction
}

EnvFunction implements the env function for environment variable lookup.

func NewEnvFunction

func NewEnvFunction() *EnvFunction

NewEnvFunction creates a new env function handler.

func (*EnvFunction) Execute

func (f *EnvFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the env function. Usage:

!env VAR_NAME           - Get environment variable, return empty string if not set
!env VAR_NAME default   - Get environment variable, return default if not set

type ExecFunction

type ExecFunction struct {
	BaseFunction
}

ExecFunction implements the exec function for shell command execution.

func NewExecFunction

func NewExecFunction() *ExecFunction

NewExecFunction creates a new exec function handler.

func (*ExecFunction) Execute

func (f *ExecFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the exec function. Usage:

!exec command args...   - Execute shell command and return output

If the output is valid JSON, it will be parsed and returned as the corresponding type. Otherwise, the raw string output is returned.

type ExecutionContext

type ExecutionContext struct {
	// AtmosConfig is the current Atmos configuration.
	AtmosConfig *schema.AtmosConfiguration

	// Stack is the current stack name being processed.
	Stack string

	// Component is the current component name being processed.
	Component string

	// BaseDir is the base directory for relative path resolution.
	BaseDir string

	// File is the path to the file being processed.
	File string

	// StackInfo contains additional stack and component information.
	StackInfo *schema.ConfigAndStacksInfo
}

ExecutionContext provides the runtime context for function execution. It contains all the information a function might need to resolve values.

func NewExecutionContext

func NewExecutionContext(atmosConfig *schema.AtmosConfiguration, stack, component string) *ExecutionContext

NewExecutionContext creates a new ExecutionContext with the given parameters.

func (*ExecutionContext) WithBaseDir

func (ctx *ExecutionContext) WithBaseDir(baseDir string) *ExecutionContext

WithBaseDir returns a copy of the context with the base directory set.

func (*ExecutionContext) WithFile

func (ctx *ExecutionContext) WithFile(file string) *ExecutionContext

WithFile returns a copy of the context with the file path set.

func (*ExecutionContext) WithStackInfo

func (ctx *ExecutionContext) WithStackInfo(stackInfo *schema.ConfigAndStacksInfo) *ExecutionContext

WithStackInfo returns a copy of the context with stack info set.

type Function

type Function interface {
	// Name returns the primary function name (e.g., "env", "terraform.output").
	Name() string

	// Aliases returns alternative names for the function.
	Aliases() []string

	// Phase returns when this function should be executed.
	Phase() Phase

	// Execute processes the function with the given arguments and context.
	Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)
}

Function defines the interface for all Atmos configuration functions. Functions are format-agnostic and can be used in YAML, HCL, or JSON configurations.

type GitRootFunction

type GitRootFunction struct {
	BaseFunction
}

GitRootFunction implements the repo-root function for getting the git repository root.

func NewGitRootFunction

func NewGitRootFunction() *GitRootFunction

NewGitRootFunction creates a new repo-root function handler.

func (*GitRootFunction) Execute

func (f *GitRootFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the repo-root function. Usage:

!repo-root   - Returns the absolute path to the git repository root

Returns an error if not in a git repository.

type IncludeFunction

type IncludeFunction struct {
	BaseFunction
}

IncludeFunction implements the include function for including content from files.

func NewIncludeFunction

func NewIncludeFunction() *IncludeFunction

NewIncludeFunction creates a new include function handler.

func (*IncludeFunction) Execute

func (f *IncludeFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the include function. Usage:

!include path/to/file.yaml
!include path/to/file.yaml .query.expression

Note: The include function is special - it operates on yaml.Node directly and cannot return arbitrary values like other functions. The actual implementation remains in pkg/utils/yaml_include_by_extension.go which modifies the yaml.Node in-place.

This function serves as a marker for the registry but the actual processing is handled specially in the YAML processor.

type IncludeRawFunction

type IncludeRawFunction struct {
	BaseFunction
}

IncludeRawFunction implements the include.raw function for including raw file content.

func NewIncludeRawFunction

func NewIncludeRawFunction() *IncludeRawFunction

NewIncludeRawFunction creates a new include.raw function handler.

func (*IncludeRawFunction) Execute

func (f *IncludeRawFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the include.raw function. Usage:

!include.raw path/to/file.txt

Note: Like include, this function operates on yaml.Node directly.

type LiteralFunction

type LiteralFunction struct {
	BaseFunction
}

LiteralFunction implements the literal function for preserving values as-is. This bypasses template processing to preserve template-like syntax ({{...}}, ${...}) for downstream tools like Terraform, Helm, and ArgoCD.

func NewLiteralFunction

func NewLiteralFunction() *LiteralFunction

NewLiteralFunction creates a new literal function handler.

func (*LiteralFunction) Execute

func (f *LiteralFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the literal function. Usage:

!literal "{{external.email}}"
!literal "{{ .Values.ingress.class }}"
!literal |
  #!/bin/bash
  echo "Hello ${USER}"

The function returns the argument exactly as provided, preserving any template-like syntax that would otherwise be processed by Atmos.

type Phase

type Phase int

Phase represents when a function should be executed during configuration processing.

const (
	// PreMerge functions are executed during initial file loading, before
	// configuration merging. Examples: !env, !exec, !include, !random.
	PreMerge Phase = iota

	// PostMerge functions are executed after configuration merging, when the
	// full stack context is available. Examples: !terraform.output, !store.get.
	PostMerge
)

func (Phase) String

func (p Phase) String() string

String returns a human-readable representation of the phase.

type RandomFunction

type RandomFunction struct {
	BaseFunction
}

RandomFunction implements the random function for generating random numbers.

func NewRandomFunction

func NewRandomFunction() *RandomFunction

NewRandomFunction creates a new random function handler.

func (*RandomFunction) Execute

func (f *RandomFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the random function. Usage:

!random           - Generate random number between 0 and 65535
!random max       - Generate random number between 0 and max
!random min max   - Generate random number between min and max

type Registry

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

Registry is a thread-safe registry for Function implementations.

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry returns the global function registry.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new empty function registry.

func (*Registry) Clear

func (r *Registry) Clear()

Clear removes all functions from the registry.

func (*Registry) Get

func (r *Registry) Get(name string) (Function, error)

Get retrieves a function by name or alias. Returns ErrFunctionNotFound if the function is not registered.

func (*Registry) GetByPhase

func (r *Registry) GetByPhase(phase Phase) []Function

GetByPhase returns all functions that should execute in the given phase.

func (*Registry) Has

func (r *Registry) Has(name string) bool

Has checks if a function is registered by name or alias.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered functions.

func (*Registry) List

func (r *Registry) List() []string

List returns all registered function names.

func (*Registry) Register

func (r *Registry) Register(fn Function) error

Register adds a function to the registry. Returns an error if the name or any alias is already registered.

func (*Registry) Unregister

func (r *Registry) Unregister(name string)

Unregister removes a function from the registry.

type StoreFunction

type StoreFunction struct {
	BaseFunction
}

StoreFunction implements the store function for retrieving values from configured stores.

func NewStoreFunction

func NewStoreFunction() *StoreFunction

NewStoreFunction creates a new store function handler.

func (*StoreFunction) Execute

func (f *StoreFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the store function. Usage:

!store store_name stack component key
!store store_name component key            - Uses current stack
!store store_name stack component key | default "value"
!store store_name stack component key | query ".foo.bar"

type StoreGetFunction

type StoreGetFunction struct {
	BaseFunction
}

StoreGetFunction implements the store.get function for retrieving arbitrary keys from stores.

func NewStoreGetFunction

func NewStoreGetFunction() *StoreGetFunction

NewStoreGetFunction creates a new store.get function handler.

func (*StoreGetFunction) Execute

func (f *StoreGetFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the store.get function. Usage:

!store.get store_name key
!store.get store_name key | default "value"
!store.get store_name key | query ".foo.bar"

type TemplateFunction

type TemplateFunction struct {
	BaseFunction
}

TemplateFunction implements the template function for JSON template processing.

func NewTemplateFunction

func NewTemplateFunction() *TemplateFunction

NewTemplateFunction creates a new template function handler.

func (*TemplateFunction) Execute

func (f *TemplateFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the template function. Usage:

!template {"key": "value"}   - Parse JSON and return as native type
!template [1, 2, 3]          - Parse JSON array and return as native slice

If the input is valid JSON, it will be parsed and returned as the corresponding type. Otherwise, the raw string is returned.

type TerraformOutputFunction

type TerraformOutputFunction struct {
	BaseFunction
}

TerraformOutputFunction implements the terraform.output function.

func NewTerraformOutputFunction

func NewTerraformOutputFunction() *TerraformOutputFunction

NewTerraformOutputFunction creates a new terraform.output function handler.

func (*TerraformOutputFunction) Execute

func (f *TerraformOutputFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the terraform.output function. Usage:

!terraform.output component output_name
!terraform.output component stack output_name

Note: This is a placeholder that parses args. The actual terraform output retrieval is handled by internal/exec which has the full implementation.

type TerraformStateFunction

type TerraformStateFunction struct {
	BaseFunction
}

TerraformStateFunction implements the terraform.state function.

func NewTerraformStateFunction

func NewTerraformStateFunction() *TerraformStateFunction

NewTerraformStateFunction creates a new terraform.state function handler.

func (*TerraformStateFunction) Execute

func (f *TerraformStateFunction) Execute(ctx context.Context, args string, execCtx *ExecutionContext) (any, error)

Execute processes the terraform.state function. Usage:

!terraform.state component output_name
!terraform.state component stack output_name

Note: This is a placeholder that parses args. The actual terraform state retrieval is handled by internal/exec which has the full implementation.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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