cliconfig

package
v1.13.2 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2026 License: MPL-2.0 Imports: 33 Imported by: 0

Documentation

Overview

Package cliconfig has the types representing and the logic to load CLI-level configuration settings.

The CLI config is a small collection of settings that a user can override via some files in their home directory or, in some cases, via environment variables. The CLI config is not the same thing as a Ghoten configuration written in the Terraform language; the logic for those lives in the top-level directory "configs".

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigDir

func ConfigDir() (string, error)

ConfigDir returns the configuration directory for Ghoten.

func ConfigFile

func ConfigFile() (string, error)

ConfigFile returns the default path to the configuration file.

On Unix-like systems this is the ".tofurc" file in the home directory. On Windows, this is the "ghoten.rc" file in the application data directory.

func DataDirs

func DataDirs() ([]string, error)

DataDirs returns the data directories for Ghoten.

func ProviderDownloadRetries

func ProviderDownloadRetries() int

ProviderDownloadRetries will attempt for requests with retryable errors, like 502 status codes

Types

type Config

type Config struct {
	// If set, enables local caching of plugins in this directory to
	// avoid repeatedly re-downloading over the Internet.
	PluginCacheDir string `hcl:"plugin_cache_dir"`

	// PluginCacheMayBreakDependencyLockFile is an interim accommodation for
	// those who wish to use the Plugin Cache Dir even in cases where doing so
	// will cause the dependency lock file to be incomplete.
	//
	// This is likely to become a silent no-op in future Ghoten versions but
	// is here in recognition of the fact that the dependency lock file is not
	// yet a good fit for all Ghoten workflows and folks in that category
	// would prefer to have the plugin cache dir's behavior to take priority
	// over the requirements of the dependency lock file.
	PluginCacheMayBreakDependencyLockFile bool `hcl:"plugin_cache_may_break_dependency_lock_file"`

	Hosts map[string]*ConfigHost `hcl:"host"`

	Credentials        map[string]map[string]interface{}   `hcl:"credentials"`
	CredentialsHelpers map[string]*ConfigCredentialsHelper `hcl:"credentials_helper"`

	// RegistryProtocols contains some settings for tailoring the request
	// timeout and retry count for metadata requests made by our registry
	// protocol clients.
	//
	// [LoadConfig] guarantees that this will always be present and contain
	// values. If these settings are not configured either in files or the
	// environment then we use some reasonable default settings.
	RegistryProtocols *RegistryProtocolsConfig

	// ProviderInstallation represents any provider_installation blocks
	// in the configuration. Only one of these is allowed across the whole
	// configuration, but we decode into a slice here so that we can handle
	// that validation at validation time rather than initial decode time.
	ProviderInstallation []*ProviderInstallation

	// OCIDefaultCredentials and OCIRepositoryCredentials together represent
	// the individual OCI-credentials-related blocks in the configuration.
	//
	// Only one OCIDefaultCredentials element is allowed, but we validate
	// that after loading the configuration. Zero or more OCICredentials
	// blocks are allowed, but they must each have a unique repository
	// prefix.
	OCIDefaultCredentials    []*OCIDefaultCredentials
	OCIRepositoryCredentials []*OCIRepositoryCredentials
}

Config is the structure of the configuration for the Ghoten CLI.

This is not the configuration for Ghoten itself. That is in the "config" package.

var BuiltinConfig Config

BuiltinConfig is the built-in defaults for the configuration. These can be overridden by user configurations.

func EnvConfig

func EnvConfig() *Config

EnvConfig returns a Config populated from environment variables.

Any values specified in this config should override those set in the configuration file.

func LoadConfig

func LoadConfig(ctx context.Context) (*Config, tfdiags.Diagnostics)

LoadConfig reads the CLI configuration from the various filesystem locations and from the environment, returning a merged configuration along with any diagnostics (errors and warnings) encountered along the way.

func (*Config) CredentialsSource

func (c *Config) CredentialsSource(helperPlugins pluginDiscovery.PluginMetaSet) (*CredentialsSource, error)

CredentialsSource creates and returns a service credentials source whose behavior depends on which "credentials" and "credentials_helper" blocks, if any, are present in the receiving config.

func (*Config) Merge

func (c *Config) Merge(c2 *Config) *Config

Merge merges two configurations and returns a third entirely new configuration with the two merged.

func (*Config) OCICredentialsPolicy

func (c *Config) OCICredentialsPolicy(ctx context.Context) (ociauthconfig.CredentialsConfigs, error)

OCICredentialsPolicy returns an object that encapsulates the operator's configured OCI credentials policy, including both the explicitly-configured credentials and any automatically-discovered "ambient" credentials.

This should be called only on a Config where Config.Validate was already called and returned no error diagnostics. Calling this on an unvalidated or invalid configuration produces unspecified results, possibly including panics.

