settings

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const C3XDir = ".c3x"

Variables

View Source
var ErrorInvalidConfigFile = errors.New("parsing config file failed, check file syntax")

Functions

func ApplyRegexMapping

func ApplyRegexMapping(sourceMap TerraformSourceMapRegex, source string) (string, error)

ApplyRegexMapping applies the regex-based mapping to the given source URL and returns the mapped URL if there is a match, otherwise returns the original source

func CleanProjectName

func CleanProjectName(name string) string

func ConfigurationFilePath

func ConfigurationFilePath() string

func CredentialsFilePath

func CredentialsFilePath() string

func FileExists

func FileExists(path string) bool

func IsDev

func IsDev() bool

func IsEnvPresent

func IsEnvPresent(s string) bool

func IsTest

func IsTest() bool

func RootDir

func RootDir() string

Types

type AutodetectConfig

type AutodetectConfig struct {
	// EnvNames is the list of environment names that we should use to group
	// terraform var files.
	EnvNames []string `yaml:"env_names,omitempty" ignored:"true"`
	// ExcludeDirs is a list of directories that the autodetect should ignore.
	ExcludeDirs []string `yaml:"exclude_dirs,omitempty" ignored:"true"`
	// IncludeDirs is a list of directories that the autodetect should append
	// to the already detected directories.
	IncludeDirs []string `yaml:"include_dirs,omitempty" ignored:"true"`
	// PathOverrides defines paths that should be overridden with specific
	// environment variable grouping.
	PathOverrides []PathOverride `yaml:"path_overrides,omitempty" ignored:"true"`
	// MaxSearchDepth configures the number of folders that C3X should
	// traverse to detect projects.
	MaxSearchDepth int `yaml:"max_search_depth,omitempty" ignored:"true"`
	// ForceProjectType is used to force the project type to be a specific value.
	// This is useful when autodetect collides with two project types, normally
	// Terragrunt and Terraform and we want to force the project type to be one or
	// the other.
	ForceProjectType string `yaml:"force_project_type,omitempty" ignored:"true"`
	// TerraformVarFileExtensions is a list of suffixes that should be used to group terraform
	// var files. This is useful when there are non-standard terraform var file
	// names which use different extensions.
	TerraformVarFileExtensions []string `yaml:"terraform_var_file_extensions,omitempty" ignored:"true"`
	// PreferFolderNameForEnv tells the autodetect to prefer the folder name over the
	// over a env specified in a tfvars file. For example, given the following
	// folder structure:
	//
	// .
	// ├── qa
	// │   └── dev.tfvars
	// └── staging
	//     └── prod.tfvars
	//
	// If PreferFolderNameForEnv is true, then the autodetect will group the projects
	// by the folder name so the projects will be named "qa" and "staging".
	PreferFolderNameForEnv bool `yaml:"prefer_folder_name_for_env,omitempty" ignored:"true"`
}

type Configuration

type Configuration struct {
	Version               string `yaml:"version"`
	Currency              string `yaml:"currency,omitempty"`
	EnableDashboard       *bool  `yaml:"enable_dashboard,omitempty"`
	DisableHCLParsing     *bool  `yaml:"disable_hcl_parsing,omitempty"`
	TLSInsecureSkipVerify *bool  `yaml:"tls_insecure_skip_verify,omitempty"`
	TLSCACertFile         string `yaml:"tls_ca_cert_file,omitempty"`
	EnableCloud           *bool  `yaml:"enable_cloud"`
	EnableCloudUpload     *bool  `yaml:"enable_cloud_upload"`

	ProductionFilters []ProductionFilter `yaml:"production_filters,omitempty"`
}

func (Configuration) Save

func (c Configuration) Save() error

type ContextValues

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

ContextValues is a type that wraps a map with methods that safely handle concurrent reads and writes.

func NewContextValues

func NewContextValues(values map[string]interface{}) *ContextValues

NewContextValues returns a new instance of ContextValues.

func (*ContextValues) GetValue

func (cv *ContextValues) GetValue(key string) (interface{}, bool)

