toolsconfig

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2023 License: MIT Imports: 9 Imported by: 0

README

Toolsconfig

Documentation is work in progress!

Single config file containing credentials and favourites for cli tools using cobra and viper.

Default configuration file: ~/.toolsconfig/config.yaml. On Linux systems the directory should have 700 permissions, and the file 600, otherwise an error will be thrown.

The following kinds of credentials are now available.

  • Server credentials per URL/Identifier (Similar to ~/.m2/settings.xml or ~/.gradle/gradle.properties) e.g. Docker registry, Artifactory, ...
  • Azure Subscription Credentials
  • Generic credentials (Simple Key/Value pair)

If a credential is required, and it does not exist in the config file a new entry with empty values will be added to the configuration.

Additional features:

  • Favourite handling

    Requires adding toolconfig commands and functions to the cobra root command!

    • Every successfully executed call can be saved as a favourite using
      mytool [param1] [param2] --flag1 test --save myFirstFavourite
    • List existing favourites.
      mytool fav list
    • Run save commands
      mytool --run myFirstFavourite => runs mytool [param1] [param2] --flag1 test

Configuration

# ~/.toolsconfig/config.yaml
servers:
  - # The server base url. This url is used from the apps to find the credentials for the server
    url: repository.url
    # The username to access the server
    username: [ USERNAME ]
    # The password to access the server
    password: [ PASSWORD ]

    # Another example for a maven repository
  - url: maven.repository.url
    username: [ MAVEN_USERNAME ]
    password: [ MAVENPASSWORD ]

azureSubscriptions:
  - # The subscription name. Either the name or the subscriptionID can be used from the tools to get teh credentials 
    name: azureSubsciption01
    # The subscription ID
    subscriptionID: [ SUBSCRIPTION_ID ]
    # The tenant ID
    tenantID: [ TENANT_ID ]
    # The client ID
    clientID: [ CLIENT_ID ]
    # The client secret
    clientSecret: [ CLIENT_SECRET ]
generics:
  - # The key of a generic value 
    key: system-with-token
    # The value for the generic key (e.g. auth token)
    value: [ SECRET TOKEN ]
favourites:
  toolname1:
    favName:
      name: favName
      args: [ arg01, arg02, arg03]
Environement Variables

You can use environment variables to use instead of the values from config files. Environment variables overrule values from config files, but only if all values for a entry are available.

Environment values for the example from above:

REPOSITORY.URL_USERNAME=[USERNAME]
REPOSITORY.URL_IO_PASSWORD=[PASSWORD]
MAVEN.REPOSITORY.URL_PASSWORD=[USERNAME] 
MAVEN.REPOSITORY.URL_USERNAME=[PASSWORD]
AZURESUBSCRIPTION01_SUBSCRIPTIONID=[SUBSCRIPTION_ID]
AZURESUBSCRIPTION01_TENANTID=[TENANT_ID]
AZURESUBSCRIPTION01_CLIENTID=[CLIENT_ID]
AZURESUBSCRIPTION01_CLIENTSECRET=[CLIENT_SECRET]
SYSTEM_WITH_TOKEN_VALUE=CLIENT_SECRET

Example

see Command example

run with:

go run example/main.go --help

Documentation

Index

Constants

View Source
const (
	ConfigFormat          = "yaml"
	ConfigFilePermissions = 0600
)

Variables

View Source
var NewToolConfiguration = func(options ...ConfigOption) (Configuration, error) {
	if configDirectory == nil || configFile == nil {
		return nil, fmt.Errorf(`configuration file location not set (Call toolconfig.ConfigFileLocation("dir", "filename"))`)
	}
	opts := ConfigOptions{
		updateConfig:    true,
		configDirectory: *configDirectory,
		configFile:      *configFile,
	}
	for _, option := range options {
		option(&opts)
	}

	c := &ToolConfiguration{
		servers:            map[string]*ServerCredential{},
		azureSubscriptions: map[string]*AzureSubscriptionCredential{},
		generics:           map[string]*GenericCredential{},
	}

	file, err := configFileName(opts.configDirectory, opts.configFile)
	if err != nil {
		return nil, wrapErr(err)
	}
	viper.SetConfigType(ConfigFormat)
	viper.SetConfigFile(*file)
	viper.SetConfigPermissions(ConfigFilePermissions)

	c.config = readConfiguration()
	err = verifyRequiredValues(c, opts)
	if err != nil {
		dirty := c.config.merge(opts.requiredConfig())
		if dirty && opts.updateConfig {
			err := saveConfiguration(c.config)
			if err != nil {
				return nil, wrapErr(err)
			}
		}
		return nil, err
	}
	return c, err
}

