github.com/mitchellh/packer@v1.3.2/builder/docker/ecr_login.go (about) 1 package docker 2 3 import ( 4 "encoding/base64" 5 "fmt" 6 "log" 7 "regexp" 8 "strings" 9 10 "github.com/aws/aws-sdk-go/aws" 11 "github.com/aws/aws-sdk-go/service/ecr" 12 "github.com/hashicorp/packer/builder/amazon/common" 13 ) 14 15 type AwsAccessConfig struct { 16 AccessKey string `mapstructure:"aws_access_key"` 17 SecretKey string `mapstructure:"aws_secret_key"` 18 Token string `mapstructure:"aws_token"` 19 Profile string `mapstructure:"aws_profile"` 20 cfg *common.AccessConfig 21 } 22 23 // Get a login token for Amazon AWS ECR. Returns username and password 24 // or an error. 25 func (c *AwsAccessConfig) EcrGetLogin(ecrUrl string) (string, string, error) { 26 27 exp := regexp.MustCompile(`(?:http://|https://|)([0-9]*)\.dkr\.ecr\.(.*)\.amazonaws\.com.*`) 28 splitUrl := exp.FindStringSubmatch(ecrUrl) 29 if len(splitUrl) != 3 { 30 return "", "", fmt.Errorf("Failed to parse the ECR URL: %s it should be on the form <account number>.dkr.ecr.<region>.amazonaws.com", ecrUrl) 31 } 32 accountId := splitUrl[1] 33 region := splitUrl[2] 34 35 log.Println(fmt.Sprintf("Getting ECR token for account: %s in %s..", accountId, region)) 36 37 c.cfg = &common.AccessConfig{ 38 AccessKey: c.AccessKey, 39 ProfileName: c.Profile, 40 RawRegion: region, 41 SecretKey: c.SecretKey, 42 Token: c.Token, 43 } 44 45 session, err := c.cfg.Session() 46 if err != nil { 47 return "", "", fmt.Errorf("failed to create session: %s", err) 48 } 49 50 service := ecr.New(session) 51 52 params := &ecr.GetAuthorizationTokenInput{ 53 RegistryIds: []*string{ 54 aws.String(accountId), 55 }, 56 } 57 resp, err := service.GetAuthorizationToken(params) 58 if err != nil { 59 return "", "", fmt.Errorf(err.Error()) 60 } 61 62 auth, err := base64.StdEncoding.DecodeString(*resp.AuthorizationData[0].AuthorizationToken) 63 if err != nil { 64 return "", "", fmt.Errorf("Error decoding ECR AuthorizationToken: %s", err) 65 } 66 67 authParts := strings.SplitN(string(auth), ":", 2) 68 log.Printf("Successfully got login for ECR: %s", ecrUrl) 69 70 return authParts[0], authParts[1], nil 71 }