Documentation

Overview

Package config provides utilities for loading configuration from multiple sources that can be used to configure the SDK's API clients, and utilities.

The config package will load configuration from environment variables, AWS shared configuration file (~/.aws/config), and AWS shared credentials file (~/.aws/credentials).

Use the LoadDefaultConfig to load configuration from all the SDK's supported sources, and resolve credentials using the SDK's default credential chain.

LoadDefaultConfig allows for a variadic list of additional Config sources that can provide one or more configuration values which can be used to programmatically control the resolution of a specific value, or allow for broader range of additional configuration sources not supported by the SDK. A Config source implements one or more provider interfaces defined in this package. Config sources passed in will take precedence over the default environment and shared config sources used by the SDK. If one or more Config sources implement the same provider interface, priority will be handled by the order in which the sources were passed in.

A number of helpers (prefixed by “With“) are provided in this package that implement their respective provider interface. These helpers should be used for overriding configuration programmatically at runtime.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sts"
)

func main() {
	ctx := context.TODO()
	cfg, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Fatal(err)
	}

	client := sts.NewFromConfig(cfg)
	identity, err := client.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Account: %s, Arn: %s", aws.ToString(identity.Account), aws.ToString(identity.Arn))
}
Output:

Example (Custom_config)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sts"
)

func main() {
	ctx := context.TODO()

	// Config sources can be passed to LoadDefaultConfig, these sources can implement one or more
	// provider interfaces. These sources take priority over the standard environment and shared configuration values.
	cfg, err := config.LoadDefaultConfig(ctx,
		config.WithRegion("us-west-2"),
		config.WithSharedConfigProfile("customProfile"),
	)
	if err != nil {
		log.Fatal(err)
	}

	client := sts.NewFromConfig(cfg)
	identity, err := client.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Account: %s, Arn: %s", aws.ToString(identity.Account), aws.ToString(identity.Arn))
}
Output:

Index

Examples

Constants

View Source
const CredentialsSourceName = "EnvConfigCredentials"

CredentialsSourceName provides a name of the provider when config is loaded from environment.

View Source
const (

	// DefaultSharedConfigProfile is the default profile to be used when
	// loading configuration from the config files if another profile name
	// is not provided.
	DefaultSharedConfigProfile = `default`
)

Variables

View Source
var DefaultSharedConfigFiles = []string{
	DefaultSharedConfigFilename(),
}

DefaultSharedConfigFiles is a slice of the default shared config files that the will be used in order to load the SharedConfig.

View Source
var DefaultSharedCredentialsFiles = []string{
	DefaultSharedCredentialsFilename(),
}

DefaultSharedCredentialsFiles is a slice of the default shared credentials files that the will be used in order to load the SharedConfig.

Functions

func DefaultSharedConfigFilename

func DefaultSharedConfigFilename() string

DefaultSharedConfigFilename returns the SDK's default file path for the shared config file.

Builds the shared config file path based on the OS's platform.

- Linux/Unix: $HOME/.aws/config
- Windows: %USERPROFILE%\.aws\config

func DefaultSharedCredentialsFilename

func DefaultSharedCredentialsFilename() string

DefaultSharedCredentialsFilename returns the SDK's default file path for the shared credentials file.

Builds the shared config file path based on the OS's platform.

- Linux/Unix: $HOME/.aws/credentials
- Windows: %USERPROFILE%\.aws\credentials

func LoadDefaultConfig

func LoadDefaultConfig(ctx context.Context, optFns ...func(*LoadOptions) error) (cfg aws.Config, err error)

LoadDefaultConfig reads the SDK's default external configurations, and populates an AWS Config with the values from the external configurations.

An optional variadic set of additional Config values can be provided as input that will be prepended to the configs slice. Use this to add custom configuration. The custom configurations must satisfy the respective providers for their data or the custom data will be ignored by the resolvers and config loaders.

cfg, err := config.LoadDefaultConfig( context.TODO(),
   WithSharedConfigProfile("test-profile"),
)
if err != nil {
   panic(fmt.Sprintf("failed loading config, %v", err))
}

The default configuration sources are: * Environment Variables * Shared Configuration and Shared Credentials files.

Types

type AssumeRoleTokenProviderNotSetError

type AssumeRoleTokenProviderNotSetError struct{}

AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the MFAToken option is not set when shared config is configured load assume a role with an MFA token.

