docker ECR login (go-aws-sdk)

This commit is contained in:
2021-11-30 17:58:09 +01:00
parent 1071695e87
commit 46be715e9e
7 changed files with 131 additions and 2 deletions

View File

@ -0,0 +1,36 @@
package aws_ledo
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
"os"
)
func getRegion() string {
region, exists := os.LookupEnv("AWS_REGION")
if !exists {
fmt.Printf("AWS_REGION not set and unable to fetch region")
os.Exit(1)
}
return region
}
func EcrLogin() (*ecr.GetAuthorizationTokenOutput, error) {
var input *ecr.GetAuthorizationTokenInput
var token *ecr.GetAuthorizationTokenOutput
config := &aws.Config{
Region: aws.String(getRegion()),
}
sess, _ := session.NewSession(config)
_, err := sess.Config.Credentials.Get()
if err != nil {
return token, err
}
ecrCtx := ecr.New(sess)
token, err = ecrCtx.GetAuthorizationToken(input)
return token, nil
}

View File

@ -81,3 +81,11 @@ func (lx *LedoContext) ExecCmd(cmd string, cmdArgs []string) error {
command.Stderr = os.Stderr
return command.Run()
}
func (lx *LedoContext) ExecCmdSilent(cmd string, cmdArgs []string) error {
command := exec.Command(cmd, cmdArgs...)
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
return command.Run()
}

View File

@ -0,0 +1,40 @@
package docker
import (
b64 "encoding/base64"
"fmt"
"ledo/app/modules/aws_ledo"
"ledo/app/modules/context"
"net/url"
"os"
)
func trimLeftChars(s string, n int) string {
m := 0
for i := range s {
if m >= n {
return s[i:]
}
m++
}
return s[:0]
}
func DockerEcrLogin(ctx *context.LedoContext) error {
ecr, err := aws_ledo.EcrLogin()
if err != nil {
fmt.Println("Ecr login error: %s", err)
os.Exit(1)
}
password := *ecr.AuthorizationData[0].AuthorizationToken
ecrUrl := *ecr.AuthorizationData[0].ProxyEndpoint
sDec, _ := b64.StdEncoding.DecodeString(password)
registryAddr, err := url.Parse(ecrUrl)
if err != nil {
fmt.Printf("Ecr endpoint addr parse error: %s", err)
os.Exit(1)
}
ctx.ExecCmdSilent("docker", []string{"login", "-u", "AWS", "-p", string(trimLeftChars(string(sDec), 4)), registryAddr.Host})
return nil
}