9

我正在编写一个 go 函数来从 AWS S3 存储桶下载文件。

func DownloadFromS3Bucket() {
    bucket := "cellery-runtime-installation"
    item := "hello-world.txt"

    file, err := os.Create(item)
    if err != nil {
        fmt.Println(err)
    }

    defer file.Close()

    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, _ := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1")},
    )

    downloader := s3manager.NewDownloader(sess)

    numBytes, err := downloader.Download(file,
        &s3.GetObjectInput{
            Bucket: aws.String(bucket),
            Key:    aws.String(item),
        })
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
}

但是,我收到一条要求提供凭据的错误消息。

NoCredentialProviders:链中没有有效的提供者。已弃用。有关详细消息,请参阅 aws.Config.CredentialsChainVerboseErrors

该文档没有具体说明如何设置凭据。(访问密钥 ID,秘密访问密钥)

任何想法?

4

2 回答 2

7

有几种方法可以设置凭据。有关更多详细信息aws/credentials

例如,您可以通过设置环境变量来指定它:

AWS_ACCESS_KEY = <your_access_key>
AWS_SECRET_KEY = <your_secret_key>

然后只需credentials.NewEnvCredentials()在您的配置实例中使用:

sess, _ := session.NewSession(&aws.Config{
    Region:      aws.String("us-east-1"),
    Credentials: credentials.NewEnvCredentials(),
})
于 2019-01-28T12:04:52.607 回答
3

只需设置AWS_ACCESS_KEYAWS_SECRET_KEY环境变量(您不需要调用- 您所做的是完美的)credentials.NewEnvCredentials()session.NewSession

func DownloadFromS3Bucket() {
    
    os.Setenv("AWS_ACCESS_KEY","my-key")
    os.Setenv("AWS_SECRET_KEY","my-secret")

    bucket := "cellery-runtime-installation"
    item := "hello-world.txt"

    file, err := os.Create(item)
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()

    sess, _ := session.NewSession(&aws.Config{Region: aws.String("us-east-1")})
    downloader := s3manager.NewDownloader(sess)
    numBytes, err := downloader.Download(file,
        &s3.GetObjectInput{
            Bucket: aws.String(bucket),
            Key:    aws.String(item),
        })
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
}

这是来自 AWS Go SDK 的完整示例:https ://github.com/awsdocs/aws-doc-sdk-examples/blob/master/go/example_code/s3/s3_download_object.go

我写了一篇关于如何测试 S3 下载器的博客文章,并创建了一个可测试的 S3 存储桶扫描器,它列出了所有存储桶的文件并临时下载每个文件,请参阅:https ://medium.com/@tufin/a-testable-go -aws-s3-scanner-e54de0c26197

在这里你可以找到代码:https ://github.com/Tufin/blog/tree/master/s3-scanner

于 2020-07-19T18:24:33.803 回答