fileconfiguration

package
v0.1.15 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 8 Imported by: 2 modules, 31 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fileconfiguration

Loads the IONOS YAML configuration file (~/.ionos/config by default) and exposes lookup helpers for per-product, per-location endpoint overrides, credentials, and transport-level failover options.

This package only reads configuration. Applying an override to a live client is the caller's job — see Applying overrides.

Loading

import "github.com/ionos-cloud/sdk-go-bundle/shared/fileconfiguration"

cfg, err := fileconfiguration.New("")                    // default path
cfg, err := fileconfiguration.New("/path/to/config")     // explicit path
cfg, err := fileconfiguration.NewFromEnv()               // path from IONOS_CONFIG_FILE

profiles := fileconfiguration.ReadProfilesFromFile()     // profiles only, never errors
Function Behaviour
New(path) Empty path → DefaultConfigFileName(). Errors if the file is missing, unreadable, empty, or invalid YAML.
NewFromEnv() New(os.Getenv("IONOS_CONFIG_FILE")) — falls back to the default path when the variable is unset.
DefaultConfigFileName() $HOME/.ionos/config; errors if the home directory can't be determined.
ReadProfilesFromFile() Best-effort read of just the currentProfile + profiles keys. Returns nil when the config path is unavailable or the file cannot be read; YAML unmarshal errors are ignored.
Environment variables
Variable Effect
IONOS_CONFIG_FILE Path to the config file. Used by NewFromEnv and ReadProfilesFromFile.
IONOS_CURRENT_PROFILE Overrides currentProfile from the file. Applied inside New and re-checked by GetCurrentProfile, so it wins even if you set cfg.CurrentProfile manually afterwards.

File format

version: 1.0
currentProfile: testProfile

profiles:
  - name: testProfile
    environment: testEnvironment
    credentials:
      username: testUser
      password: testPass
      token: testToken
      s3AccessKey: ...
      s3SecretKey: ...

environments:
  - name: testEnvironment
    certificateAuthData: testCertData      # environment-wide CA
    products:
      - name: mariadb
        endpoints:
          - location: de/fra               # location-based endpoint
            name: mariadb.de-fra.ionos.com
            skipTlsVerify: false
          - location: de/txl
            name: mariadb.de-txl.ionos.com
            certificateAuthData: certauthdata
            skipTlsVerify: true
      - name: psql
        endpoints:
          - name: api.ionos.com/databases/postgresql   # global endpoint (no location)

failover:                                  # optional, see shared/failover
  strategy: roundRobin
  retryableMethods: [GET, PUT]
  retryOnTimeout: true
  failoverOnStatusCodes: [502, 503]

Structure: profile → names an environment → holds a list of products → each with a list of endpoints.

Version is a float64 wrapper with a custom MarshalYAML, so 1.0 is emitted as 1.0 rather than 1 when the config is written back out.

Endpoint fields
Field Meaning
name The endpoint host (no scheme). Callers prepend https:// — shared.NewConfigurationFromOptions does this via getServerUrl.
location Region, e.g. de/fra. Empty means global — that distinction drives every lookup below.
skipTlsVerify Disable TLS verification for this endpoint.
certificateAuthData PEM CA bundle for this endpoint; falls back to the environment's certificateAuthData.
Product name constants

Use the exported constants rather than raw strings — they are the names the lookups match (case-insensitively, whitespace-trimmed).

  • Regionless (global endpoint override): Autoscaling, APIGateway, CDN, Cert, Cloud, ContainerRegistry, DNS, Mongo, ObjectStorageManagement, PSQL
  • Location-based (endpoint per region): InMemoryDB, InMemoryDBV2, Kafka, Logging, Mariadb, MariaDBV2, Monitoring, NFS, ObjectStorage, VPN, PSQLV2

Lookups

Every method is nil-receiver safe and returns nil/zero rather than panicking, so fileconfiguration.New(...) failures can be ignored where a missing config file is acceptable.

Profiles and environments
cfg.GetProfileNames()          // []string
cfg.GetEnvironmentNames()      // []string
cfg.GetCurrentProfile()        // *Profile, nil if unset or not found
cfg.GetEnvForCurrentProfile()  // environment name of the current profile, "" if none

GetCurrentProfile matches case-insensitively and logs a warning when no current profile is set or the named profile is absent.

Endpoints
cfg.GetProductOverrides("mariadb")                        // *Product
cfg.GetProductLocationOverrides("mariadb", "de/fra")      // *Endpoint, exact location match
cfg.GetProductGlobalOverrides("psql", 0)                  // *Endpoint, n-th global endpoint
cfg.GetOverride("dns", "de/fra")                          // location, else first endpoint
cfg.GetLocationOverridesWithGlobalFallback("dns", "de/fra") // location, else first global
cfg.FilterOverrides("nfs", func(e Endpoint) bool { ... })  // []Endpoint by predicate
cfg.FilterGlobalOverrides("nfs")                          // []Endpoint, location == ""
cfg.FilterLocationOverrides("nfs")                        // []Endpoint, location != ""