NewToolConfiguration creates a new configuration object. You have to set the config file location before calling this function by calling `toolconfig.ConfigFileLocation("dir", "filename")`. Use the options * RequiredServer(..) * RequiredAzureSubscription(..) * RequiredGeneric(..) to specify which credentials are required. If the credentials are not available in the configuration, an error is returned immediately.

Functions

func ConfigFileLocation added in v0.2.0

func ConfigFileLocation(dir, filename string)

Types

type AzureSubscriptionCredential

type AzureSubscriptionCredential struct {
	Name           string `yaml:"name"`
	SubscriptionID string `yaml:"subscriptionID"`
	TenantID       string `yaml:"tenantID"`
	ClientID       string `yaml:"clientID"`
	ClientSecret   string `yaml:"clientSecret"`
}

func (AzureSubscriptionCredential) FromEnv

type Config

type Config struct {
	DefaultAzureSubscription string                          `yaml:"defaultAzureSubscription,omitempty"`
	Servers                  []ServerCredential              `yaml:"servers"`
	AzureSubscriptions       []AzureSubscriptionCredential   `yaml:"azureSubscriptions"`
	Generic                  []GenericCredential             `yaml:"generics"`
	Favourites               map[string]map[string]Favourite `yaml:"favourites"`
}

type ConfigError

type ConfigError struct {
	Missing []string
	Err     error
}

func (ConfigError) Error

func (e ConfigError) Error() string

type ConfigOption

type ConfigOption func(*ConfigOptions)

func RequiredGeneric

func RequiredGeneric(key string) ConfigOption

RequiredGeneric add the generic credential with given key as required

func RequiredServer

func RequiredServer(serverURLs string) ConfigOption

RequiredServer add the server credential with given url as required

func RequiredSubscription

func RequiredSubscription(nameOrIDs string) ConfigOption

RequiredSubscription add the subscription credential with given name or ID as required

func UpdateConfig

func UpdateConfig(value bool) ConfigOption

UpdateConfig defines whether the config should be updated in file. Default is 'true'. If Enabled and an unknown credential is requested a new empty entry will be added to the configuration file.

type ConfigOptions

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

type Configuration

type Configuration interface {
	// SetAzureSubscriptionCredentials set the azure subscription credentials.
	SetAzureSubscriptionCredentials(entry AzureSubscriptionCredential) error
	// GetAzureSubscriptionCredentials get the azure subscription credentials.
	GetAzureSubscriptionCredentials(nameOrID string) (*AzureSubscriptionCredential, error)
	// GetAllAzureSubscriptionCredentials returns all azure subscription credentials available in config file.
	GetAllAzureSubscriptionCredentials() []AzureSubscriptionCredential
	// SetServerCredentials set the server credentials.
	SetServerCredentials(entry ServerCredential) error
	// GetServerCredentials get the server credentials.
	GetServerCredentials(url string) (*ServerCredential, error)
	// GetAllServerCredentials returns all generic credentials available in config file.
	GetAllServerCredentials() []ServerCredential
	// SetGenericCredentials set the generic credentials.
	SetGenericCredentials(entry GenericCredential) error
	// GetGenericCredentials set the generic credentials.
	GetGenericCredentials(key string) (*GenericCredential, error)
	// GetAllGenericCredentials returns all generic credentials available in config file.
	GetAllGenericCredentials() []GenericCredential
	// GetGeneric ...
	GetGeneric(key string) string
	// SetDefaultSubscription set the default azure subscription.
	SetDefaultSubscription(subscriptionName string) error
	// SaveFavourite saves a favourite in the config file.
	SaveFavourite(tool, name string, args []string) error
	// GetFavourite get a favourite entry identified by the toolname and it's name.
	GetFavourite(tool, name string) (*Favourite, error)
	// GetFavourites get all favourites for a given tool.
	GetFavourites(tool string) []Favourite
	// RemoveFavourite remove a favourite from the config file.
	RemoveFavourite(tool, name string) error
}