func (AssumeRoleTokenProviderNotSetError) Error

Error is the error message

type Config

type Config interface{}

A Config represents a generic configuration value or set of values. This type will be used by the AWSConfigResolvers to extract

General the Config type will use type assertion against the Provider interfaces to extract specific data from the Config.

type CredentialRequiresARNError

type CredentialRequiresARNError struct {
	// type of credentials that were configured.
	Type string

	// Profile name the credentials were in.
	Profile string
}

CredentialRequiresARNError provides the error for shared config credentials that are incorrectly configured in the shared config or credentials file.

func (CredentialRequiresARNError) Error

Error satisfies the error interface.

type EnvConfig

type EnvConfig struct {
	// Environment configuration values. If set both Access Key ID and Secret Access
	// Key must be provided. Session Token and optionally also be provided, but is
	// not required.
	//
	//	# Access Key ID
	//	AWS_ACCESS_KEY_ID=AKID
	//	AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set.
	//
	//	# Secret Access Key
	//	AWS_SECRET_ACCESS_KEY=SECRET
	//	AWS_SECRET_KEY=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set.
	//
	//	# Session Token
	//	AWS_SESSION_TOKEN=TOKEN
	Credentials aws.Credentials

	// ContainerCredentialsEndpoint value is the HTTP enabled endpoint to retrieve credentials
	// using the endpointcreds.Provider
	ContainerCredentialsEndpoint string

	// ContainerCredentialsRelativePath is the relative URI path that will be used when attempting to retrieve
	// credentials from the container endpoint.
	ContainerCredentialsRelativePath string

	// ContainerAuthorizationToken is the authorization token that will be included in the HTTP Authorization
	// header when attempting to retrieve credentials from the container credentials endpoint.
	ContainerAuthorizationToken string

	// Region value will instruct the SDK where to make service API requests to. If is
	// not provided in the environment the region must be provided before a service
	// client request is made.
	//
	//	AWS_REGION=us-west-2
	//	AWS_DEFAULT_REGION=us-west-2
	Region string

	// Profile name the SDK should load use when loading shared configuration from the
	// shared configuration files. If not provided "default" will be used as the
	// profile name.
	//
	//	AWS_PROFILE=my_profile
	//	AWS_DEFAULT_PROFILE=my_profile
	SharedConfigProfile string

	// Shared credentials file path can be set to instruct the SDK to use an alternate
	// file for the shared credentials. If not set the file will be loaded from
	// $HOME/.aws/credentials on Linux/Unix based systems, and
	// %USERPROFILE%\.aws\credentials on Windows.
	//
	//	AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials
	SharedCredentialsFile string

	// Shared config file path can be set to instruct the SDK to use an alternate
	// file for the shared config. If not set the file will be loaded from
	// $HOME/.aws/config on Linux/Unix based systems, and
	// %USERPROFILE%\.aws\config on Windows.
	//
	//	AWS_CONFIG_FILE=$HOME/my_shared_config
	SharedConfigFile string

	// Sets the path to a custom Credentials Authority (CA) Bundle PEM file
	// that the SDK will use instead of the system's root CA bundle.
	// Only use this if you want to configure the SDK to use a custom set
	// of CAs.
	//
	// Enabling this option will attempt to merge the Transport
	// into the SDK's HTTP client. If the client's Transport is
	// not a http.Transport an error will be returned. If the
	// Transport's TLS config is set this option will cause the
	// SDK to overwrite the Transport's TLS config's  RootCAs value.
	//
	// Setting a custom HTTPClient in the aws.Config options will override this setting.
	// To use this option and custom HTTP client, the HTTP client needs to be provided
	// when creating the config. Not the service client.
	//
	//  AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle
	CustomCABundle string

	// Enables endpoint discovery via environment variables.
	//
	//	AWS_ENABLE_ENDPOINT_DISCOVERY=true
	EnableEndpointDiscovery *bool

	// Specifies the WebIdentity token the SDK should use to assume a role
	// with.
	//
	//  AWS_WEB_IDENTITY_TOKEN_FILE=file_path
	WebIdentityTokenFilePath string

	// Specifies the IAM role arn to use when assuming an role.
	//
	//  AWS_ROLE_ARN=role_arn
	RoleARN string

	// Specifies the IAM role session name to use when assuming a role.
	//
	//  AWS_ROLE_SESSION_NAME=session_name
	RoleSessionName string

	// Specifies if the S3 service should allow ARNs to direct the region
	// the client's requests are sent to.
	//
	// AWS_S3_USE_ARN_REGION=true
	S3UseARNRegion *bool
}