GetProductOverrides scopes the search to the current profile's environment. If no current profile (or no environment) is resolvable, the environment filter is skipped and the first environment containing a product with that name wins — worth knowing when a config defines the same product in several environments.

GetOverride vs GetLocationOverridesWithGlobalFallback

Both try the exact location first, then fall back. They differ in what they fall back to:

Fallback target Fails when
GetOverride Endpoints[0], whatever it is Endpoints[0] is location-based and its location ≠ the requested one → returns nil with a debug log, even if global endpoints exist further down the list
GetLocationOverridesWithGlobalFallback the first endpoint with an empty location no global endpoints exist for that product

Prefer GetLocationOverridesWithGlobalFallback when the endpoint list mixes global and location-based entries; it preserves declaration order among globals and won't be tripped up by a location-based first element. Pass location: "" to GetOverride for a regionless product.

Failover
opts := cfg.GetFailoverOptions()   // *failover.Options, nil when no failover: block

The failover: block deserializes straight into failover.Options — it's the same struct the RoundTripper consumes, so any field documented there is valid YAML here. The package does not wire it up; propagating it to the runtime configuration is the caller's responsibility.

Applying overrides

fileconfiguration returns data; the shared package applies it:

ep := cfg.GetLocationOverridesWithGlobalFallback(fileconfiguration.Mariadb, "de/fra")
if ep != nil {
    shared.OverrideLocationFor(client, "de/fra", "https://"+ep.Name, false)
}

shared.OverrideLocationFor rewrites the matching ServerConfiguration in place (or appends one), marking it with the shared.EndpointOverridden description so overridden servers can be identified later. Pass replaceServers: true to discard all configured servers in favour of the single override. TLS settings from the endpoint go through shared.SetSkipTLSVerify / shared.CreateTransport.

Files

  • fileconfiguration.go — types, loaders, lookup helpers, product name constants
  • fileconfiguration_test.go — loading, profile/environment resolution, override precedence, failover deserialization

Documentation

Index

Constants

View Source
const (
	Autoscaling             = "autoscaling"
	APIGateway              = "apigateway"
	CDN                     = "cdn"
	Cert                    = "cert"
	Cloud                   = "cloud"
	ContainerRegistry       = "containerregistry"
	DNS                     = "dns"
	Mongo                   = "mongo"
	ObjectStorageManagement = "objectstoragemanagement"
	PSQL                    = "psql"
)

products that do not have a location and will override the endpoint that is used globally

View Source
const (
	InMemoryDB    = "inmemorydb"
	InMemoryDBV2  = "inmemorydbv2"
	Kafka         = "kafka"
	Logging       = "logging"
	Mariadb       = "mariadb"
	MariaDBV2     = "mariadbv2"
	MongoDBV2     = "mongodbv2"
	Monitoring    = "monitoring"
	NFS           = "nfs"
	ObjectStorage = "objectstorage"
	VPN           = "vpn"
	PSQLV2        = "psqlv2"
)

products that have a location and will override the endpoint that is for each location

Variables

This section is empty.

Functions

func DefaultConfigFileName

func DefaultConfigFileName() (string, error)

DefaultConfigFileName returns the default file path for the loaded configuration

Types

type Endpoint

type Endpoint struct {
	// the location or the region
	// Products that do not have a location and will override the endpoint that is used globally:
	// cloud, objectstoragemanagement, kafka, dns, mongo, psql, creg, autoscaling, apigateway
	// Products that have location-based endpoints: logging, monitoring, containerregistry, vpn, inmemorydb, nfs, objectstorage, mariadb
	Location            string `yaml:"location,omitempty"`
	Name                string `yaml:"name"`
	SkipTLSVerify       bool   `yaml:"skipTlsVerify"`
	CertificateAuthData string `yaml:"certificateAuthData,omitempty"`
}

Endpoint is a struct that represents an endpoint

type Environment

type Environment struct {
	Name string `yaml:"name"`
	// CertificateAuthData
	CertificateAuthData string `yaml:"certificateAuthData,omitempty"`
	// Products is a list of ionos products for which we will override endpoint, tls verification
	Products []Product `yaml:"products"`
}

Environment is a struct that represents an environment

type FileConfig

type FileConfig struct {
	// Version of the configuration
	Version Version `yaml:"version"`
	// CurrentProfile active profile for configuration
	CurrentProfile string `yaml:"currentProfile"`
	// Profiles list of profiles
	Profiles []Profile `yaml:"profiles"`
	// Environments list of environments
	Environments []Environment `yaml:"environments"`
	// Failover controls transport-level endpoint failover behaviour and,
	// when set, is propagated to the runtime configuration by the caller.
	Failover *failover.Options `yaml:"failover,omitempty"`
}

FileConfig is a struct that represents the loaded configuration

func New

func New(filePath string) (*FileConfig, error)

