-
Notifications
You must be signed in to change notification settings - Fork 1
/
ecr.go
94 lines (87 loc) · 2.47 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package amazon
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
)
// GetAccountID returns the current account ID
func GetAccountIDAndRegion(profile string, region string) (string, string, error) {
sess, err := NewAwsSession(profile, region)
region = *sess.Config.Region
if err != nil {
return "", region, err
}
svc := sts.New(sess)
input := &sts.GetCallerIdentityInput{}
result, err := svc.GetCallerIdentity(input)
if err != nil {
return "", region, err
}
if result.Account != nil {
return *result.Account, region, nil
}
return "", region, fmt.Errorf("Could not find the AWS Account ID!")
}
// GetContainerRegistryHost
func GetContainerRegistryHost() (string, error) {
accountId, region, err := GetAccountIDAndRegion("", "")
if err != nil {
return "", err
}
return accountId + ".dkr.ecr." + region + ".amazonaws.com", nil
}
// LazyCreateRegistry lazily creates the ECR registry if it does not already exist
func LazyCreateRegistry(orgName string, appName string) error {
// strip any tag/version from the app name
idx := strings.Index(appName, ":")
if idx > 0 {
appName = appName[0:idx]
}
repoName := appName
if orgName != "" {
repoName = orgName + "/" + appName
}
repoName = strings.ToLower(repoName)
log.Infof("Let's ensure that we have an ECR repository for the Docker image %s\n", util.ColorInfo(repoName))
sess, err := NewAwsSessionWithoutOptions()
if err != nil {
return err
}
svc := ecr.New(sess)
repoInput := &ecr.DescribeRepositoriesInput{
RepositoryNames: []*string{
aws.String(repoName),
},
}
result, err := svc.DescribeRepositories(repoInput)
if aerr, ok := err.(awserr.Error); !ok || aerr.Code() != ecr.ErrCodeRepositoryNotFoundException {
return err
}
for _, repo := range result.Repositories {
name := repo.String()
log.Infof("Found repository: %s\n", name)
if name == repoName {
return nil
}
}
createRepoInput := &ecr.CreateRepositoryInput{
RepositoryName: aws.String(repoName),
}
createResult, err := svc.CreateRepository(createRepoInput)
if err != nil {
return fmt.Errorf("Failed to create the ECR repository for %s due to: %s", repoName, err)
}
repo := createResult.Repository
if repo != nil {
u := repo.RepositoryUri
if u != nil {
log.Infof("Created ECR repository: %s\n", util.ColorInfo(*u))
}
}
return nil
}