AWS Go SDK 在 C:/###/ 找不到凭证文件。aws/credentials

AWS Go SDK not finding the credentials file at C:/###/.aws/credentials

我正在使用 Amazon Kinesis 和适用于 AWS 的 Go SDK,但出现错误。

这是我的代码:

package main

import (
    "math/rand"
    "strings"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    _kinesis "github.com/aws/aws-sdk-go/service/kinesis"
)

func main() {
    session, err := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1"),
    })

    handleErr(err)

    kinesis := _kinesis.New(session)

    laugh := strings.Builder{}
    laughingSounds := []string{"haha", "hoho", "hehe", "hehehe", "*snicker*"}

    for i := 0; i < 10; i++ {
        laugh.WriteString(laughingSounds[rand.Intn(len(laughingSounds))])
    }

    _, err = kinesis.PutRecord(&_kinesis.PutRecordInput{
        Data:         []byte(laugh.String()),
        PartitionKey: aws.String("laughs"),
        StreamName:   aws.String("laughs"),
    })

    handleErr(err)
}

func handleErr(err error) {
      if err != nil {
             panic(err)
      }
}

当我运行这个时,我得到一个错误:

panic: UnrecognizedClientException: The security token included in the request is invalid.
        status code: 400, request id: dc139793-cd38-fb30-86a3-f92b6410e1c7

goroutine 1 [running]:
main.handleErr(...)
        C:/Users/####/----/main.go:5
main.main()
        C:/Users/####/----/main.go:34 +0x3ac
exit status 2

我有 运行 aws configure:

$ aws configure
AWS Access Key ID [None]:  ####
AWS Secret Access Key [None]: ####
Default region name [None]: us-east-1
Default output format [None]: 

并且 C:/users/####/.aws/credentials 文件是使用正确的配置创建的。但是我的程序还是执行不成功

我尝试设置环境变量,但没有成功。

$ $env:aws_access_key_id="####"

版本信息:

$ pwsh -v
PowerShell 7.2.2
$ aws -v
aws-cli/2.4.27 Python/3.8.8 Windows/10 exe/AMD64 prompt/off

OS: Windows 11

我在 GoDoc 中找到了答案,我只需要更改配置设置并使用 NewSessionWithOptions:

session, err := session.NewSessionWithOptions(session.Options{
    Config: aws.Config{
        Region: aws.String("<your region>"),
    }, SharedConfigState: session.SharedConfigEnable,
})

确保 运行 aws configure 使用正确的凭据(或者甚至只是手动创建 ~/.aws/credentials 文件),否则这将不起作用。