forked from EngineerBetter/concourse-up
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route_53.go
49 lines (41 loc) · 1.44 KB
/
route_53.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
package aws
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
)
// FindLongestMatchingHostedZone finds the longest hosted zone that matches the given subdomain
func FindLongestMatchingHostedZone(subdomain string) (string, string, error) {
sess, err := session.NewSession(aws.NewConfig().WithCredentialsChainVerboseErrors(true))
if err != nil {
return "", "", err
}
client := route53.New(sess)
hostedZones := []*route53.HostedZone{}
err = client.ListHostedZonesPages(&route53.ListHostedZonesInput{}, func(output *route53.ListHostedZonesOutput, _ bool) bool {
hostedZones = append(hostedZones, output.HostedZones...)
return true
})
if err != nil {
return "", "", err
}
longestMatchingHostedZoneName := ""
longestMatchingHostedZoneID := ""
for _, hostedZone := range hostedZones {
domain := strings.TrimRight(*hostedZone.Name, ".")
id := *hostedZone.Id
if strings.HasSuffix(subdomain, domain) {
if len(domain) > len(longestMatchingHostedZoneName) {
longestMatchingHostedZoneName = domain
longestMatchingHostedZoneID = id
}
}
}
if longestMatchingHostedZoneName == "" {
return "", "", fmt.Errorf("No matching hosted zone found for domain %s", subdomain)
}
longestMatchingHostedZoneID = strings.Replace(longestMatchingHostedZoneID, "/hostedzone/", "", -1)
return longestMatchingHostedZoneName, longestMatchingHostedZoneID, err
}