How to run AWS SDK with credentials from variables?
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, ""),
})
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
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)
}
}