GetValue safely retrieves a value from the map. It locks the mutex for reading, deferring the unlock until the method returns. This prevents a race condition if a separate goroutine writes to the map concurrently.

func (*ContextValues) SetValue

func (cv *ContextValues) SetValue(key string, value interface{})

SetValue safely sets a value in the map. It locks the mutex for writing, deferring the unlock until the method returns. This prevents a race condition if separate goroutines read or write to the map concurrently.

func (*ContextValues) Values

func (cv *ContextValues) Values() map[string]interface{}

Values safely retrieves a copy of the map. This method locks the mutex for reading, deferring the unlock until the method returns. By returning a copy, this prevents a race condition if separate goroutines read or write to the original map concurrently. However, creating a copy may be expensive for large maps.

type Credentials

type Credentials struct {
	Version            string `yaml:"version"`
	APIKey             string `yaml:"api_key,omitempty"`
	PricingAPIEndpoint string `yaml:"pricing_api_endpoint,omitempty"`
}

func (Credentials) Save

func (c Credentials) Save() error

type PathOverride

type PathOverride struct {
	Path    string   `yaml:"path"`
	Exclude []string `yaml:"exclude"`
	Only    []string `yaml:"only"`
}

type ProductionFilter

type ProductionFilter struct {
	ID      string `yaml:"id"`
	Type    string `yaml:"type"`
	Include bool   `yaml:"include"`
	Value   string `yaml:"value"`
}

ProductionFilter is a filter for production/non-production paths..

type Project

