/
clients.go
483 lines (403 loc) · 13.4 KB
/
clients.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package aws
import (
"context"
"fmt"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/acm"
acmtypes "github.com/aws/aws-sdk-go-v2/service/acm/types"
"github.com/aws/aws-sdk-go-v2/service/route53"
route53types "github.com/aws/aws-sdk-go-v2/service/route53/types"
"github.com/go-logr/logr"
)
// Clients wrapper for AWS
type Clients struct {
Log logr.Logger
Config aws.Config
Route53 *route53.Client
}
func (c Clients) Region(region string) string {
if region != "" {
return region
}
return c.Config.Region
}
func (c Clients) Acm(region string) *acm.Client {
region = c.Region(region)
cfg, _ := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
return acm.NewFromConfig(cfg)
}
var unescaper = strings.NewReplacer(`\057`, "/", `\052`, "*")
type UniqueConstraintException struct {
message string
}
func (e *UniqueConstraintException) Error() string {
return e.message
}
// FindOneAcmCertificateByDomainName returns the first matching ACM Certificate by domain name
func (c Clients) FindOneAcmCertificateByDomainName(ctx context.Context, region string, domainName string) (*acmtypes.CertificateSummary, error) {
items, err := c.ListAcmCertificates(ctx, region)
if err != nil {
return nil, err
}
matches := make([]acmtypes.CertificateSummary, 0)
for _, cert := range items {
match := *cert.DomainName == domainName
if match {
matches = append(matches, cert)
}
}
if len(matches) == 1 {
return &matches[0], nil
}
if len(matches) > 0 {
return nil, &UniqueConstraintException{
message: fmt.Sprintf("multiple certificates found matching the domain name %s", domainName),
}
}
return nil, nil
}
// FindAcmCertificatesByDomainName returns the first matching ACM Certificate by domain name
func (c Clients) FindAcmCertificatesByDomainName(ctx context.Context, region string, domainName string) ([]acmtypes.CertificateSummary, error) {
items, err := c.ListAcmCertificates(ctx, region)
if err != nil {
return nil, err
}
matches := make([]acmtypes.CertificateSummary, 0)
for _, cert := range items {
match := *cert.DomainName == domainName
if match {
matches = append(matches, cert)
}
}
return matches, nil
}
// GetAcmCertificateDetailsByArn returns ACM Certificate details by ARN
func (c Clients) GetAcmCertificateDetailsByArn(ctx context.Context, region string, arn string) (acmtypes.CertificateDetail, error) {
res, err := c.Acm(region).DescribeCertificate(ctx, &acm.DescribeCertificateInput{
CertificateArn: aws.String(arn),
})
if err != nil {
return acmtypes.CertificateDetail{}, err
}
return *res.Certificate, nil
}
// ListAcmCertificates returns all ACM Certificates
func (c Clients) ListAcmCertificates(ctx context.Context, region string) ([]acmtypes.CertificateSummary, error) {
items := make([]acmtypes.CertificateSummary, 0)
paginator := acm.NewListCertificatesPaginator(c.Acm(region), &acm.ListCertificatesInput{
MaxItems: aws.Int32(5),
})
for paginator.HasMorePages() {
output, err := paginator.NextPage(ctx)
if err != nil {
return nil, err
}
items = append(items, output.CertificateSummaryList...)
}
return items, nil
}
// SetAcmCertificateTagsByArn adds, removes and updates tags for the ACM Certificate by ARN
func (c Clients) SetAcmCertificateTagsByArn(ctx context.Context, region string, arn string, tags map[string]string) error {
rc := c.Acm(region)
tagsRes, err := rc.ListTagsForCertificate(ctx, &acm.ListTagsForCertificateInput{
CertificateArn: aws.String(arn),
})
if err != nil {
return err
}
remove := make([]acmtypes.Tag, 0)
add := make([]acmtypes.Tag, 0)
for _, tag := range tagsRes.Tags {
if val, ok := tags[*tag.Key]; ok {
if *tag.Value != val {
remove = append(remove, tag)
}
} else {
remove = append(remove, tag)
}
}
for key, value := range tags {
add = append(add, acmtypes.Tag{
Key: aws.String(key),
Value: aws.String(value),
})
}
if len(remove) > 0 {
_, err := rc.RemoveTagsFromCertificate(ctx, &acm.RemoveTagsFromCertificateInput{
CertificateArn: aws.String(arn),
Tags: remove,
})
if err != nil {
return err
}
}
if len(add) > 0 {
_, err := rc.AddTagsToCertificate(ctx, &acm.AddTagsToCertificateInput{
CertificateArn: aws.String(arn),
Tags: add,
})
if err != nil {
return err
}
}
return nil
}
// ListAcmCertificateTagsByArn lists tags for the ACM Certificate by ARN
func (c Clients) ListAcmCertificateTagsByArn(ctx context.Context, region string, arn string) (tags map[string]string, err error) {
tags = make(map[string]string)
tagsRes, err := c.Acm(region).ListTagsForCertificate(ctx, &acm.ListTagsForCertificateInput{
CertificateArn: aws.String(arn),
})
if err != nil {
return tags, err
}
for _, tag := range tagsRes.Tags {
tags[*tag.Key] = *tag.Value
}
return tags, nil
}
// FindOneRoute53HostedZoneByName returns the first matching Route53 HostedZone by name
func (c Clients) FindOneRoute53HostedZoneByName(ctx context.Context, name string) (*route53types.HostedZone, error) {
items, err := c.ListRoute53HostedZones(ctx)
if err != nil {
return nil, err
}
matches := make([]route53types.HostedZone, 0)
for _, zone := range items {
match := *zone.Name == name+"."
if match {
matches = append(matches, zone)
}
}
if len(matches) == 1 {
return &matches[0], nil
}
if len(matches) > 0 {
return nil, &UniqueConstraintException{
message: fmt.Sprintf("multiple hosted zones found matching the name %s", name),
}
}
return nil, nil
}
// FindRoute53HostedZonesByName returns the matching Route53 HostedZones by name
func (c Clients) FindRoute53HostedZonesByName(ctx context.Context, name string) ([]route53types.HostedZone, error) {
items, err := c.ListRoute53HostedZones(ctx)
if err != nil {
return nil, err
}
matches := make([]route53types.HostedZone, 0)
for _, zone := range items {
match := *zone.Name == name+"."
if match {
matches = append(matches, zone)
}
}
return matches, nil
}
// GetRoute53HostedZoneById returns Route53 HostedZone by ID
func (c Clients) GetRoute53HostedZoneById(ctx context.Context, id string) (route53types.HostedZone, error) {
res, err := c.Route53.GetHostedZone(ctx, &route53.GetHostedZoneInput{
Id: aws.String(id),
})
if err != nil {
return route53types.HostedZone{}, err
}
return *res.HostedZone, nil
}
// DeleteRoute53HostedZone deletes a Route53 HostedZone by ID
func (c Clients) DeleteRoute53HostedZone(ctx context.Context, hostedZone route53types.HostedZone, force bool) error {
if force {
c.Log.V(1).Info("purging AWS Route53 HostedZone before deletion", "hosted-zone", hostedZone.Id)
recordSetList, err := c.ListRoute53ResourceRecordSets(ctx, *hostedZone.Id)
if err != nil {
return err
}
changes := make([]route53types.Change, 0)
for _, rs := range recordSetList {
rs := rs
if !isRoute53HostedZoneDefaultRecord(hostedZone, rs) {
change := route53types.Change{
Action: route53types.ChangeActionDelete,
ResourceRecordSet: &rs,
}
changes = append(changes, change)
}
}
if len(changes) > 0 {
params := route53.ChangeResourceRecordSetsInput{
HostedZoneId: hostedZone.Id,
ChangeBatch: &route53types.ChangeBatch{
Changes: changes,
Comment: aws.String("purging AWS Route53 HostedZone, cleaning up all resource record sets"),
},
}
res, err := c.Route53.ChangeResourceRecordSets(ctx, ¶ms)
if err != nil {
return err
}
c.WaitForRoute53Change(ctx, res.ChangeInfo)
c.Log.Info(fmt.Sprintf("deleted %d resource record sets from AWS Route53 HostedZone", len(changes)), "hosted-zone", hostedZone.Id)
}
}
res, err := c.Route53.DeleteHostedZone(ctx, &route53.DeleteHostedZoneInput{
Id: hostedZone.Id,
})
if err != nil {
return err
}
c.WaitForRoute53Change(ctx, res.ChangeInfo)
return nil
}
// ListRoute53HostedZones returns all Route53 HostedZones
func (c Clients) ListRoute53HostedZones(ctx context.Context) ([]route53types.HostedZone, error) {
items := make([]route53types.HostedZone, 0)
paginator := route53.NewListHostedZonesPaginator(c.Route53, &route53.ListHostedZonesInput{})
for paginator.HasMorePages() {
output, err := paginator.NextPage(ctx)
if err != nil {
return nil, err
}
items = append(items, output.HostedZones...)
}
return items, nil
}
// ListRoute53HostedZoneTagsById lists tags for the Route53 HostedZone by Id
func (c Clients) ListRoute53HostedZoneTagsById(ctx context.Context, id string) (tags map[string]string, err error) {
id = strings.ReplaceAll(id, "/hostedzone/", "")
tags = make(map[string]string)
tagsRes, err := c.Route53.ListTagsForResource(ctx, &route53.ListTagsForResourceInput{
ResourceType: route53types.TagResourceTypeHostedzone,
ResourceId: aws.String(id),
})
if err != nil {
return tags, err
}
for _, tag := range tagsRes.ResourceTagSet.Tags {
tags[*tag.Key] = *tag.Value
}
return tags, nil
}
// ListRoute53ResourceRecordSets returns all Route53 record sets for a HostedZone
func (c Clients) ListRoute53ResourceRecordSets(ctx context.Context, hostedZoneID string) ([]route53types.ResourceRecordSet, error) {
items := make([]route53types.ResourceRecordSet, 0)
req := route53.ListResourceRecordSetsInput{
HostedZoneId: aws.String(hostedZoneID),
}
for {
var resp *route53.ListResourceRecordSetsOutput
resp, err := c.Route53.ListResourceRecordSets(ctx, &req)
if err != nil {
return items, err
} else {
items = append(items, resp.ResourceRecordSets...)
if resp.IsTruncated {
req.StartRecordName = resp.NextRecordName
req.StartRecordType = resp.NextRecordType
req.StartRecordIdentifier = resp.NextRecordIdentifier
} else {
break
}
}
}
// unescape wildcards
for _, rrset := range items {
rrset.Name = aws.String(unescaper.Replace(*rrset.Name))
}
return items, nil
}
// SetRoute53HostedZoneTagsById adds, removes and updates tags for the Route53 HostedZone by Id
func (c Clients) SetRoute53HostedZoneTagsById(ctx context.Context, id string, tags map[string]string) error {
id = strings.ReplaceAll(id, "/hostedzone/", "")
tagsRes, err := c.Route53.ListTagsForResource(ctx, &route53.ListTagsForResourceInput{
ResourceId: aws.String(id),
ResourceType: route53types.TagResourceTypeHostedzone,
})
if err != nil {
return err
}
remove := make([]string, 0)
add := make([]route53types.Tag, 0)
for _, tag := range tagsRes.ResourceTagSet.Tags {
if val, ok := tags[*tag.Key]; ok {
if *tag.Value != val {
remove = append(remove, *tag.Key)
}
} else {
remove = append(remove, *tag.Key)
}
}
for key, value := range tags {
add = append(add, route53types.Tag{
Key: aws.String(key),
Value: aws.String(value),
})
}
params := route53.ChangeTagsForResourceInput{
ResourceId: aws.String(id),
ResourceType: route53types.TagResourceTypeHostedzone,
}
if len(add) == 0 && len(remove) == 0 {
return nil
}
if len(add) > 0 {
params.AddTags = add
}
if len(remove) > 0 {
params.RemoveTagKeys = remove
}
_, err = c.Route53.ChangeTagsForResource(ctx, ¶ms)
if err != nil {
return err
}
return nil
}
// UpsertRoute53ResourceRecordSet creates or updates a resource recordset in the specified hosted zone
func (c Clients) UpsertRoute53ResourceRecordSet(ctx context.Context, hostedZoneId string, recordSet route53types.ResourceRecordSet, description string) error {
return c.route53ResourceRecordSetAction(ctx, route53types.ChangeActionUpsert, hostedZoneId, recordSet, description)
}
// DeleteRoute53ResourceRecordSet deletes a resource recordset in the specified hosted zone
func (c Clients) DeleteRoute53ResourceRecordSet(ctx context.Context, hostedZoneId string, recordSet route53types.ResourceRecordSet, description string) error {
return c.route53ResourceRecordSetAction(ctx, route53types.ChangeActionDelete, hostedZoneId, recordSet, description)
}
func (c Clients) route53ResourceRecordSetAction(ctx context.Context, action route53types.ChangeAction, hostedZoneId string, recordSet route53types.ResourceRecordSet, description string) error {
params := route53.ChangeResourceRecordSetsInput{
ChangeBatch: &route53types.ChangeBatch{
Changes: []route53types.Change{
{
Action: action,
ResourceRecordSet: &recordSet,
},
},
Comment: aws.String(description),
},
HostedZoneId: aws.String(hostedZoneId),
}
_, err := c.Route53.ChangeResourceRecordSets(ctx, ¶ms)
return err
}
func (c Clients) WaitForRoute53Change(ctx context.Context, change *route53types.ChangeInfo) {
c.Log.V(1).Info("waiting for AWS Route53 change to complete", "id", change.Id)
for {
req := route53.GetChangeInput{Id: change.Id}
resp, err := c.Route53.GetChange(ctx, &req)
if err != nil {
c.Log.V(1).Error(err, "waiting for AWS Route53 change failed", "id", change.Id)
}
if resp.ChangeInfo.Status == route53types.ChangeStatusInsync {
c.Log.V(1).Info("AWS Route53 change completed", "id", change.Id)
break
} else if resp.ChangeInfo.Status == route53types.ChangeStatusPending {
c.Log.V(2).Info("still wating for AWS Route53 change to complete", "id", change.Id)
} else {
c.Log.V(1).Info("AWS Route53 change failed", "id", change.Id, "status", resp.ChangeInfo.Status)
break
}
time.Sleep(1 * time.Second)
}
}
func isRoute53HostedZoneDefaultRecord(hostedZone route53types.HostedZone, recordSet route53types.ResourceRecordSet) bool {
return (recordSet.Type == route53types.RRTypeNs || recordSet.Type == route53types.RRTypeSoa) && *recordSet.Name == *hostedZone.Name
}