type Favourite

type Favourite struct {
	Name string   `yaml:"name"`
	Args []string `yaml:"args,flow"`
}

func (Favourite) String

func (s Favourite) String() string

type GenericCredential

type GenericCredential struct {
	Key   string `yaml:"key"`
	Value string `yaml:"value"`
}

func (GenericCredential) FromEnv

func (c GenericCredential) FromEnv(key string) *GenericCredential

type ServerCredential

type ServerCredential struct {
	URL      string `yaml:"url"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
}

func (ServerCredential) FromEnv

func (c ServerCredential) FromEnv(url string) *ServerCredential

type ToolConfiguration

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

func (*ToolConfiguration) GetAllAzureSubscriptionCredentials added in v0.2.1

func (c *ToolConfiguration) GetAllAzureSubscriptionCredentials() []AzureSubscriptionCredential

func (*ToolConfiguration) GetAllGenericCredentials added in v0.2.2

func (c *ToolConfiguration) GetAllGenericCredentials() []GenericCredential

func (*ToolConfiguration) GetAllServerCredentials added in v0.2.2

func (c *ToolConfiguration) GetAllServerCredentials() []ServerCredential

func (*ToolConfiguration) GetAzureSubscriptionCredentials

func (c *ToolConfiguration) GetAzureSubscriptionCredentials(nameOrID string) (*AzureSubscriptionCredential, error)

GetAzureSubscriptionCredentials find the credentials for the given name or subscription id. Returns errNotFound if not found.

func (*ToolConfiguration) GetFavourite

func (c *ToolConfiguration) GetFavourite(tool, name string) (*Favourite, error)

func (*ToolConfiguration) GetFavourites

func (c *ToolConfiguration) GetFavourites(tool string) []Favourite

func (*ToolConfiguration) GetGeneric

func (c *ToolConfiguration) GetGeneric(key string) string

GetGeneric is a simple call to get only the value of a generic key. Empty string if not exists.

func (*ToolConfiguration) GetGenericCredentials

func (c *ToolConfiguration) GetGenericCredentials(key string) (*GenericCredential, error)

GetGenericCredentials find the credentials for the given key. Returns errNotFound if not found.

func (*ToolConfiguration) GetServerCredentials

func (c *ToolConfiguration) GetServerCredentials(url string) (*ServerCredential, error)

GetServerCredentials find the credentials for the given url. Returns errNotFound if not found.

func (*ToolConfiguration) RemoveFavourite

func (c *ToolConfiguration) RemoveFavourite(tool, name string) error

func (*ToolConfiguration) SaveFavourite

func (c *ToolConfiguration) SaveFavourite(tool, name string, args []string) error

func (*ToolConfiguration) SetAzureSubscriptionCredentials

func (c *ToolConfiguration) SetAzureSubscriptionCredentials(entry AzureSubscriptionCredential) error

func (*ToolConfiguration) SetDefaultSubscription

func (c *ToolConfiguration) SetDefaultSubscription(subscriptionName string) error

SetDefaultSubscription updates the default subscription value in the configuration. GetAzureSubscriptionCredentials returns the subscription credentials with this name or id if the given identifier is empty.

func (*ToolConfiguration) SetGenericCredentials added in v0.2.0

func (c *ToolConfiguration) SetGenericCredentials(entry GenericCredential) error

func (*ToolConfiguration) SetServerCredentials

func (c *ToolConfiguration) SetServerCredentials(entry ServerCredential) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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