type Project struct {
	// ConfigSha can be provided to identify the configuration used for the project
	ConfigSha string `yaml:"config_sha,omitempty"  ignored:"true"`
	// Path to the Terraform directory or JSON/plan file.
	// A path can be repeated with different parameters, e.g. for multiple workspaces.
	Path string `yaml:"path" ignored:"true"`
	// ExcludePaths defines a list of directories that the provider should ignore.
	ExcludePaths []string `yaml:"exclude_paths,omitempty" ignored:"true"`
	// DependencyPaths is a list of any paths that this project depends on. These paths are relative to the
	// config file and NOT the project.
	DependencyPaths []string `yaml:"dependency_paths,omitempty"`
	// IncludeAllPaths tells autodetect to use all folders with valid project files.
	IncludeAllPaths bool `yaml:"include_all_paths,omitempty" ignored:"true"`
	// SkipAutodetect tells autodetect to skip this project.
	SkipAutodetect bool `yaml:"skip_autodetect,omitempty" ignored:"true"`
	// Name is a user defined name for the project
	Name string `yaml:"name,omitempty" ignored:"true"`
	// TerraformVarFiles is any var files that are to be used with the project.
	TerraformVarFiles []string `yaml:"terraform_var_files,omitempty"`
	// TerraformVars is a slice of input vars that are to be used with the project.
	TerraformVars map[string]interface{} `yaml:"terraform_vars,omitempty"`
	// TerraformForceCLI will run a project by calling out to the terraform/terragrunt binary to generate a plan JSON file.
	TerraformForceCLI bool `yaml:"terraform_force_cli,omitempty"`
	// TerraformPlanFlags are flags to pass to terraform plan with Terraform directory paths
	TerraformPlanFlags string `yaml:"terraform_plan_flags,omitempty" ignored:"true"`
	// TerraformInitFlags are flags to pass to terraform init
	TerraformInitFlags string `yaml:"terraform_init_flags,omitempty" ignored:"true"`
	// TerraformBinary is an optional field used to change the path to the terraform or terragrunt binary
	TerraformBinary string `yaml:"terraform_binary,omitempty" envconfig:"TERRAFORM_BINARY"`
	// TerraformWorkspace is an optional field used to set the Terraform workspace
	TerraformWorkspace string `yaml:"terraform_workspace,omitempty" envconfig:"TERRAFORM_WORKSPACE"`
	// TerraformCloudWorkspace is used to override the terraform configuration blocks workspace value.
	TerraformCloudWorkspace string `yaml:"terraform_cloud_workspace,omitempty" envconfig:"TERRAFORM_CLOUD_WORKSPACE"`
	// TerraformCloudOrg is used to override the terraform configuration blocks organization value.
	TerraformCloudOrg string `yaml:"terraform_cloud_org,omitempty" envconfig:"TERRAFORM_CLOUD_ORG"`
	// TerraformCloudHost is used to override the default app.terraform.io backend host. Only applicable for
	// terraform cloud/enterprise users.
	TerraformCloudHost string `yaml:"terraform_cloud_host,omitempty" envconfig:"TERRAFORM_CLOUD_HOST"`
	// TerraformCloudToken sets the Team API Token or User API Token so c3x can use it to access the plan.
	// Only applicable for terraform cloud/enterprise users.
	TerraformCloudToken string `yaml:"terraform_cloud_token,omitempty" envconfig:"TERRAFORM_CLOUD_TOKEN"`
	// SpaceliftAPIKeyEndpoint is the endpoint that the spacelift API client will communicate with.
	SpaceliftAPIKeyEndpoint string `yaml:"spacelift_api_key_endpoint,omitempty" envconfig:"SPACELIFT_API_KEY_ENDPOINT"`
	// SpaceliftAPIKeyID is the spacelift API key ID. This is used in combination
	// with the API key secret to generate a JWT token.
	SpaceliftAPIKeyID string `yaml:"spacelift_api_key_id,omitempty" envconfig:"SPACELIFT_API_KEY_ID"`
	// SpaceliftAPIKeySecret is the spacelift API key secret.This is used in combination
	// with the API key id to generate a JWT token.
	SpaceliftAPIKeySecret string `yaml:"spacelift_api_key_secret,omitempty" envconfig:"SPACELIFT_API_KEY_SECRET"`
	// TerragruntFlags set additional flags that should be passed to terragrunt.
	TerragruntFlags string `yaml:"terragrunt_flags,omitempty" envconfig:"TERRAGRUNT_FLAGS"`
	// UsageFile is the full path to usage file that specifies values for usage-based resources
	UsageFile string `yaml:"usage_file,omitempty" ignored:"true"`
	// TerraformUseState sets if the users wants to use the terraform state for c3x ops.
	TerraformUseState bool              `yaml:"terraform_use_state,omitempty" ignored:"true"`
	Env               map[string]string `yaml:"env,omitempty" ignored:"true"`
	// YorConfigPath is the path to a Yor config file, which we can extract default tags from
	YorConfigPath string `yaml:"yor_config_path,omitempty" ignored:"true"`
	// Metadata is a map of key-value pairs that can be used to store additional information about the project.
	// This is useful for storing flexible project information that needs to be accessed by other parts
	// of the application.
	Metadata map[string]string `yaml:"metadata,omitempty" ignored:"true"`
}

Project defines a specific terraform project config. This can be used specify per folder/project configurations so that users don't have to provide flags every run. Fields are documented below. More info is outlined here: https://www.c3x.dev/config-file

type ProjectSession

type ProjectSession struct {
	RunContext    *Session
	ProjectConfig *Project

	ContextValues *ContextValues

	UsingCache bool
	CacheErr   string
	// contains filtered or unexported fields
}

func NewProjectContext

func NewProjectContext(runCtx *Session, projectCfg *Project, logFields interface{}) *ProjectSession

func (*ProjectSession) Logger

func (c *ProjectSession) Logger() zerolog.Logger

func (*ProjectSession) SetFrom

func (c *ProjectSession) SetFrom(d ProjectSessioner)

func (*ProjectSession) SetProjectType

func (c *ProjectSession) SetProjectType(projectType string)

type ProjectSessioner

type ProjectSessioner interface {
	ProjectContext() map[string]interface{}
}

type Session

type Session struct {
	Config        *Settings
	State         *State
	VCSMetadata   vcs.Metadata
	CMD           string
	ContextValues *ContextValues

	ModuleMutex *intSync.KeyMutex
	StartTime   int64

	OutWriter io.Writer
	ErrWriter io.Writer
	Exit      func(code int)
	// contains filtered or unexported fields
}

func EmptyRunContext

