/
ecr.go
77 lines (62 loc) · 1.79 KB
/
ecr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package aws
import (
"encoding/base64"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
)
const (
EC2RoleDockerRegistryAuth = "aws-ec2-role"
)
type ECRRegistryAuthProvider struct{}
func (p *ECRRegistryAuthProvider) GetLoginCredentials(registryURI string) (string, string, error) {
registry, err := parseECRRegistryURI(registryURI)
if err != nil {
return "", "", err
}
svc, err := getECR(registry.region)
if err != nil {
return "", "", err
}
input := &ecr.GetAuthorizationTokenInput{
RegistryIds: []*string{®istry.accountID},
}
output, err := svc.GetAuthorizationToken(input)
if err != nil {
return "", "", err
}
if len(output.AuthorizationData) != 1 {
return "", "", fmt.Errorf("expected 1 authorization token, got %v", len(output.AuthorizationData))
}
creds, err := base64.StdEncoding.DecodeString(*output.AuthorizationData[0].AuthorizationToken)
splitCreds := strings.Split(string(creds), ":")
if len(splitCreds) != 2 {
return "", "", fmt.Errorf("unexpected format for authorization creds")
}
return splitCreds[0], splitCreds[1], nil
}
func getECR(region string) (*ecr.ECR, error) {
sess, err := session.NewSession(&aws.Config{Region: ®ion})
if err != nil {
return nil, nil
}
return ecr.New(sess), nil
}
type ecrRegistry struct {
accountID string
region string
}
func parseECRRegistryURI(registryURI string) (ecrRegistry, error) {
// Example ECR registry: <account_id>.dkr.ecr.us-east-1.amazonaws.com
registryParts := strings.Split(registryURI, ".")
if len(registryParts) != 6 {
return ecrRegistry{}, fmt.Errorf("invalid ECR registry URI: %v", registryURI)
}
registry := ecrRegistry{
accountID: registryParts[0],
region: registryParts[3],
}
return registry, nil
}