EnvConfig is a collection of environment values the SDK will read setup config from. All environment values are optional. But some values such as credentials require multiple values to be complete or the values will be ignored.

func NewEnvConfig

func NewEnvConfig() (EnvConfig, error)

NewEnvConfig retrieves the SDK's environment configuration. See `EnvConfig` for the values that will be retrieved.

func (EnvConfig) GetS3UseARNRegion

func (c EnvConfig) GetS3UseARNRegion(ctx context.Context) (value, ok bool, err error)

GetS3UseARNRegion returns whether to allow ARNs to direct the region the S3 client's requests are sent to.

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient is an HTTP client implementation

type LoadOptions

type LoadOptions struct {

	// Region is the region to send requests to.
	Region string

	// Credentials object to use when signing requests.
	Credentials aws.CredentialsProvider

	// HTTPClient the SDK's API clients will use to invoke HTTP requests.
	HTTPClient HTTPClient

	// EndpointResolver that can be used to provide or override an endpoint for the given
	// service and region Please see the `aws.EndpointResolver` documentation on usage.
	EndpointResolver aws.EndpointResolver

	// Retryer is a function that provides a Retryer implementation. A Retryer guides how HTTP requests should be
	// retried in case of recoverable failures.
	Retryer func() aws.Retryer

	// APIOptions provides the set of middleware mutations modify how the API
	// client requests will be handled. This is useful for adding additional
	// tracing data to a request, or changing behavior of the SDK's client.
	APIOptions []func(*middleware.Stack) error

	// Logger writer interface to write logging messages to.
	Logger logging.Logger

	// ClientLogMode is used to configure the events that will be sent to the configured logger.
	// This can be used to configure the logging of signing, retries, request, and responses
	// of the SDK clients.
	//
	// See the ClientLogMode type documentation for the complete set of logging modes and available
	// configuration.
	ClientLogMode *aws.ClientLogMode

	// SharedConfigProfile is the profile to be used when loading the SharedConfig
	SharedConfigProfile string

	// SharedConfigFiles is the slice of custom shared config files to use when loading the SharedConfig.
	// A non-default profile used within config file must have name defined with prefix 'profile '.
	// eg [profile xyz] indicates a profile with name 'xyz'.
	// To read more on the format of the config file, please refer the documentation at
	// https://docs.aws.amazon.com/credref/latest/refdocs/file-format.html#file-format-config
	//
	// If duplicate profiles are provided within the same, or across multiple shared config files, the next parsed
	// profile will override only the properties that conflict with the previously defined profile.
	// Note that if duplicate profiles are provided within the SharedCredentialsFiles and SharedConfigFiles,
	// the properties defined in shared credentials file take precedence.
	SharedConfigFiles []string

	// SharedCredentialsFile is the slice of custom shared credentials files to use when loading the SharedConfig.
	// The profile name used within credentials file must not prefix 'profile '.
	// eg [xyz] indicates a profile with name 'xyz'. Profile declared as [profile xyz] will be ignored.
	// To read more on the format of the credentials file, please refer the documentation at
	// https://docs.aws.amazon.com/credref/latest/refdocs/file-format.html#file-format-creds
	//
	// If duplicate profiles are provided with a same, or across multiple shared credentials files, the next parsed
	// profile will override only properties that conflict with the previously defined profile.
	// Note that if duplicate profiles are provided within the SharedCredentialsFiles and SharedConfigFiles,
	// the properties defined in shared credentials file take precedence.
	SharedCredentialsFiles []string

	// CustomCABundle is CA bundle PEM bytes reader
	CustomCABundle io.Reader

	// DefaultRegion is the fall back region, used if a region was not resolved from other sources
	DefaultRegion string

	// UseEC2IMDSRegion indicates if SDK should retrieve the region
	// from the EC2 Metadata service
	UseEC2IMDSRegion *UseEC2IMDSRegion

	// ProcessCredentialOptions is a function for setting
	// the processcreds.Options
	ProcessCredentialOptions func(*processcreds.Options)

	// EC2RoleCredentialOptions is a function for setting
	// the ec2rolecreds.Options
	EC2RoleCredentialOptions func(*ec2rolecreds.Options)

	// EndpointCredentialOptions is a function for setting
	// the endpointcreds.Options
	EndpointCredentialOptions func(*endpointcreds.Options)

	// WebIdentityRoleCredentialOptions is a function for setting
	// the stscreds.WebIdentityRoleOptions
	WebIdentityRoleCredentialOptions func(*stscreds.WebIdentityRoleOptions)

	// AssumeRoleCredentialOptions is a function for setting the
	// stscreds.AssumeRoleOptions
	AssumeRoleCredentialOptions func(*stscreds.AssumeRoleOptions)

	// SSOProviderOptions is a function for setting
	// the ssocreds.Options
	SSOProviderOptions func(options *ssocreds.Options)

	// LogConfigurationWarnings when set to true, enables logging
	// configuration warnings
	LogConfigurationWarnings *bool

	// S3UseARNRegion specifies if the S3 service should allow ARNs to direct
	// the region, the client's requests are sent to.
	S3UseARNRegion *bool
}

