如何 运行 AWS SDK 使用来自变量的凭据?

How to run AWS SDK with credentials from variables?

我之前用过环境变量,效果很好。

现在我将我的配置变量迁移到一个文件中,并且我有 AWS_SECRET_ACCESS_KEY 和 AWS_ACCESS_KEY_ID 变量包含从该文件加载的相应值。

我试过此代码但收到错误消息:

creds := credentials.NewStaticCredentials("123", conf.AWS_SECRET_ACCESS_KEY, conf.AWS_ACCESS_KEY_ID)
sess, err := session.NewSession(&aws.Config{Credentials: creds})

这里是错误

InvalidClientTokenId: The security token included in the request is invalid.

如何正确地将我的密钥注入 aws sdk 调用?

尝试重新排序您的参数,使 ACCESS_KEY 是第一个参数,SECRET_KEY 是第二个:

creds := credentials.NewStaticCredentials(conf.AWS_ACCESS_KEY_ID, conf.AWS_SECRET_ACCESS_KEY, "")

也尝试添加区域:

sess, err := session.NewSession(&aws.Config{
    Region:      aws.String("us-west-2"),
    Credentials: credentials.NewStaticCredentials(conf.AWS_ACCESS_KEY_ID, conf.AWS_SECRET_ACCESS_KEY, ""),
})

此外,如果您不知道,SDK 允许使用 .aws/config 下的共享配置。您可以将您的值放在那里,然后将环境变量 AWS_SDK_LOAD_CONFIG 设置为真值以加载共享配置。示例共享配置如下所示:

[default]
aws_access_key_id = AKID
aws_secret_access_key = SECRET

然后运行:

AWS_SDK_LOAD_CONFIG=true go run main.go

或者您可以临时设置环境变量。

package main
import (
    "fmt"
    "os"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
)

const (
    AccessKeyId     = "XXXXXXXXXXXXXXXXXX"
    SecretAccessKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    Region          = "eu-west-1"
    Bucket          = "XXXXX-XXXX-XXX"
)

func main() {
    os.Setenv("AWS_ACCESS_KEY_ID",     AccessKeyId)
    os.Setenv("AWS_SECRET_ACCESS_KEY", SecretAccessKey)

    filename := os.Args[1]

    file, err := os.Open(filename)
    if err != nil {
        fmt.Println("Failed to open file", filename, err)
        os.Exit(1)
    }
    defer file.Close()

    conf := aws.Config{Region: aws.String(Region)}
    sess := session.New(&conf)

    svc := s3manager.NewUploader(sess)

    fmt.Println("Uploading file to S3...")
    result, err := svc.Upload(&s3manager.UploadInput{
        Bucket: aws.String(Bucket),
        Key:    aws.String(filepath.Base(filename)),
        Body:   file,
    })
    if err != nil {
        fmt.Println("error", err)
        os.Exit(1)
    }
}

使用此通用服务连接您的 SDK 客户端

var awsSession *session.Session

func init() {
    initializeAwsSession()
}


func initializeAwsSession() {
    awsSession = session.Must(session.NewSession(&aws.Config{
        Region:      aws.String("ap-southeast-1"),
        Credentials: credentials.NewStaticCredentials("YOUR_ACCESS_KEY","YOUR SECRET_KEY", ""),
    }))
}