func (*Config) Validate

func (c *Config) Validate() tfdiags.Diagnostics

Validate checks for errors in the configuration that cannot be detected just by HCL decoding, returning any problems as diagnostics.

On success, the returned diagnostics will return false from the HasErrors method. A non-nil diagnostics is not necessarily an error, since it may contain just warnings.

type ConfigCredentialsHelper

type ConfigCredentialsHelper struct {
	Args []string `hcl:"args"`
}

ConfigCredentialsHelper is the structure of the "credentials_helper" nested block within the CLI configuration.

type ConfigFileSystem

type ConfigFileSystem interface {
	// Open opens the named file for reading.
	Open(name string) (fs.File, error)
	// ReadDir reads the named directory, returning all its directory entries sorted by filename.
	ReadDir(name string) ([]os.DirEntry, error)
	// ReadFile reads the named file and returns the contents.
	ReadFile(name string) ([]byte, error)
	// Stat returns a [FileInfo] describing the named file. If there is an error, it will be of type [*PathError].
	Stat(name string) (os.FileInfo, error)
}

ConfigFileSystem is an abstraction layer for file system operations involved in loading the CLI configuration.

The logic of choosing CLI configuration files is highly dependent on the location of those files in the filesystem. Since it's not feasible to test that in a real filesystem, we separate the filesystem operations from the logic of how the files are chosen. The real CLI config loader uses standard os package functions, and the test config loader uses fstest-based functions.

type ConfigHost

type ConfigHost struct {
	Services map[string]interface{} `hcl:"services"`
}

ConfigHost is the structure of the "host" nested block within the CLI configuration, which can be used to override the default service host discovery behavior for a particular hostname.

type ConfigLoader

type ConfigLoader struct {
	ConfigFileSystem
}

func (*ConfigLoader) ConfigDir

func (cl *ConfigLoader) ConfigDir() (string, error)

func (*ConfigLoader) ConfigFile

func (cl *ConfigLoader) ConfigFile() (string, error)

func (*ConfigLoader) DataDirs

func (cl *ConfigLoader) DataDirs() ([]string, error)

func (*ConfigLoader) LoadConfig

func (cl *ConfigLoader) LoadConfig(_ context.Context) (*Config, tfdiags.Diagnostics)

type CredentialsLocation

type CredentialsLocation rune

CredentialsLocation describes a type of storage used for the credentials for a particular hostname.

const (
	// CredentialsNotAvailable means that we know that there are no credential
	// available for the host.
	//
	// Note that CredentialsViaHelper might also lead to no credentials being
	// available, depending on how the helper answers when we request credentials
	// from it.
	CredentialsNotAvailable CredentialsLocation = 0

	// CredentialsInPrimaryFile means that there is already a credentials object
	// for the host in the credentials.tfrc.json file.
	CredentialsInPrimaryFile CredentialsLocation = 'P'

	// CredentialsInOtherFile means that there is already a credentials object
	// for the host in a CLI config file other than credentials.tfrc.json.
	CredentialsInOtherFile CredentialsLocation = 'O'

	// CredentialsViaHelper indicates that no statically-configured credentials
	// are available for the host but a helper program is available that may
	// or may not have credentials for the host.
	CredentialsViaHelper CredentialsLocation = 'H'
)

type CredentialsSource

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

CredentialsSource is an implementation of svcauth.CredentialsSource that can read and write the CLI configuration, and possibly also delegate to a credentials helper when configured.

func EmptyCredentialsSourceForTests

func EmptyCredentialsSourceForTests(credentialsFilePath string) *CredentialsSource

EmptyCredentialsSourceForTests constructs a CredentialsSource with no credentials pre-loaded and which writes new credentials to a file at the given path.

As the name suggests, this function is here only for testing and should not be used in normal application code.

func (*CredentialsSource) CredentialsFilePath

func (s *CredentialsSource) CredentialsFilePath() (string, error)

CredentialsFilePath returns the full path to the local credentials configuration file, so that a caller can mention this path in order to be transparent about where credentials will be stored.

This file will be used for writes only if HostCredentialsLocation for the relevant host returns CredentialsInPrimaryFile or CredentialsNotAvailable.

The credentials file path is found relative to the current user's home directory, so this function will return an error in the unlikely event that we cannot determine a suitable home directory to resolve relative to.

func (*CredentialsSource) CredentialsHelperType

func (s *CredentialsSource) CredentialsHelperType() string

CredentialsHelperType returns the name of the configured credentials helper type, or an empty string if no credentials helper is configured.

func (*CredentialsSource) ForHost

func (*CredentialsSource) ForgetForHost

func (s *CredentialsSource) ForgetForHost(ctx context.Context, host svchost.Hostname) error

func (*CredentialsSource) HostCredentialsLocation