LoadOptions are discrete set of options that are valid for loading the configuration

func (LoadOptions) GetS3UseARNRegion

func (o LoadOptions) GetS3UseARNRegion(ctx context.Context) (v bool, found bool, err error)

GetS3UseARNRegion returns whether to allow ARNs to direct the region the S3 client's requests are sent to.

type LoadOptionsFunc

type LoadOptionsFunc func(*LoadOptions) error

LoadOptionsFunc is a type alias for LoadOptions functional option

func WithAPIOptions

func WithAPIOptions(v []func(*middleware.Stack) error) LoadOptionsFunc

WithAPIOptions is a helper function to construct functional options that sets APIOptions on LoadOptions. If APIOptions is set to nil, the APIOptions value is ignored. If multiple WithAPIOptions calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

func main() {
	// import "github.com/aws/smithy-go/middleware"
	// import smithyhttp "github.com/aws/smithy-go/transport/http"

	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithAPIOptions([]func(*middleware.Stack) error{
			smithyhttp.AddHeaderValue("X-Custom-Header", "customHeaderValue"),
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	_ = cfg
}
Output:

func WithAssumeRoleCredentialOptions

func WithAssumeRoleCredentialOptions(v func(*stscreds.AssumeRoleOptions)) LoadOptionsFunc

WithAssumeRoleCredentialOptions is a helper function to construct functional options that sets a function to use stscreds.AssumeRoleOptions on config's LoadOptions. If assume role credentials options is set to nil, the assume role credentials value will be ignored. If multiple WithAssumeRoleCredentialOptions calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
)

func main() {
	// WithAssumeRoleCredentialOptions can be used to configure the AssumeRoleOptions for the STS credential provider.
	// For example the TokenProvider can be populated if assuming a role that requires an MFA token.
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithAssumeRoleCredentialOptions(func(options *stscreds.AssumeRoleOptions) {
			options.TokenProvider = func() (string, error) {
				return "theTokenCode", nil
			}
		}))
	if err != nil {
		log.Fatal(err)
	}
	_ = cfg
}
Output:

func WithClientLogMode

func WithClientLogMode(v aws.ClientLogMode) LoadOptionsFunc

WithClientLogMode is a helper function to construct functional options that sets client log mode on LoadOptions. If client log mode is set to nil, the client log mode value will be ignored. If multiple WithClientLogMode calls are made, the last call overrides the previous call values.

func WithCredentialsProvider

func WithCredentialsProvider(v aws.CredentialsProvider) LoadOptionsFunc

WithCredentialsProvider is a helper function to construct functional options that sets Credential provider value on config's LoadOptions. If credentials provider is set to nil, the credentials provider value will be ignored. If multiple WithCredentialsProvider calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		// Hard coded credentials.
		config.WithCredentialsProvider(credentials.StaticCredentialsProvider{
			Value: aws.Credentials{
				AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "SESSION",
				Source: "example hard coded credentials",
			},
		}))
	if err != nil {
		log.Fatal(err)
	}

	// Credentials retrieve will be called automatically internally to the SDK
	// service clients created with the cfg value.
	creds, err := cfg.Credentials.Retrieve(context.TODO())
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Credentials Source:", creds.Source)
	// Credentials Source: example hard coded credentials
}
Output:

