-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
194 lines (165 loc) · 4.67 KB
/
main.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io/ioutil"
"strings"
"text/template"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
log "github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const appVersion = "0.1.0"
const cfgTemplate = `{
"auths": {
"{{ .registry }}": {
"auth": "{{ .token }}"
}
}
}`
func init() {
log.SetFormatter(&log.JSONFormatter{})
}
func main() {
log.Infof("appVersion: %s", appVersion)
// Flags
region := flag.String("region", "", "The aws region")
interval := flag.Int("interval", 1200, "Refresh interval in seconds")
profile := flag.String("profile", "", "The AWS Account profile")
secretName := flag.String("secretName", "ecr-auth-cfg", "The name of the secret")
secretTypeName := flag.String("secretType", "Opaque", fmt.Sprintf("The secret type, available options: (%s|%s|%s)",
v1.SecretTypeOpaque, v1.SecretTypeDockerConfigJson, v1.SecretTypeDockercfg))
flag.Parse()
log.Infof("Flags: region=%s, interval=%d, profile=%s, secretName=%s, secretType=%s",
*region, *interval, *profile, *secretName, *secretTypeName)
secretType, err := parseSecretType(*secretTypeName)
if err != nil {
panic(err.Error())
}
// Validate important variables
if *region == "" {
panic("Region not specified")
}
// Start a new aws client session
sess := session.Must(session.NewSession(&aws.Config{
Region: region,
}))
svc := ecr.New(sess)
for {
// Get the ECR authorization token from AWS
tokenInput := &ecr.GetAuthorizationTokenInput{}
if *profile != "" {
tokenInput.RegistryIds = []*string{profile}
}
token, err := svc.GetAuthorizationToken(tokenInput)
if err != nil {
panic(err.Error())
}
// Create the docker config.json in buffer
dockerCfg, err := createDockerCfg(token)
// Get current namespace
namespace, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
panic(err.Error())
}
// Create the docker config.json as a kubernetes secret
kconfig, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
clientSet, err := kubernetes.NewForConfig(kconfig)
if err != nil {
panic(err.Error())
}
kclient := &kubernetesAPI{client: clientSet}
err = kclient.applyDockerCfgSecret(dockerCfg, *secretName, string(namespace), secretType)
if err != nil {
panic(err.Error())
}
// sleep interval
time.Sleep(time.Duration(*interval) * time.Second)
}
}
func createDockerCfg(ecrToken *ecr.GetAuthorizationTokenOutput) ([]byte, error) {
if len(ecrToken.AuthorizationData) < 1 {
return nil, errors.New("authorization data should have at least 1 auth data")
}
cfgData := map[string]string{}
cfgData["registry"] = *ecrToken.AuthorizationData[0].ProxyEndpoint
cfgData["token"] = *ecrToken.AuthorizationData[0].AuthorizationToken
// Put the config template output in a buffer
t := template.Must(template.New("").Parse(cfgTemplate))
cfgBuffer := bytes.NewBufferString("")
if err := t.Execute(cfgBuffer, cfgData); err != nil {
return nil, err
}
cfgInByte, err := ioutil.ReadAll(cfgBuffer)
if err != nil {
return nil, err
}
return cfgInByte, nil
}
type kubernetesAPI struct {
client kubernetes.Interface
}
func (k *kubernetesAPI) applyDockerCfgSecret(cfg []byte, secretName, namespace string, kind v1.SecretType) error {
var data map[string][]byte
switch kind {
case v1.SecretTypeDockerConfigJson:
data = map[string][]byte{
string(v1.DockerConfigJsonKey): cfg,
}
case v1.SecretTypeDockercfg:
data = map[string][]byte{
string(v1.DockerConfigKey): cfg,
}
default:
data = map[string][]byte{
"config.json": cfg,
}
}
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
},
Data: data,
Type: kind,
}
log.Infoln("creating kubernetes secret")
secretClient := k.client.CoreV1().Secrets(namespace)
result, err := secretClient.Update(secret)
actionTaken := "updated"
if err != nil {
if strings.Contains(err.Error(), "not found") {
result, err = secretClient.Create(secret)
if err != nil {
return err
}
actionTaken = "created"
} else {
return err
}
}
log.Infof("%s kubernetes secret: %s", actionTaken, result.GetObjectMeta().GetName())
return nil
}
func parseSecretType(s string) (v1.SecretType, error) {
switch v1.SecretType(s) {
case v1.SecretTypeOpaque:
return v1.SecretTypeOpaque, nil
case v1.SecretTypeDockerConfigJson:
return v1.SecretTypeDockerConfigJson, nil
case v1.SecretTypeDockercfg:
return v1.SecretTypeDockercfg, nil
default:
return "", fmt.Errorf("unmatched secret type: %s", s)
}
}