|
| 1 | +// Copyright 2021 Nitric Technologies Pty Ltd. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package deploytf |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "strings" |
| 20 | + |
| 21 | + "github.com/aws/aws-sdk-go-v2/config" |
| 22 | + "github.com/aws/aws-sdk-go-v2/service/route53" |
| 23 | + "github.com/aws/aws-sdk-go/aws" |
| 24 | +) |
| 25 | + |
| 26 | +func getZoneIds(domainNames []string) map[string]*string { |
| 27 | + ctx := context.TODO() |
| 28 | + |
| 29 | + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2")) |
| 30 | + if err != nil { |
| 31 | + return nil |
| 32 | + } |
| 33 | + |
| 34 | + client := route53.NewFromConfig(cfg) |
| 35 | + |
| 36 | + zoneMap := make(map[string]*string) |
| 37 | + |
| 38 | + normalizedDomains := make(map[string]string) |
| 39 | + for _, d := range domainNames { |
| 40 | + d = strings.ToLower(strings.TrimSuffix(d, ".")) |
| 41 | + normalizedDomains[d] = d + "." |
| 42 | + } |
| 43 | + |
| 44 | + paginator := route53.NewListHostedZonesPaginator(client, &route53.ListHostedZonesInput{}) |
| 45 | + hostedZones := make(map[string]string) // map of zone name -> zone ID |
| 46 | + |
| 47 | + for paginator.HasMorePages() { |
| 48 | + page, err := paginator.NextPage(ctx) |
| 49 | + if err != nil { |
| 50 | + return nil |
| 51 | + } |
| 52 | + |
| 53 | + for _, hz := range page.HostedZones { |
| 54 | + name := strings.ToLower(strings.TrimSuffix(*hz.Name, ".")) |
| 55 | + hostedZones[name] = strings.TrimPrefix(*hz.Id, "/hostedzone/") |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // Resolve each domain name |
| 60 | + for domain, normalized := range normalizedDomains { |
| 61 | + // Check full domain |
| 62 | + if id, ok := hostedZones[strings.TrimSuffix(normalized, ".")]; ok { |
| 63 | + zoneMap[domain] = aws.String(id) |
| 64 | + continue |
| 65 | + } |
| 66 | + |
| 67 | + // Try parent/root domain |
| 68 | + parts := strings.Split(domain, ".") |
| 69 | + if len(parts) > 2 { |
| 70 | + root := strings.Join(parts[len(parts)-2:], ".") |
| 71 | + if id, ok := hostedZones[root]; ok { |
| 72 | + zoneMap[domain] = aws.String(id) |
| 73 | + continue |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + // No match |
| 78 | + zoneMap[domain] = nil |
| 79 | + } |
| 80 | + |
| 81 | + return zoneMap |
| 82 | +} |
0 commit comments