Skip to content

Instantly share code, notes, and snippets.

@zapkub
Last active March 7, 2024 07:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zapkub/fb3b12c229952d79e6cbf4d1186a8186 to your computer and use it in GitHub Desktop.
Save zapkub/fb3b12c229952d79e6cbf4d1186a8186 to your computer and use it in GitHub Desktop.
how to get AWS credential from ECR with golang
/*
* Copyright (c) 2019. Inception Asia
* Maintain by DigithunWorldwide ❤
* Maintainer
* - rungsikorn.r@digithunworldwide.com
* - nipon.chi@digithunworldwide.com
*/
package util
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"io/ioutil"
"net/http"
"os"
)
type ContainerCredentialProvider struct{}
func (m *ContainerCredentialProvider) Retrieve() (credentials.Value, error) {
awsContainerURI := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
if len(awsContainerURI) < 1 {
fmt.Println("[AWS] ECS URI not found, SKIP THIS IF YOU RUNNING OUTSIDE ECS")
return credentials.Value{}, errors.New("No ECS URI")
}
ecsCredentialURL := fmt.Sprintf("http://169.254.170.2%s", awsContainerURI)
r, err := http.Get(ecsCredentialURL)
if err != nil {
panic(err)
}
defer r.Body.Close()
b, _ := ioutil.ReadAll(r.Body)
fmt.Println("Result")
awsID := gjson.Get(string(b), "AccessKeyId").String()
awsSecret := gjson.Get(string(b), "SecretAccessKey").String()
awsToken := gjson.Get(string(b), "Token").String()
return credentials.Value{
SecretAccessKey: awsSecret,
SessionToken: awsToken,
AccessKeyID: awsID,
ProviderName: "ECS Container Credential",
}, nil
}
func (m *ContainerCredentialProvider) IsExpired() bool {
return false
}
type AWSConfigOptions struct {
AWS *aws.Config
AWSAccountID string
AWSAccountSecret string
}
// Prepare will block thread until it complete gathering resource
func NewAWSConfig(opts AWSConfigOptions) *aws.Config {
fmt.Println("[AWS] init aws config...")
fmt.Printf("Config\nID:%s\nSecret:%s\n", opts.AWSAccountID, opts.AWSAccountSecret)
awsConfig := aws.Config{
Region: aws.String("ap-southeast-1"),
Credentials: credentials.NewChainCredentials([]credentials.Provider{
&ContainerCredentialProvider{},
&credentials.StaticProvider{
Value: credentials.Value{
ProviderName: "User define",
AccessKeyID: opts.AWSAccountID,
SessionToken: "",
SecretAccessKey: opts.AWSAccountSecret,
},
},
}),
}
return &awsConfig
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment