How to run AWS SDK with credentials from variables?

huangapple go评论76阅读模式
英文:

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 的调用中?

英文:

I used environment variables before and it worked fine.

Now I am migrating my config variables into a single file and I have AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID variables containing respective values that are loaded from this file.

I tried this code but receiving an error:

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

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

How do I properly inject my keys into the aws sdk calls?

答案1

得分: 43

尝试重新调整参数的顺序,将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, ""),
})
英文:

Try re-ordering your args so that ACCESS_KEY is the 1st param and SECRET_KEY is the second:

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

Try adding the region as well:

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, ""),
})

答案2

得分: 5

或者你可以暂时设置环境变量。

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)
	}
}
英文:

Or you can just temporaly set Environment variables.

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)
	}
}

答案3

得分: 4

另外,如果你不知道的话,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
英文:

Additionally, if you hadn't known, the SDK allows for the use of the shared config under .aws/config. You can put your values in there and then set the environment variable AWS_SDK_LOAD_CONFIG to a truthy value to load the shared config. An example shared config would look like this:

[default]
aws_access_key_id = AKID
aws_secret_access_key = SECRET

Then running:

AWS_SDK_LOAD_CONFIG=true go run main.go

答案4

得分: 0

你可以将creds变量传递给aws.Config结构体,以设置S3会话的AWS凭证。

> 你需要导入github.com/aws/aws-sdk-go/aws/credentials包。

package main

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
)

func main() {
	accessKey := "ACCESS"
	secretKey := "SECRET"
	creds := credentials.NewStaticCredentials(accessKey, secretKey, "")

	sess, err := session.NewSession(&aws.Config{
		Credentials: creds,
		Endpoint:    aws.String("ENDPOINT"),
		Region:      aws.String("REGION"),
	})
	if err != nil {
		panic(err)
	}

	svc := s3.New(sess)

	bucketName := "ramingotestsdk"

	_, err = svc.CreateBucket(&s3.CreateBucketInput{
		Bucket: aws.String(bucketName),
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("Bucket %s created\n", bucketName)
}

输出:

Bucket ramingotestsdk created
英文:

You can pass the creds variable to the aws.Config struct to set the AWS credentials for the S3 session.

> You need to import the github.com/aws/aws-sdk-go/aws/credentials package.

package main

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
)

func main() {
	accessKey := "ACCESS"
	secretKey := "SECRET"
	creds := credentials.NewStaticCredentials(accessKey, secretKey, "")

	sess, err := session.NewSession(&aws.Config{
		Credentials: creds,
		Endpoint:    aws.String("ENDPOINT"),
		Region:      aws.String("REGION"),
	})
	if err != nil {
		panic(err)
	}

	svc := s3.New(sess)

	bucketName := "ramingotestsdk"

	_, err = svc.CreateBucket(&s3.CreateBucketInput{
		Bucket: aws.String(bucketName),
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("Bucket %s created\n", bucketName)
}

OUTPUT:

Bucket ramingotestsdk created

答案5

得分: 0

你可以使用aws.Credentials结构中的配置选项,如下面的代码片段所示。

package services

import (
	"context"
	"fmt"
	"ldapmng/config"
	"time"

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

type AwsService struct {
	Ds *directoryservice.Client
}

func NewAwsService(ctx context.Context) (*AwsService, error) {

	awsService := &AwsService{}

	settings, _ := config.LoadSettings()

	awsSessionExpiration, err := time.Parse("2006-01-02T15:04:05-07:00", settings.AwsSessionExpiration)

	creds := aws.Credentials{
		AccessKeyID:     settings.AwsAccessKeyId,
		SecretAccessKey: settings.AwsSecretAccessKey,
		SessionToken:    settings.AwsSessionToken,
		// Source:          ,
		// CanExpire:       false,
		Expires: awsSessionExpiration,
	}

	credsProvider := credentials.StaticCredentialsProvider{
		Value: creds,
	}

	cfg := aws.Config{
		Region:      settings.AwsRegion,
		Credentials: credsProvider,
	}

	if err != nil {
		fmt.Println("Error loading AWS configuration:", err)
		return nil, err
	}

	awsService.Ds = directoryservice.NewFromConfig(cfg)

	return awsService, nil
}

这段代码展示了如何在aws.Credentials结构中利用你的配置选项。你可以根据自己的需求填写AccessKeyIDSecretAccessKeySessionToken等字段,然后将其传递给aws.ConfigCredentials字段。这样,你就可以使用这些配置创建一个directoryservice.Client对象。

英文:

Hi you have the option to utilize your configurations within an aws.Credentials struct, as demonstrated in the code snippet below.

package services
import (
"context"
"fmt"
"ldapmng/config"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/directoryservice"
)
type AwsService struct {
Ds *directoryservice.Client
}
func NewAwsService(ctx context.Context) (*AwsService, error) {
awsService := &AwsService{}
settings, _ := config.LoadSettings()
awsSessionExpiration, err := time.Parse("2006-01-02T15:04:05-07:00", settings.AwsSessionExpiration)
creds := aws.Credentials{
AccessKeyID:     settings.AwsAccessKeyId,
SecretAccessKey: settings.AwsSecretAccessKey,
SessionToken:    settings.AwsSessionToken,
// Source:          ,
// CanExpire:       false,
Expires: awsSessionExpiration,
}
credsProvider := credentials.StaticCredentialsProvider{
Value: creds,
}
cfg := aws.Config{
Region:      settings.AwsRegion,
Credentials: credsProvider,
}
if err != nil {
fmt.Println("Error loading AWS configuration:", err)
return nil, err
}
awsService.Ds = directoryservice.NewFromConfig(cfg)
return awsService, nil
}

答案6

得分: -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", ""),
	}))
}

请注意,这是一个使用AWS SDK的Go代码示例,用于初始化AWS会话并连接到服务。在代码中,您需要将YOUR_ACCESS_KEYYOUR_SECRET_KEY替换为您自己的访问密钥和秘密密钥。此外,您还可以根据需要更改Region参数以适应您的特定区域。

英文:

Connect your sdk client using this generic service

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", ""),
}))
}

huangapple
  • 本文由 发表于 2017年1月9日 17:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41544554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定