-
-
Save johnteee/9ca2e711433f36f8ed119fe953ba6522 to your computer and use it in GitHub Desktop.
how to get AWS credential from ECR with golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (c) 2019. Inception Asia | |
* Maintain by DigithunWorldwide ❤ | |
* Maintainer | |
* - [email protected] | |
* - [email protected] | |
*/ | |
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