func (s *CredentialsSource) HostCredentialsLocation(host svchost.Hostname) CredentialsLocation

HostCredentialsLocation returns a value indicating what type of storage is currently used for the credentials for the given hostname.

The current location of credentials determines whether updates are possible at all and, if they are, where any updates will be written.

func (*CredentialsSource) StoreForHost

func (s *CredentialsSource) StoreForHost(ctx context.Context, host svchost.Hostname, credentials svcauth.NewHostCredentials) error

type ErrUnwritableHostCredentials

type ErrUnwritableHostCredentials svchost.Hostname

ErrUnwritableHostCredentials is an error type that is returned when a caller tries to write credentials for a host that has existing credentials configured in a file that we cannot automatically update.

func (ErrUnwritableHostCredentials) Error

func (ErrUnwritableHostCredentials) Hostname

Hostname returns the host that could not be written.

type OCIDefaultCredentials

type OCIDefaultCredentials struct {
	// DiscoverAmbientCredentials decides whether Ghoten will attempt to find
	// credentials "ambiently" in the environment where Ghoten is running, such
	// as searching the conventional locations for Docker-style configuration files.
	//
	// This defaults to true, but operators can set it to false to completely opt out
	// of Ghoten using credentials from anywhere other than elsewhere in the
	// Ghoten CLI configuration.
	DiscoverAmbientCredentials bool

	// DockerStyleConfigFiles forces a specific set of filenames to try to use as
	// sources of OCI credentials, interpreting them as Docker CLI-style configuration
	// files.
	//
	// If this is nil, Ghoten uses a default set of search locations mimicking the
	// behavior of other tools in the ecosystem such as Podman, Buildah, etc.
	//
	// If this is non-nil but zero length, it effectively disables using any Docker CLI-style
	// configuration files at all, but if DiscoverAmbientCredentials is also true then
	// future versions of Ghoten might try to use other sources of ambient credentials.
	//
	// This field is always nil if DiscoverAmbientCredentials is false, because this field
	// exists only to customize one aspect of the "ambient credentials" discovery behavior.
	DockerStyleConfigFiles []string

	// The name of a Docker-style credential helper program to use for any domain
	// that doesn't have its own specific credential helper configured.
	//
	// If this is not set then a default credential helper might still be discovered
	// from the ambient credentials sources, unless such discovery is disabled using
	// the other fields in this struct.
	DefaultDockerCredentialHelper string
}

OCIDefaultCredentials corresponds to one oci_default_credentials block in the CLI configuration.

This represents just one part of the overall OCI credentials policy, and so needs to be considered in conjunction with all of the OCICredentials objects across the CLI configuration too.

type OCIRepositoryCredentials

type OCIRepositoryCredentials struct {
	// A repository address prefix, in the form "domain/path", that describes which
	// repositories these credentials are to be used for.
	//
	// This string is treated in the same way as the properties of the "auths" object
	// in a container engine configuration file.
	RepositoryPrefix string

	// Username and Password are credentials to use for a "Basic"-style
	// authentication method. These are mutually-exclusive with AccessToken
	// and RefreshToken.
	Username, Password string

	// AccessToken and RefreshToken are credentials for an OAuth-style
	// authentication method. These are mutually-exclusive with Username
	// and Password.
	AccessToken, RefreshToken string

	// DockerCredentialsHelper is the name of a Docker-style credential helper program
	// to use.
	//
	// Docker-style config only allows credential helpers to be configured at
	// whole-registry-domain granularity, so for consistency we only allow this to be
	// set when RepositoryPathPrefix isn't set.
	DockerCredentialHelper string
}

OCIRepositoryCredentials corresponds directly to a single oci_credentials block in the CLI configuration, decoded in isolation. It represents the credentials configuration for a set of OCI repositories with a specific registry domain and optional repository path prefix.

This represents just one part of the overall OCI credentials policy, and so needs to be considered in conjunction with all of the other OCICredentials objects across the CLI configuration, and the OCIDefaultCredentials object too.

type ProviderInstallation

type ProviderInstallation struct {
	Methods []*ProviderInstallationMethod

	// DevOverrides allows overriding the normal selection process for
	// a particular subset of providers to force using a particular
	// local directory and disregard version numbering altogether.
	// This is here to allow provider developers to conveniently test
	// local builds of their plugins in a development environment, without
	// having to fuss with version constraints, dependency lock files, and
	// so forth.
	//
	// This is _not_ intended for "production" use because it bypasses the
	// usual version selection and checksum verification mechanisms for
	// the providers in question. To make that intent/effect clearer, some
	// Ghoten commands emit warnings when overrides are present. Local
	// mirror directories are a better way to distribute "released"
	// providers, because they are still subject to version constraints and
	// checksum verification.
	DevOverrides map[addrs.Provider]getproviders.PackageLocalDir
}

ProviderInstallation is the structure of the "provider_installation" nested block within the CLI configuration.

type ProviderInstallationFilesystemMirror

type ProviderInstallationFilesystemMirror string

ProviderInstallationFilesystemMirror is a ProviderInstallationSourceLocation representing installation from a particular local filesystem mirror. The string value is the filesystem path to the mirror directory.

func (ProviderInstallationFilesystemMirror) GoString

type ProviderInstallationLocation

type ProviderInstallationLocation interface {
	// contains filtered or unexported methods
}

ProviderInstallationLocation is an interface type representing the different installation location types. The concrete implementations of this interface are:

var ProviderInstallationDirect ProviderInstallationLocation = providerInstallationDirect{}

ProviderInstallationDirect is a ProviderInstallationSourceLocation representing installation from a provider's origin registry.

type ProviderInstallationMethod

type ProviderInstallationMethod struct {
	Location ProviderInstallationLocation
	Include  []string
	Exclude  []string
	Retries  ProviderInstallationMethodRetries
}

ProviderInstallationMethod represents an installation method block inside a provider_installation block.

type ProviderInstallationMethodRetries

type ProviderInstallationMethodRetries func() (int, bool)

ProviderInstallationMethodRetries defines the function to return the configured, or lack of, retries (`download_retry_count`) configured for a provider installation method. This will return a number >= 0 and a bool in case the value actually comes from the CLI configuration. When the bool returned is [false], the number returned will be 0, meaning that the configuration was not specified.

type ProviderInstallationNetworkMirror

type ProviderInstallationNetworkMirror string

ProviderInstallationNetworkMirror is a ProviderInstallationSourceLocation representing installation from a particular local network mirror. The string value is the HTTP base URL exactly as written in the configuration, without any normalization.

func (ProviderInstallationNetworkMirror) GoString

type ProviderInstallationOCIMirror

type ProviderInstallationOCIMirror struct {
	// RepositoryMapping is a function that translates from an Ghoten-style
	// logical provider source address to a physical OCI repository address.
	//
	// For a valid OCI mirror source this function encapsulates the details
	// of evaluating the user-provided mapping template from the configuration,
	// so that callers of this function don't need to be aware of the
	// implementation detail that this uses HCL templates.
	RepositoryMapping func(addrs.Provider) (registryDomain, repositoryName string, err error)
}

ProviderInstallationOCIMirror is a ProviderInstallationSourceLocation representing a rule for using repositories in OCI registries as a provider network mirror.

This is conceptualy similar to ProviderInstallationNetworkMirror, but this on uses the OCI Distribution protocol instead of the Ghoten-specific Provider Mirror Protocol.

func (ProviderInstallationOCIMirror) GoString

type RegistryProtocolsConfig

type RegistryProtocolsConfig struct {
	// RetryCount specifies the number of times Ghoten should
	// retry making metadata requests to module or provider registries
	// when it encounters a retryable error.
	RetryCount    int
	RetryCountSet bool // for tracking overrides between files

	// RequestTimeout is the amount of time to wait for a response
	// to a metadata request to a module or provider registry.
	RequestTimeout    time.Duration
	RequestTimeoutSet bool // for tracking overrides between files
}

RegistryProtocolsConfig models the "registry_protocols" configuration block and its associated environment variables.

These settings are a little awkward in that they relate to Ghoten's native module and provider registry protocols, but not to any other module or provider installation methods. The name of this block type assumes that we'd extend these settings to any other Ghoten-native registry protocols we might add in future, although at the time of writing this comment we have no plans to introduce any, since we're preferring to use industry-standard artifact distribution protocols like OCI Distribution.

They also, due to a historical implementation mistake that we preserved for backward-compatibility, also partially influence Ghoten's native service discovery client regardless of which service protocol it's trying to perform discovery for.

Directories

Path Synopsis
Package ociauthconfig contains types used for describing OCI authentication settings, and helpers for discovering such settings from container engine configuration files as described in https://github.com/containers/image/blob/main/docs/containers-auth.json.5.md .
Package ociauthconfig contains types used for describing OCI authentication settings, and helpers for discovering such settings from container engine configuration files as described in https://github.com/containers/image/blob/main/docs/containers-auth.json.5.md .
Package svcauthconfig contains some helper functions and types to support the cliconfig package's use of github.com/opentofu/svchost/svcauth, which is our mechanism for representing the policy for authenticating to Ghoten-native services such as implementations Ghoten's provider registry protocol.
Package svcauthconfig contains some helper functions and types to support the cliconfig package's use of github.com/opentofu/svchost/svcauth, which is our mechanism for representing the policy for authenticating to Ghoten-native services such as implementations Ghoten's provider registry protocol.

Jump to

Keyboard shortcuts

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