func EmptyRunContext() *Session

func NewRunContextFromEnv

func NewRunContextFromEnv(rootCtx context.Context) (*Session, error)

func (*Session) Context

func (r *Session) Context() context.Context

Context returns the underlying context.

func (*Session) EventEnv

func (r *Session) EventEnv() map[string]interface{}

func (*Session) EventEnvWithProjectContexts

func (r *Session) EventEnvWithProjectContexts(projectContexts []*ProjectSession) map[string]interface{}

func (*Session) GetParallelism

func (r *Session) GetParallelism() (int, error)

func (*Session) IsAutoDetect

func (r *Session) IsAutoDetect() bool

IsAutoDetect returns true if the command is running with auto-detect functionality.

func (*Session) IsC3XComment

func (r *Session) IsC3XComment() bool

func (*Session) IsCIRun

func (r *Session) IsCIRun() bool

func (*Session) IsCloudEnabled

func (r *Session) IsCloudEnabled() bool

func (*Session) IsCloudUploadEnabled

func (r *Session) IsCloudUploadEnabled() bool

func (*Session) IsCloudUploadExplicitlyEnabled

func (r *Session) IsCloudUploadExplicitlyEnabled() bool

IsCloudUploadExplicitlyEnabled returns true if cloud upload has been enabled through one of the env variables ENABLE_CLOUD, ENABLE_CLOUD_UPLOAD, or ENABLE_DASHBOARD

func (*Session) SetIsC3XComment

func (r *Session) SetIsC3XComment()

SetIsC3XComment identifies that the primary command being run is `c3x comment`

func (*Session) UUID

func (r *Session) UUID() uuid.UUID

UUID returns the underlying run uuid. This can be used to globally identify the run context.

func (*Session) VCSRepositoryURL

func (r *Session) VCSRepositoryURL() string

type Settings