func WithCustomCABundle

func WithCustomCABundle(v io.Reader) LoadOptionsFunc

WithCustomCABundle is a helper function to construct functional options that sets CustomCABundle on config's LoadOptions. Setting the custom CA Bundle to nil will result in custom CA Bundle value being ignored. If multiple WithCustomCABundle calls are made, the last call overrides the previous call values.

func WithDefaultRegion

func WithDefaultRegion(v string) LoadOptionsFunc

WithDefaultRegion is a helper function to construct functional options that sets a DefaultRegion on config's LoadOptions. Setting the default region to an empty string, will result in the default region value being ignored. If multiple WithDefaultRegion calls are made, the last call overrides the previous call values. Note that both WithRegion and WithEC2IMDSRegion call takes precedence over WithDefaultRegion call when resolving region.

func WithEC2IMDSRegion

func WithEC2IMDSRegion(fnOpts ...func(o *UseEC2IMDSRegion)) LoadOptionsFunc

WithEC2IMDSRegion is a helper function to construct functional options that enables resolving EC2IMDS region. The function takes in a UseEC2IMDSRegion functional option, and can be used to set the EC2IMDS client which will be used to resolve EC2IMDSRegion. If no functional option is provided, an EC2IMDS client is built and used by the resolver. If multiple WithEC2IMDSRegion calls are made, the last call overrides the previous call values. Note that the WithRegion calls takes precedence over WithEC2IMDSRegion when resolving region.

Example
package main

import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithEC2IMDSRegion(),
	)
	if err != nil {
		log.Fatal(err)
	}
	_ = cfg
}
Output:

func WithEC2RoleCredentialOptions

func WithEC2RoleCredentialOptions(v func(*ec2rolecreds.Options)) LoadOptionsFunc

WithEC2RoleCredentialOptions is a helper function to construct functional options that sets a function to use ec2rolecreds.Options on config's LoadOptions. If EC2 role credential options is set to nil, the EC2 role credential options value will be ignored. If multiple WithEC2RoleCredentialOptions calls are made, the last call overrides the previous call values.

func WithEndpointCredentialOptions

func WithEndpointCredentialOptions(v func(*endpointcreds.Options)) LoadOptionsFunc

WithEndpointCredentialOptions is a helper function to construct functional options that sets a function to use endpointcreds.Options on config's LoadOptions. If endpoint credential options is set to nil, the endpoint credential options value will be ignored. If multiple WithEndpointCredentialOptions calls are made, the last call overrides the previous call values.

func WithEndpointResolver

func WithEndpointResolver(v aws.EndpointResolver) LoadOptionsFunc

WithEndpointResolver is a helper function to construct functional options that sets endpoint resolver on LoadOptions. The EndpointResolver is set to nil, the EndpointResolver value is ignored. If multiple WithEndpointResolver calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithEndpointResolver(aws.EndpointResolverFunc(
			func(service, region string) (aws.Endpoint, error) {
				return aws.Endpoint{URL: "https://mock.amazonaws.com"}, nil
			})),
	)

	if err != nil {
		log.Fatal(err)
	}
	_ = cfg
}
Output:

func WithHTTPClient

func WithHTTPClient(v HTTPClient) LoadOptionsFunc

WithHTTPClient is a helper function to construct functional options that sets HTTPClient on LoadOptions. If HTTPClient is set to nil, the HTTPClient value will be ignored. If multiple WithHTTPClient calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"log"
	"net/http"

	awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
	"github.com/aws/aws-sdk-go-v2/config"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithHTTPClient(awshttp.NewBuildableClient().
			WithTransportOptions(func(tr *http.Transport) {
				tr.MaxIdleConns = 60
			})),
	)
	if err != nil {
		log.Fatal(err)
	}
	_ = cfg
}
Output:

func WithLogConfigurationWarnings

func WithLogConfigurationWarnings(v bool) LoadOptionsFunc

WithLogConfigurationWarnings is a helper function to construct functional options that can be used to set LogConfigurationWarnings on LoadOptions.

If multiple WithLogConfigurationWarnings calls are made, the last call overrides the previous call values.

func WithLogger

func WithLogger(v logging.Logger) LoadOptionsFunc

