forked from kubernetes-sigs/external-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
azure.go
458 lines (403 loc) · 12.6 KB
/
azure.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
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package provider
import (
"fmt"
"io/ioutil"
"strings"
log "github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v2"
"github.com/Azure/azure-sdk-for-go/arm/dns"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/kubernetes-incubator/external-dns/endpoint"
"github.com/kubernetes-incubator/external-dns/plan"
)
const (
azureRecordTTL = 300
)
type config struct {
Cloud string `json:"cloud" yaml:"cloud"`
TenantID string `json:"tenantId" yaml:"tenantId"`
SubscriptionID string `json:"subscriptionId" yaml:"subscriptionId"`
ResourceGroup string `json:"resourceGroup" yaml:"resourceGroup"`
Location string `json:"location" yaml:"location"`
ClientID string `json:"aadClientId" yaml:"aadClientId"`
ClientSecret string `json:"aadClientSecret" yaml:"aadClientSecret"`
}
// ZonesClient is an interface of dns.ZoneClient that can be stubbed for testing.
type ZonesClient interface {
ListByResourceGroup(resourceGroupName string, top *int32) (result dns.ZoneListResult, err error)
ListByResourceGroupNextResults(lastResults dns.ZoneListResult) (result dns.ZoneListResult, err error)
}
// RecordsClient is an interface of dns.RecordClient that can be stubbed for testing.
type RecordsClient interface {
ListByDNSZone(resourceGroupName string, zoneName string, top *int32) (result dns.RecordSetListResult, err error)
ListByDNSZoneNextResults(list dns.RecordSetListResult) (result dns.RecordSetListResult, err error)
Delete(resourceGroupName string, zoneName string, relativeRecordSetName string, recordType dns.RecordType, ifMatch string) (result autorest.Response, err error)
CreateOrUpdate(resourceGroupName string, zoneName string, relativeRecordSetName string, recordType dns.RecordType, parameters dns.RecordSet, ifMatch string, ifNoneMatch string) (result dns.RecordSet, err error)
}
// AzureProvider implements the DNS provider for Microsoft's Azure cloud platform.
type AzureProvider struct {
domainFilter DomainFilter
zoneIDFilter ZoneIDFilter
dryRun bool
resourceGroup string
zonesClient ZonesClient
recordsClient RecordsClient
}
// NewAzureProvider creates a new Azure provider.
//
// Returns the provider or an error if a provider could not be created.
func NewAzureProvider(configFile string, domainFilter DomainFilter, zoneIDFilter ZoneIDFilter, resourceGroup string, dryRun bool) (*AzureProvider, error) {
contents, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, fmt.Errorf("failed to read Azure config file '%s': %v", configFile, err)
}
cfg := config{}
err = yaml.Unmarshal(contents, &cfg)
if err != nil {
return nil, fmt.Errorf("failed to read Azure config file '%s': %v", configFile, err)
}
// If a resource group was given, override what was present in the config file
if resourceGroup != "" {
cfg.ResourceGroup = resourceGroup
}
var environment azure.Environment
if cfg.Cloud == "" {
environment = azure.PublicCloud
} else {
environment, err = azure.EnvironmentFromName(cfg.Cloud)
if err != nil {
return nil, fmt.Errorf("invalid cloud value '%s': %v", cfg.Cloud, err)
}
}
oauthConfig, err := adal.NewOAuthConfig(environment.ActiveDirectoryEndpoint, cfg.TenantID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve OAuth config: %v", err)
}
token, err := adal.NewServicePrincipalToken(*oauthConfig, cfg.ClientID, cfg.ClientSecret, environment.ResourceManagerEndpoint)
if err != nil {
return nil, fmt.Errorf("failed to create service principal token: %v", err)
}
zonesClient := dns.NewZonesClient(cfg.SubscriptionID)
zonesClient.Authorizer = autorest.NewBearerAuthorizer(token)
recordsClient := dns.NewRecordSetsClient(cfg.SubscriptionID)
recordsClient.Authorizer = autorest.NewBearerAuthorizer(token)
provider := &AzureProvider{
domainFilter: domainFilter,
zoneIDFilter: zoneIDFilter,
dryRun: dryRun,
resourceGroup: cfg.ResourceGroup,
zonesClient: zonesClient,
recordsClient: recordsClient,
}
return provider, nil
}
// Records gets the current records.
//
// Returns the current records or an error if the operation failed.
func (p *AzureProvider) Records() (endpoints []*endpoint.Endpoint, _ error) {
zones, err := p.zones()
if err != nil {
return nil, err
}
for _, zone := range zones {
err := p.iterateRecords(*zone.Name, func(recordSet dns.RecordSet) bool {
if recordSet.Name == nil || recordSet.Type == nil {
log.Error("Skipping invalid record set with nil name or type.")
return true
}
recordType := strings.TrimLeft(*recordSet.Type, "Microsoft.Network/dnszones/")
if !supportedRecordType(recordType) {
return true
}
name := formatAzureDNSName(*recordSet.Name, *zone.Name)
target := extractAzureTarget(&recordSet)
if target == "" {
log.Errorf("Failed to extract target for '%s' with type '%s'.", name, recordType)
return true
}
var ttl endpoint.TTL
if recordSet.TTL != nil {
ttl = endpoint.TTL(*recordSet.TTL)
}
ep := endpoint.NewEndpointWithTTL(name, target, recordType, endpoint.TTL(ttl))
log.Debugf(
"Found %s record for '%s' with target '%s'.",
ep.RecordType,
ep.DNSName,
ep.Target,
)
endpoints = append(endpoints, ep)
return true
})
if err != nil {
return nil, err
}
}
return endpoints, nil
}
// ApplyChanges applies the given changes.
//
// Returns nil if the operation was successful or an error if the operation failed.
func (p *AzureProvider) ApplyChanges(changes *plan.Changes) error {
zones, err := p.zones()
if err != nil {
return err
}
deleted, updated := p.mapChanges(zones, changes)
p.deleteRecords(deleted)
p.updateRecords(updated)
return nil
}
func (p *AzureProvider) zones() ([]dns.Zone, error) {
log.Debug("Retrieving Azure DNS zones.")
var zones []dns.Zone
list, err := p.zonesClient.ListByResourceGroup(p.resourceGroup, nil)
if err != nil {
return nil, err
}
for list.Value != nil && len(*list.Value) > 0 {
for _, zone := range *list.Value {
if zone.Name == nil {
continue
}
if !p.domainFilter.Match(*zone.Name) {
continue
}
if !p.zoneIDFilter.Match(*zone.ID) {
continue
}
zones = append(zones, zone)
}
list, err = p.zonesClient.ListByResourceGroupNextResults(list)
if err != nil {
return nil, err
}
}
log.Debugf("Found %d Azure DNS zone(s).", len(zones))
return zones, nil
}
func (p *AzureProvider) iterateRecords(zoneName string, callback func(dns.RecordSet) bool) error {
log.Debugf("Retrieving Azure DNS records for zone '%s'.", zoneName)
list, err := p.recordsClient.ListByDNSZone(p.resourceGroup, zoneName, nil)
if err != nil {
return err
}
for list.Value != nil && len(*list.Value) > 0 {
for _, recordSet := range *list.Value {
if !callback(recordSet) {
return nil
}
}
list, err = p.recordsClient.ListByDNSZoneNextResults(list)
if err != nil {
return err
}
}
return nil
}
type azureChangeMap map[string][]*endpoint.Endpoint
func (p *AzureProvider) mapChanges(zones []dns.Zone, changes *plan.Changes) (azureChangeMap, azureChangeMap) {
ignored := map[string]bool{}
deleted := azureChangeMap{}
updated := azureChangeMap{}
zoneNameIDMapper := zoneIDName{}
for _, z := range zones {
if z.Name != nil {
zoneNameIDMapper.Add(*z.Name, *z.Name)
}
}
mapChange := func(changeMap azureChangeMap, change *endpoint.Endpoint) {
zone, _ := zoneNameIDMapper.FindZone(change.DNSName)
if zone == "" {
if _, ok := ignored[change.DNSName]; !ok {
ignored[change.DNSName] = true
log.Infof("Ignoring changes to '%s' because a suitable Azure DNS zone was not found.", change.DNSName)
}
return
}
// Ensure the record type is suitable
changeMap[zone] = append(changeMap[zone], change)
}
for _, change := range changes.Delete {
mapChange(deleted, change)
}
for _, change := range changes.UpdateOld {
mapChange(deleted, change)
}
for _, change := range changes.Create {
mapChange(updated, change)
}
for _, change := range changes.UpdateNew {
mapChange(updated, change)
}
return deleted, updated
}
func (p *AzureProvider) deleteRecords(deleted azureChangeMap) {
// Delete records first
for zone, endpoints := range deleted {
for _, endpoint := range endpoints {
name := p.recordSetNameForZone(zone, endpoint)
if p.dryRun {
log.Infof("Would delete %s record named '%s' for Azure DNS zone '%s'.", endpoint.RecordType, name, zone)
} else {
log.Infof("Deleting %s record named '%s' for Azure DNS zone '%s'.", endpoint.RecordType, name, zone)
if _, err := p.recordsClient.Delete(p.resourceGroup, zone, name, dns.RecordType(endpoint.RecordType), ""); err != nil {
log.Errorf(
"Failed to delete %s record named '%s' for Azure DNS zone '%s': %v",
endpoint.RecordType,
name,
zone,
err,
)
}
}
}
}
}
func (p *AzureProvider) updateRecords(updated azureChangeMap) {
for zone, endpoints := range updated {
for _, endpoint := range endpoints {
name := p.recordSetNameForZone(zone, endpoint)
if p.dryRun {
log.Infof(
"Would update %s record named '%s' to '%s' for Azure DNS zone '%s'.",
endpoint.RecordType,
name,
endpoint.Target,
zone,
)
continue
}
log.Infof(
"Updating %s record named '%s' to '%s' for Azure DNS zone '%s'.",
endpoint.RecordType,
name,
endpoint.Target,
zone,
)
recordSet, err := p.newRecordSet(endpoint)
if err == nil {
_, err = p.recordsClient.CreateOrUpdate(
p.resourceGroup,
zone,
name,
dns.RecordType(endpoint.RecordType),
recordSet,
"",
"",
)
}
if err != nil {
log.Errorf(
"Failed to update %s record named '%s' to '%s' for DNS zone '%s': %v",
endpoint.RecordType,
name,
endpoint.Target,
zone,
err,
)
}
}
}
}
func (p *AzureProvider) recordSetNameForZone(zone string, endpoint *endpoint.Endpoint) string {
// Remove the zone from the record set
name := endpoint.DNSName
name = name[:len(name)-len(zone)]
name = strings.TrimSuffix(name, ".")
// For root, use @
if name == "" {
return "@"
}
return name
}
func (p *AzureProvider) newRecordSet(endpoint *endpoint.Endpoint) (dns.RecordSet, error) {
var ttl int64 = azureRecordTTL
if endpoint.RecordTTL.IsConfigured() {
ttl = int64(endpoint.RecordTTL)
}
switch dns.RecordType(endpoint.RecordType) {
case dns.A:
return dns.RecordSet{
RecordSetProperties: &dns.RecordSetProperties{
TTL: to.Int64Ptr(ttl),
ARecords: &[]dns.ARecord{
{
Ipv4Address: to.StringPtr(endpoint.Target),
},
},
},
}, nil
case dns.CNAME:
return dns.RecordSet{
RecordSetProperties: &dns.RecordSetProperties{
TTL: to.Int64Ptr(ttl),
CnameRecord: &dns.CnameRecord{
Cname: to.StringPtr(endpoint.Target),
},
},
}, nil
case dns.TXT:
return dns.RecordSet{
RecordSetProperties: &dns.RecordSetProperties{
TTL: to.Int64Ptr(ttl),
TxtRecords: &[]dns.TxtRecord{
{
Value: &[]string{
endpoint.Target,
},
},
},
},
}, nil
}
return dns.RecordSet{}, fmt.Errorf("unsupported record type '%s'", endpoint.RecordType)
}
// Helper function (shared with test code)
func formatAzureDNSName(recordName, zoneName string) string {
if recordName == "@" {
return zoneName
}
return fmt.Sprintf("%s.%s", recordName, zoneName)
}
// Helper function (shared with text code)
func extractAzureTarget(recordSet *dns.RecordSet) string {
properties := recordSet.RecordSetProperties
if properties == nil {
return ""
}
// Check for A records
aRecords := properties.ARecords
if aRecords != nil && len(*aRecords) > 0 && (*aRecords)[0].Ipv4Address != nil {
return *(*aRecords)[0].Ipv4Address
}
// Check for CNAME records
cnameRecord := properties.CnameRecord
if cnameRecord != nil && cnameRecord.Cname != nil {
return *cnameRecord.Cname
}
// Check for TXT records
txtRecords := properties.TxtRecords
if txtRecords != nil && len(*txtRecords) > 0 && (*txtRecords)[0].Value != nil {
values := (*txtRecords)[0].Value
if values != nil && len(*values) > 0 {
return (*values)[0]
}
}
return ""
}