cannot use &cfg (value of type *aws.Config) as *aws.Config value in argument to session.NewSession

Issue

I’m trying to get a new AWS Session like this:

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

awsSession, err := session.NewSession(&cfg)
if err != nil {
    log.Fatal(err)
}

But I get a confusing (at least to me) error:

cannot use &cfg (value of type *aws.Config) as *aws.Config value in argument to session.NewSession

The signature of NewSession() looks like this:

func NewSession(cfgs ...*aws.Config) (*Session, error)

Does the fact that NewSession() is a variadic function play any role in producing this error?

Why does the error go away if I pass a literal aws.Config{} like this?

awsSession, err := session.NewSession(&aws.Config{})

Solution

You’re mixing up AWS SDK versions.

The package session exists in AWS SDK v1 with import path github.com/aws/aws-sdk-go/aws/session and expects arguments of type "github.com/aws/aws-sdk-go/aws".Config. It does not exist in AWS SDK v2.

The config package you were loading your configs from instead is from AWS SDK v2 with import path github.com/aws/aws-sdk-go-v2/config therefore LoadDefaultConfigs returns "github.com/aws/aws-sdk-go-v2/config".Config.

These are not the same type and the compiler is telling you that (albeit with a partially useful error message).

You have to keep your AWS SDK versions consistent. With v2, you are supposed to instantiate the specific AWS services with the config, instead of a session. For example s3.New(&cfg).

Answered By – blackgreen

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.