New reads yaml file, loads it into a struct and returns it IONOS_CONFIG_FILE environment variable can be set to point to the file to be loaded

func NewFromEnv

func NewFromEnv() (*FileConfig, error)

func (*FileConfig) FilterGlobalOverrides added in v0.1.7

func (f *FileConfig) FilterGlobalOverrides(productName string) []Endpoint

FilterGlobalOverrides returns all global endpoints defined for a given product

func (*FileConfig) FilterLocationOverrides added in v0.1.7

func (f *FileConfig) FilterLocationOverrides(productName string) []Endpoint

FilterLocationOverrides returns all location-based endpoints defined for a given product

func (*FileConfig) FilterOverrides added in v0.1.7

func (f *FileConfig) FilterOverrides(productName string, predicate func(Endpoint) bool) []Endpoint

FilterOverrides returns all endpoints for which the predicate function returns true

func (*FileConfig) GetCurrentProfile

func (f *FileConfig) GetCurrentProfile() *Profile

GetCurrentProfile returns the current profile from the loaded configuration if the current profile is not set, it returns nil if the current profile is set and found in the loaded configuration, it returns the profile

func (*FileConfig) GetEnvForCurrentProfile

func (f *FileConfig) GetEnvForCurrentProfile() string

func (*FileConfig) GetEnvironmentNames added in v0.1.5

func (f *FileConfig) GetEnvironmentNames() []string

GetEnvironmentNames returns a list of environment names from the loaded configuration

func (*FileConfig) GetFailoverOptions added in v0.1.8

func (f *FileConfig) GetFailoverOptions() *failover.Options

GetFailoverOptions returns the failover options from the file configuration. Returns nil when no failover block is defined in the config file.

func (*FileConfig) GetLocationOverridesWithGlobalFallback added in v0.1.7

func (f *FileConfig) GetLocationOverridesWithGlobalFallback(productName, location string) *Endpoint

GetLocationOverridesWithGlobalFallback returns the endpoint for a specific product and location with fallback to the first global endpoint defined if the location is not found. Unlike GetOverride, this function ensures that fallback is done only with global endpoints. It will maintain the order in which the endpoints are defined.

GetLocationOverridesWithGlobalFallback should fail only if the location requested does not exist and there are no global endpoints in the product configuration to fallback on.

func (*FileConfig) GetOverride added in v0.1.5

func (f *FileConfig) GetOverride(productName, location string) *Endpoint

GetOverride returns the endpoint for a specific product and location with fallback to the global endpoint if no location is found. This function will pick the first endpoint defined for the product to attempt fallback. Even if there are global endpoints configured, if the first is location-based, fallback will fail.

It is a helper function combining GetProductLocationOverrides and GetProductOverrides

func (*FileConfig) GetProductGlobalOverrides added in v0.1.7

func (f *FileConfig) GetProductGlobalOverrides(productName string, index int) *Endpoint

GetProductGlobalOverrides returns the n-th overrides for a specific product for the current environment.

func (*FileConfig) GetProductLocationOverrides

func (f *FileConfig) GetProductLocationOverrides(productName, location string) *Endpoint

GetProductLocationOverrides returns the overrides for a specific product and location for the current environment

func (*FileConfig) GetProductOverrides

func (f *FileConfig) GetProductOverrides(productName string) *Product

GetProductOverrides returns the overrides for the given product in the current environment. If no current environment is set, it returns the overrides from the first environment that defines the product.

func (*FileConfig) GetProfileNames added in v0.1.5

func (f *FileConfig) GetProfileNames() []string

GetProfileNames returns a list of profile names from the loaded configuration

func (*FileConfig) Validate added in v0.1.13

func (f *FileConfig) Validate() error

Validate reports every problem found in the file config as a single combined error, or nil when the config is valid (a nil receiver is treated as valid).

type Product

type Product struct {
	// Name is the name of the product
	Name      string     `yaml:"name"`
	Endpoints []Endpoint `yaml:"endpoints"`
}

Product is a struct that represents a product

type Profile

type Profile struct {
	Name        string `yaml:"name"`
	Environment string `yaml:"environment"`
	Credentials shared.Credentials
}

Profile is a struct that represents a profile and it's Credentials

type Profiles

type Profiles struct {
	// CurrentProfile active profile for configuration
	CurrentProfile string `yaml:"currentProfile"`
	// Profiles
	Profiles []Profile `yaml:"profiles"`
}

Profiles wrapper to read only the profiles from the config file

func ReadProfilesFromFile

func ReadProfilesFromFile() *Profiles

ReadProfilesFromFile reads profiles from yaml file, loads it into a struct and returns it

type Version added in v0.1.6

type Version float64

Version wraps float64 so we can control its YAML output.

func (Version) MarshalYAML added in v0.1.6

func (v Version) MarshalYAML() (interface{}, error)

MarshalYAML ensures that, e.g., 1.0 is emitted as "1.0" instead of "1".

Jump to

Keyboard shortcuts

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