type Settings struct {
	Credentials   Credentials
	Configuration Configuration

	Version    string           `yaml:"version,omitempty" ignored:"true"`
	Autodetect AutodetectConfig `yaml:"autodetect,omitempty" ignored:"true"`

	LogLevel        string `yaml:"log_level,omitempty" envconfig:"LOG_LEVEL"`
	DebugReport     bool   `ignored:"true"`
	NoColor         bool   `yaml:"no_color,omitempty" envconfig:"NO_COLOR"`
	SkipUpdateCheck bool   `yaml:"skip_update_check,omitempty" envconfig:"SKIP_UPDATE_CHECK"`
	Parallelism     *int   `envconfig:"PARALLELISM"`

	APIKey                    string `envconfig:"API_KEY"`
	PricingAPIEndpoint        string `yaml:"pricing_api_endpoint,omitempty" envconfig:"PRICING_API_ENDPOINT"`
	PricingCacheDisabled      bool   `yaml:"pricing_cache_disabled" envconfig:"PRICING_CACHE_DISABLED"`
	PricingCacheObjectSize    int    `yaml:"pricing_cache_object_size" envconfig:"PRICING_CACHE_OBJECT_SIZE"`
	DefaultPricingAPIEndpoint string `yaml:"default_pricing_api_endpoint,omitempty" envconfig:"DEFAULT_PRICING_API_ENDPOINT"`
	DashboardAPIEndpoint      string `yaml:"dashboard_api_endpoint,omitempty" envconfig:"DASHBOARD_API_ENDPOINT"`
	DashboardEndpoint         string `yaml:"dashboard_endpoint,omitempty" envconfig:"DASHBOARD_ENDPOINT"`
	UsageAPIEndpoint          string `yaml:"usage_api_endpoint,omitempty" envconfig:"USAGE_API_ENDPOINT"`
	UsageActualCosts          bool   `yaml:"usage_actual_costs,omitempty" envconfig:"USAGE_ACTUAL_COSTS"`
	PolicyV2APIEndpoint       string `yaml:"policy_v2_api_endpoint,omitempty" envconfig:"POLICY_V2_API_ENDPOINT"`
	PoliciesEnabled           bool
	TagPoliciesEnabled        bool
	EnableDashboard           bool  `yaml:"enable_dashboard,omitempty" envconfig:"ENABLE_DASHBOARD"`
	EnableCloud               *bool `yaml:"enable_cloud,omitempty" envconfig:"ENABLE_CLOUD"`
	EnableCloudUpload         *bool `yaml:"enable_cloud_upload,omitempty" envconfig:"ENABLE_CLOUD_UPLOAD"`
	DisableHCLParsing         bool  `yaml:"disable_hcl_parsing,omitempty" envconfig:"DISABLE_HCL_PARSING"`
	GraphEvaluator            bool  `yaml:"graph_evaluator,omitempty" envconfig:"GRAPH_EVALUATOR"`

	TLSInsecureSkipVerify *bool  `envconfig:"TLS_INSECURE_SKIP_VERIFY"`
	TLSCACertFile         string `envconfig:"GIT_SSL_CAINFO"`

	Currency       string `envconfig:"CURRENCY"`
	CurrencyFormat string `envconfig:"CURRENCY_FORMAT"`

	AWSOverrideRegion    string `envconfig:"AWS_OVERRIDE_REGION"`
	AzureOverrideRegion  string `envconfig:"AZURE_OVERRIDE_REGION"`
	GoogleOverrideRegion string `envconfig:"GOOGLE_OVERRIDE_REGION"`

	// TerraformSourceMap replaces any source URL with the provided value.
	TerraformSourceMap TerraformSourceMap `envconfig:"TERRAFORM_SOURCE_MAP"`

	// TerraformSourceMapRegex is a more flexible source mapping that supports regex patterns.
	TerraformSourceMapRegex TerraformSourceMapRegex `yaml:"terraform_source_map,omitempty"`

	S3ModuleCacheRegion  string `envconfig:"S3_MODULE_CACHE_REGION"`
	S3ModuleCacheBucket  string `envconfig:"S3_MODULE_CACHE_BUCKET"`
	S3ModuleCachePrefix  string `envconfig:"S3_MODULE_CACHE_PREFIX"`
	S3ModuleCachePrivate bool   `envconfig:"S3_MODULE_CACHE_PRIVATE, default=false"`

	// metrics dump path
	MetricsPath string `envconfig:"METRICS_PATH"`

	// Org settings
	EnableCloudForOrganization bool

	Projects        []*Project `yaml:"projects" ignored:"true"`
	Format          string     `yaml:"format,omitempty" ignored:"true"`
	ShowAllProjects bool       `yaml:"show_all_projects,omitempty" ignored:"true"`
	ShowSkipped     bool       `yaml:"show_skipped,omitempty" ignored:"true"`
	SyncUsageFile   bool       `yaml:"sync_usage_file,omitempty" ignored:"true"`
	Fields          []string   `yaml:"fields,omitempty" ignored:"true"`
	CompareTo       string
	GitDiffTarget   *string

	// Base configuration settings
	// RootPath defines the raw value of the `--path` flag provided by the user
	RootPath string
	// ConfigFilePath defines the raw value of the `--config-file` flag provided by the user
	ConfigFilePath string
	// UsageFilePath defines the raw value of the `--usage-file` flag provided by the user
	UsageFilePath string

	NoCache bool `yaml:"no_cache,omitempty" ignored:"true"`

	SkipErrLine bool
	OfflineMode bool

	// for testing
	EventsDisabled bool
	// contains filtered or unexported fields
}

func DefaultConfig

func DefaultConfig() *Settings

func (*Settings) CachePath

func (c *Settings) CachePath() string

CachePath finds path which contains the .c3x directory. It traverses parent directories until a .c3x folder is found. If no .c3x folders exist then CachePath uses the current wd.

func (*Settings) IsProduction

func (c *Settings) IsProduction(value string) bool

IsProduction returns true if the project is production.

func (*Settings) IsSelfHosted

func (c *Settings) IsSelfHosted() bool

func (*Settings) LoadFromConfigFile

func (c *Settings) LoadFromConfigFile(path string, cmd *cobra.Command) error

func (*Settings) LoadFromEnv