WithLogger is a helper function to construct functional options that sets Logger on LoadOptions. If Logger is set to nil, the Logger value will be ignored. If multiple WithLogger calls are made, the last call overrides the previous call values.

func WithProcessCredentialOptions

func WithProcessCredentialOptions(v func(*processcreds.Options)) LoadOptionsFunc

WithProcessCredentialOptions is a helper function to construct functional options that sets a function to use processcreds.Options on config's LoadOptions. If process credential options is set to nil, the process credential value will be ignored. If multiple WithProcessCredentialOptions calls are made, the last call overrides the previous call values.

func WithRegion

func WithRegion(v string) LoadOptionsFunc

WithRegion is a helper function to construct functional options that sets Region on config's LoadOptions. Setting the region to an empty string, will result in the region value being ignored. If multiple WithRegion calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithRegion("us-west-2"))
	if err != nil {
		log.Fatal(err)
	}
	_ = cfg
}
Output:

func WithRetryer

func WithRetryer(v func() aws.Retryer) LoadOptionsFunc

WithRetryer is a helper function to construct functional options that sets Retryer on LoadOptions. If Retryer is set to nil, the Retryer value is ignored. If multiple WithRetryer calls are made, the last call overrides the previous call values.

func WithS3UseARNRegion

func WithS3UseARNRegion(v bool) LoadOptionsFunc

WithS3UseARNRegion is a helper function to construct functional options that can be used to set S3UseARNRegion on LoadOptions. If multiple WithS3UseARNRegion calls are made, the last call overrides the previous call values.

func WithSSOProviderOptions

func WithSSOProviderOptions(v func(*ssocreds.Options)) LoadOptionsFunc

WithSSOProviderOptions is a helper function to construct functional options that sets a function to use ssocreds.Options on config's LoadOptions. If the SSO credential provider options is set to nil, the sso provider options value will be ignored. If multiple WithSSOProviderOptions calls are made, the last call overrides the previous call values.

func WithSharedConfigFiles

func WithSharedConfigFiles(v []string) LoadOptionsFunc

WithSharedConfigFiles is a helper function to construct functional options that sets slice of SharedConfigFiles on config's LoadOptions. Setting the shared config files to an nil string slice, will result in the shared config files value being ignored. If multiple WithSharedConfigFiles calls are made, the last call overrides the previous call values.

func WithSharedConfigProfile

func WithSharedConfigProfile(v string) LoadOptionsFunc

WithSharedConfigProfile is a helper function to construct functional options that sets SharedConfigProfile on config's LoadOptions. Setting the shared config profile to an empty string, will result in the shared config profile value being ignored. If multiple WithSharedConfigProfile calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"path/filepath"

	"github.com/aws/aws-sdk-go-v2/config"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		// Specify the shared configuration profile to load.
		config.WithSharedConfigProfile("exampleProfile"),

		// Optionally specify the specific shared configuraiton
		// files to load the profile from.
		config.WithSharedConfigFiles([]string{
			filepath.Join("testdata", "shared_config"),
		}),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Region loaded from credentials file.
	fmt.Println("Region:", cfg.Region)

}
Output:

Region: us-west-2

func WithSharedCredentialsFiles

func WithSharedCredentialsFiles(v []string) LoadOptionsFunc

WithSharedCredentialsFiles is a helper function to construct functional options that sets slice of SharedCredentialsFiles on config's LoadOptions. Setting the shared credentials files to an nil string slice, will result in the shared credentials files value being ignored. If multiple WithSharedCredentialsFiles calls are made, the last call overrides the previous call values.

func WithWebIdentityRoleCredentialOptions

func WithWebIdentityRoleCredentialOptions(v func(*stscreds.WebIdentityRoleOptions)) LoadOptionsFunc

WithWebIdentityRoleCredentialOptions is a helper function to construct functional options that sets a function to use stscreds.WebIdentityRoleOptions on config's LoadOptions. If web identity role credentials options is set to nil, the web identity role credentials value will be ignored. If multiple WithWebIdentityRoleCredentialOptions calls are made, the last call overrides the previous call values.

Example
package main

import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithWebIdentityRoleCredentialOptions(func(options *stscreds.WebIdentityRoleOptions) {
			options.RoleSessionName = "customSessionName"
		}))
	if err != nil {
		log.Fatal(err)
	}
	_ = cfg
}
Output:

type LoadSharedConfigOptions

type LoadSharedConfigOptions struct {

	// CredentialsFiles are the shared credentials files
	CredentialsFiles []string

	// ConfigFiles are the shared config files
	ConfigFiles []string

	// Logger is the logger used to log shared config behavior
	Logger logging.Logger
}

LoadSharedConfigOptions struct contains optional values that can be used to load the config.

type SharedConfig

type SharedConfig struct {
	Profile string

	// Credentials values from the config file. Both aws_access_key_id
	// and aws_secret_access_key must be provided together in the same file
	// to be considered valid. The values will be ignored if not a complete group.
	// aws_session_token is an optional field that can be provided if both of the
	// other two fields are also provided.
	//
	//	aws_access_key_id
	//	aws_secret_access_key
	//	aws_session_token
	Credentials aws.Credentials

	CredentialSource     string
	CredentialProcess    string
	WebIdentityTokenFile string

	SSOAccountID string
	SSORegion    string
	SSORoleName  string
	SSOStartURL  string

	RoleARN             string
	ExternalID          string
	MFASerial           string
	RoleSessionName     string
	RoleDurationSeconds *time.Duration

	SourceProfileName string
	Source            *SharedConfig

	// Region is the region the SDK should use for looking up AWS service endpoints
	// and signing requests.
	//
	//	region
	Region string

	// EnableEndpointDiscovery can be enabled in the shared config by setting
	// endpoint_discovery_enabled to true
	//
	//	endpoint_discovery_enabled = true
	EnableEndpointDiscovery *bool

	// Specifies if the S3 service should allow ARNs to direct the region
	// the client's requests are sent to.
	//
	// s3_use_arn_region=true
	S3UseARNRegion *bool
}

SharedConfig represents the configuration fields of the SDK config files.

func LoadSharedConfigProfile

func LoadSharedConfigProfile(ctx context.Context, profile string, optFns ...func(*LoadSharedConfigOptions)) (SharedConfig, error)

LoadSharedConfigProfile retrieves the configuration from the list of files using the profile provided. The order the files are listed will determine precedence. Values in subsequent files will overwrite values defined in earlier files.

For example, given two files A and B. Both define credentials. If the order of the files are A then B, B's credential values will be used instead of A's.

If config files are not set, SDK will default to using a file at location `.aws/config` if present. If credentials files are not set, SDK will default to using a file at location `.aws/credentials` if present. No default files are set, if files set to an empty slice.

You can read more about shared config and credentials file location at https://docs.aws.amazon.com/credref/latest/refdocs/file-location.html#file-location

func (SharedConfig) GetS3UseARNRegion

func (c SharedConfig) GetS3UseARNRegion(ctx context.Context) (value, ok bool, err error)

GetS3UseARNRegion returns if the S3 service should allow ARNs to direct the region the client's requests are sent to.

type SharedConfigAssumeRoleError

type SharedConfigAssumeRoleError struct {
	Profile string
	RoleARN string
	Err     error
}

SharedConfigAssumeRoleError is an error for the shared config when the profile contains assume role information, but that information is invalid or not complete.

func (SharedConfigAssumeRoleError) Error

func (SharedConfigAssumeRoleError) Unwrap

Unwrap returns the underlying error that caused the failure.

type SharedConfigLoadError

type SharedConfigLoadError struct {
	Filename string
	Err      error
}

SharedConfigLoadError is an error for the shared config file failed to load.

func (SharedConfigLoadError) Error

func (e SharedConfigLoadError) Error() string

func (SharedConfigLoadError) Unwrap

func (e SharedConfigLoadError) Unwrap() error

Unwrap returns the underlying error that caused the failure.

type SharedConfigProfileNotExistError

type SharedConfigProfileNotExistError struct {
	Filename []string
	Profile  string
	Err      error
}

SharedConfigProfileNotExistError is an error for the shared config when the profile was not find in the config file.

func (SharedConfigProfileNotExistError) Error

func (SharedConfigProfileNotExistError) Unwrap

Unwrap returns the underlying error that caused the failure.

type UseEC2IMDSRegion

type UseEC2IMDSRegion struct {
	// If unset will default to generic EC2 IMDS client.
	Client *imds.Client
}

UseEC2IMDSRegion provides a regionProvider that retrieves the region from the EC2 Metadata service.