Skip to content

Instantly share code, notes, and snippets.

@johnteee
Forked from zapkub/aws-ecr-credential.go
Created March 7, 2024 07:52
Show Gist options
  • Save johnteee/9ca2e711433f36f8ed119fe953ba6522 to your computer and use it in GitHub Desktop.
Save johnteee/9ca2e711433f36f8ed119fe953ba6522 to your computer and use it in GitHub Desktop.

Revisions

  1. @zapkub zapkub revised this gist Mar 5, 2019. No changes.
  2. @zapkub zapkub created this gist Mar 5, 2019.
    85 changes: 85 additions & 0 deletions aws-ecr-credential.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@
    /*
    * 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
    }