func (c *Settings) LoadFromEnv() error

func (*Settings) LoadGlobalFlags

func (c *Settings) LoadGlobalFlags(cmd *cobra.Command) error

func (*Settings) LogFields

func (c *Settings) LogFields() map[string]interface{}

LogFields sets the meta fields that are added to any log line entries.

func (*Settings) LogWriter

func (c *Settings) LogWriter() io.Writer

LogWriter returns the writer the Logger should use to write logs to. In most cases this should be stderr, but it can also be a file.

func (*Settings) SetLogDisableTimestamps

func (c *Settings) SetLogDisableTimestamps(v bool)

SetLogDisableTimestamps sets if logs should contain the timestamp the line is written at.

func (*Settings) SetLogWriter

func (c *Settings) SetLogWriter(w io.Writer)

SetLogWriter sets the io.Writer that the logs should be piped to.

func (*Settings) WorkingDirectory

func (c *Settings) WorkingDirectory() string

WorkingDirectory returns the filepath to either the directory specified by the --path flag or the directory that the binary has been run from.

func (*Settings) WriteLevel

func (c *Settings) WriteLevel() string

WriteLevel is the log level that the Logger writes to LogWriter.

type SettingsFileSpec

type SettingsFileSpec struct {
	Version                 string                  `yaml:"version"`
	Projects                []*Project              `yaml:"projects" ignored:"true"`
	TerraformSourceMapRegex TerraformSourceMapRegex `yaml:"terraform_source_map,omitempty"`
}

func LoadConfigFile

func LoadConfigFile(path string) (SettingsFileSpec, error)

func (*SettingsFileSpec) UnmarshalYAML

func (f *SettingsFileSpec) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements the yaml.v2.Unmarshaller interface. Marshalls the yaml into an intermediary struct so that we can catch field violations before the data is set on the main ConfigFileSpec. Note this method must return a YamlError type so that we don't run into error collisions with the base yaml.v2 errors.

type State

type State struct {
	InstallID              string `json:"installId"`
	LatestReleaseVersion   string `json:"latestReleaseVersion"`
	LatestReleaseCheckedAt string `json:"latestReleaseCheckedAt"`
}

func LoadState

func LoadState() (*State, error)

func (*State) Save

func (s *State) Save() error

type TerraformSourceMap

type TerraformSourceMap map[string]string

func (*TerraformSourceMap) Decode

func (s *TerraformSourceMap) Decode(value string) error

type TerraformSourceMapRegex

type TerraformSourceMapRegex []TerraformSourceMapRegexEntry

TerraformSourceMapRegex is a slice of regex-based source map entries

func (*TerraformSourceMapRegex) Compile

func (s *TerraformSourceMapRegex) Compile() error

Compile compiles all regex patterns for faster matching

func (*TerraformSourceMapRegex) IsCompiled

func (s *TerraformSourceMapRegex) IsCompiled() bool

type TerraformSourceMapRegexEntry

type TerraformSourceMapRegexEntry struct {
	// Match is the regex pattern to match on the source URL
	Match string `yaml:"match"`
	// Replace is the replacement pattern which can contain capture groups
	Replace string `yaml:"replace"`
	// contains filtered or unexported fields
}

TerraformSourceMapRegexEntry represents a single regex-based source map entry

type YamlError

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

YamlError is a custom error type that allows setting multiple error messages under a base message. It is used to decipher between internal errors and the yaml.v2 errors.

func (*YamlError) Error

func (y *YamlError) Error() string

Error implements the error interface returning the YamlError as a string. If a raw error is set it simply returns the error message from that. Otherwise, it constructs an indented error message out of the base and errors.

YamlError.Error supports multiple nesting and can construct heavily indented output if needed. e.g.

&YamlError{
	base: "top message",
	errors: []error{
		errors.New("top error 1"),
		&YamlError{
			base: "child message",
			errors: []error{
				errors.New("child error 1"),
			},
		},
	},
}

would output a string like so:

top message:
	top error 1
	child message:
		child error 1

This can be useful for ui error messages where you need to highlight issues with specific fields/entries.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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