Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_dnsrecordset.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Obezimnaka Boms, <[email protected]>
4 # Copyright (c) 2017 Ansible Project
5 #
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_dnsrecordset
14
15 version_added: "0.1.0"
16
17 short_description: Create, delete and update DNS record sets and records
18
19 description:
20 - Creates, deletes, and updates DNS records sets and records within an existing Azure DNS Zone.
21
22 options:
23 resource_group:
24 description:
25 - Name of resource group.
26 required: true
27 type: str
28 zone_name:
29 description:
30 - Name of the existing DNS zone in which to manage the record set.
31 required: true
32 type: str
33 relative_name:
34 description:
35 - Relative name of the record set.
36 required: true
37 type: str
38 record_type:
39 description:
40 - The type of record set to create or delete.
41 choices:
42 - A
43 - AAAA
44 - CNAME
45 - MX
46 - NS
47 - SRV
48 - TXT
49 - PTR
50 - CAA
51 - SOA
52 required: true
53 type: str
54 record_mode:
55 description:
56 - Whether existing record values not sent to the module should be purged.
57 default: purge
58 type: str
59 choices:
60 - append
61 - purge
62 state:
63 description:
64 - Assert the state of the record set. Use C(present) to create or update and C(absent) to delete.
65 default: present
66 type: str
67 choices:
68 - absent
69 - present
70 metadata:
71 description:
72 - The metadata tags for the record sets.
73 type: dict
74 append_metadata:
75 description: Whether metadata should be appended or not
76 type: bool
77 default: True
78 time_to_live:
79 description:
80 - Time to live of the record set in seconds.
81 default: 3600
82 type: int
83 target_resource:
84 description:
85 - A reference to an azure resource from where the dns resource value is taken.
86 - This parameter can only be applied to I(record_type=A), I(record_type=AAAA) and I(record_type=CNAME).
87 - It cannot configure both I(target_resource) and I(records).
88 type: dict
89 suboptions:
90 id:
91 description:
92 - A reference to a another resource ID.
93 - Sample as C("/subscriptions/xxx-xxx/resourceGroups/rg_name/providers/Microsoft.Network/publicIPAddresses/pip01")
94 type: str
95 records:
96 description:
97 - List of records to be created depending on the type of record (set).
98 - It cannot configure both I(target_resource) and I(records).
99 - I(records) must be configured for all record types except I(record_type=A), I(record_type=AAAA) or I(record_type=CNAME).
100 type: list
101 elements: dict
102 suboptions:
103 preference:
104 description:
105 - Used for creating an C(MX) record set/records.
106 priority:
107 description:
108 - Used for creating an C(SRV) record set/records.
109 weight:
110 description:
111 - Used for creating an C(SRV) record set/records.
112 port:
113 description:
114 - Used for creating an C(SRV) record set/records.
115 entry:
116 description:
117 - Primary data value for all record types.
118 email:
119 description:
120 - Used for creating an C(SOA) record set/records.
121 - The email contact for this SOA record.
122 serial_number:
123 description:
124 - Used for creating an C(SOA) record set/records.
125 - The serial number for this SOA record.
126 refresh_time:
127 description:
128 - Used for creating an C(SOA) record set/records.
129 - The refresh value for this SOA record.
130 retry_time:
131 description:
132 - Used for creating an C(SOA) record set/records.
133 - The retry time for this SOA record.
134 expire_time:
135 description:
136 - Used for creating an C(SOA) record set/records.
137 - The expire time for this SOA record.
138 minimum_ttl:
139 description:
140 - Used for creating an C(SOA) record set/records.
141 - The minimum value for this SOA record. By convention this is used to determine the negative caching duration.
142 extends_documentation_fragment:
143 - azure.azcollection.azure
144 - azure.azcollection.azure_tags
145
146 author:
147 - Obezimnaka Boms (@ozboms)
148 - Matt Davis (@nitzmahone)
149 '''
150
151 EXAMPLES = '''
152
153 - name: ensure an "A" record set with multiple records
154 azure_rm_dnsrecordset:
155 resource_group: myResourceGroup
156 relative_name: www
157 zone_name: testing.com
158 record_type: A
159 records:
160 - entry: 192.168.100.101
161 - entry: 192.168.100.102
162 - entry: 192.168.100.103
163
164 - name: delete a record set
165 azure_rm_dnsrecordset:
166 resource_group: myResourceGroup
167 record_type: A
168 relative_name: www
169 zone_name: testing.com
170 state: absent
171
172 - name: create A record set with metadata information
173 azure_rm_dnsrecordset:
174 resource_group: myResourceGroup
175 relative_name: www
176 zone_name: zone1.com
177 record_type: A
178 records:
179 - entry: 192.168.100.104
180 metadata:
181 key1: "value1"
182
183 - name: Create A dns record set with target_resource
184 azure_rm_dnsrecordset:
185 resource_group: myResourceGroup
186 relative_name: www
187 zone_name: zone1.com
188 record_type: A
189 target_resource:
190 id: "/subscriptions/xxx-xxx/resourceGroups/v-xisuRG02/providers/Microsoft.Network/publicIPAddresses/pip01"
191
192 - name: create multiple "A" record sets with multiple records
193 azure_rm_dnsrecordset:
194 resource_group: myResourceGroup
195 zone_name: testing.com
196 relative_name: "{{ item.name }}"
197 record_type: "{{ item.type }}"
198 records: "{{ item.records }}"
199 with_items:
200 - {name: 'servera', type: 'A', records: [{entry: '10.10.10.20'}, {entry: '10.10.10.21'}]}
201 - {name: 'serverb', type: 'A', records: [{entry: '10.10.10.30'}, {entry: '10.10.10.41'}]}
202 - {name: 'serverc', type: 'A', records: [{entry: '10.10.10.40'}, {entry: '10.10.10.41'}]}
203
204 - name: create SRV records in a new record set
205 azure_rm_dnsrecordset:
206 resource_group: myResourceGroup
207 relative_name: _sip._tcp.testing.com
208 zone_name: testing.com
209 time_to_live: 7200
210 record_type: SRV
211 records:
212 - entry: sip.testing.com
213 preference: 10
214 priority: 20
215 weight: 10
216 port: 5060
217
218 - name: create PTR record in a new record set
219 azure_rm_dnsrecordset:
220 resource_group: myResourceGroup
221 relative_name: 192.168.100.101.in-addr.arpa
222 zone_name: testing.com
223 record_type: PTR
224 records:
225 - entry: servera.testing.com
226
227 - name: create TXT record in a new record set
228 azure_rm_dnsrecordset:
229 resource_group: myResourceGroup
230 relative_name: mail.testing.com
231 zone_name: testing.com
232 record_type: TXT
233 records:
234 - entry: 'v=spf1 a -all'
235
236 - name: Update SOA record
237 azure_rm_dnsrecordset:
238 resource_group: myResourceGroup
239 relative_name: "@"
240 zone_name: testing.com
241 record_type: SOA
242 records:
243 - host: ns1-99.example.com.
244 email: azuredns-hostmaster99.example.com
245 serial_number: 99
246 refresh_time: 3699
247 retry_time: 399
248 expire_time: 2419299
249 minimum_ttl: 399
250 '''
251
252 RETURN = '''
253 state:
254 description:
255 - Current state of the DNS record set.
256 returned: always
257 type: complex
258 contains:
259 id:
260 description:
261 - The DNS record set ID.
262 returned: always
263 type: str
264 sample: "/subscriptions/xxxx......xxx/resourceGroups/v-xisuRG/providers/Microsoft.Network/dnszones/b57dc95985712e4523282.com/A/www"
265 name:
266 description:
267 - Relate name of the record set.
268 returned: always
269 type: str
270 sample: 'www'
271 fqdn:
272 description:
273 - Fully qualified domain name of the record set.
274 returned: always
275 type: str
276 sample: www.b57dc95985712e4523282.com
277 etag:
278 description:
279 - The etag of the record set.
280 returned: always
281 type: str
282 sample: 692c3e92-a618-46fc-aecd-8f888807cd6c
283 provisioning_state:
284 description:
285 - The DNS record set state.
286 returned: always
287 type: str
288 sample: Succeeded
289 target_resource:
290 description:
291 - The target resource of the record set.
292 returned: always
293 type: dict
294 sample: {}
295 ttl:
296 description:
297 - The TTL(time-to-live) of the records in the records set.
298 returned: always
299 type: int
300 sample: 3600
301 type:
302 description:
303 - The type of DNS record in this record set.
304 returned: always
305 type: str
306 sample: A
307 arecords:
308 description:
309 - A list of records in the record set.
310 returned: always
311 type: list
312 sample: [
313 {
314 "ipv4_address": "192.0.2.2"
315 },
316 {
317 "ipv4_address": "192.0.2.4"
318 },
319 {
320 "ipv4_address": "192.0.2.8"
321 }
322 ]
323 '''
324
325 import copy
326
327 from ansible.module_utils.basic import _load_params
328 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
329
330 try:
331 from azure.core.exceptions import ResourceNotFoundError
332 except ImportError:
333 # This is handled in azure_rm_common
334 pass
335
336
337 RECORD_ARGSPECS = dict(
338 A=dict(
339 ipv4_address=dict(type='str', required=True, aliases=['entry'])
340 ),
341 AAAA=dict(
342 ipv6_address=dict(type='str', required=True, aliases=['entry'])
343 ),
344 CNAME=dict(
345 cname=dict(type='str', required=True, aliases=['entry'])
346 ),
347 MX=dict(
348 preference=dict(type='int', required=True),
349 exchange=dict(type='str', required=True, aliases=['entry'])
350 ),
351 NS=dict(
352 nsdname=dict(type='str', required=True, aliases=['entry'])
353 ),
354 PTR=dict(
355 ptrdname=dict(type='str', required=True, aliases=['entry'])
356 ),
357 SRV=dict(
358 priority=dict(type='int', required=True),
359 port=dict(type='int', required=True),
360 weight=dict(type='int', required=True),
361 target=dict(type='str', required=True, aliases=['entry'])
362 ),
363 TXT=dict(
364 value=dict(type='list', required=True, aliases=['entry'])
365 ),
366 SOA=dict(
367 host=dict(type='str', aliases=['entry']),
368 email=dict(type='str'),
369 serial_number=dict(type='int'),
370 refresh_time=dict(type='int'),
371 retry_time=dict(type='int'),
372 expire_time=dict(type='int'),
373 minimum_ttl=dict(type='int')
374 ),
375 CAA=dict(
376 value=dict(type='str', aliases=['entry']),
377 flags=dict(type='int'),
378 tag=dict(type='str')
379 )
380 # FUTURE: ensure all record types are supported (see https://github.com/Azure/azure-sdk-for-python/tree/master/azure-mgmt-dns/azure/mgmt/dns/models)
381 )
382
383 RECORDSET_VALUE_MAP = dict(
384 A=dict(attrname='a_records', classobj='ARecord', is_list=True),
385 AAAA=dict(attrname='aaaa_records', classobj='AaaaRecord', is_list=True),
386 CNAME=dict(attrname='cname_record', classobj='CnameRecord', is_list=False),
387 MX=dict(attrname='mx_records', classobj='MxRecord', is_list=True),
388 NS=dict(attrname='ns_records', classobj='NsRecord', is_list=True),
389 PTR=dict(attrname='ptr_records', classobj='PtrRecord', is_list=True),
390 SRV=dict(attrname='srv_records', classobj='SrvRecord', is_list=True),
391 TXT=dict(attrname='txt_records', classobj='TxtRecord', is_list=True),
392 SOA=dict(attrname='soa_record', classobj='SoaRecord', is_list=False),
393 CAA=dict(attrname='caa_records', classobj='CaaRecord', is_list=True)
394 # FUTURE: add missing record types from https://github.com/Azure/azure-sdk-for-python/blob/master/azure-mgmt-dns/azure/mgmt/dns/models/record_set.py
395 )
396
397
398 class AzureRMRecordSet(AzureRMModuleBase):
399
400 def __init__(self):
401
402 # we're doing two-pass arg validation, sample and store the args internally to allow this
403 _load_params()
404
405 self.module_arg_spec = dict(
406 resource_group=dict(type='str', required=True),
407 relative_name=dict(type='str', required=True),
408 zone_name=dict(type='str', required=True),
409 record_type=dict(choices=['A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SRV', 'TXT', 'SOA', 'CAA'],
410 required=True,
411 type='str'),
412 record_mode=dict(type='str', choices=['append', 'purge'], default='purge'),
413 state=dict(choices=['present', 'absent'], default='present', type='str'),
414 time_to_live=dict(type='int', default=3600),
415 records=dict(type='list', elements='dict'),
416 metadata=dict(type='dict'),
417 append_metadata=dict(type='bool', default=True),
418 target_resource=dict(
419 type='dict',
420 options=dict(
421 id=dict(type='str')
422 )
423 ),
424 )
425
426 self.results = dict(
427 changed=False
428 )
429
430 mutually_exclusive = [['target_resource', 'records']]
431 # first-pass arg validation so we can get the record type- skip exec_module
432 super(AzureRMRecordSet, self).__init__(self.module_arg_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True, skip_exec=True)
433
434 # look up the right subspec and metadata
435 record_subspec = RECORD_ARGSPECS.get(self.module.params['record_type'])
436
437 # patch the right record shape onto the argspec
438 self.module_arg_spec['records']['options'] = record_subspec
439
440 self.resource_group = None
441 self.relative_name = None
442 self.zone_name = None
443 self.record_type = None
444 self.record_mode = None
445 self.state = None
446 self.time_to_live = None
447 self.records = None
448 self.metadata = None
449 self.target_resource = None
450
451 # rerun validation and actually run the module this time
452 super(AzureRMRecordSet, self).__init__(self.module_arg_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True)
453
454 def exec_module(self, **kwargs):
455 for key in self.module_arg_spec.keys():
456 setattr(self, key, kwargs[key])
457
458 zone = self.dns_client.zones.get(self.resource_group, self.zone_name)
459 if not zone:
460 self.fail('The zone {0} does not exist in the resource group {1}'.format(self.zone_name, self.resource_group))
461
462 try:
463 self.log('Fetching Record Set {0}'.format(self.relative_name))
464 record_set = self.dns_client.record_sets.get(self.resource_group, self.zone_name, self.relative_name, self.record_type)
465 self.results['state'] = self.recordset_to_dict(record_set)
466 except ResourceNotFoundError:
467 record_set = None
468 # FUTURE: fail on anything other than ResourceNotFound
469
470 record_type_metadata = RECORDSET_VALUE_MAP.get(self.record_type)
471
472 # FUTURE: implement diff mode
473
474 if self.state == 'present':
475 # convert the input records to SDK objects
476 self.input_sdk_records = self.create_sdk_records(self.records, self.record_type)
477
478 if not record_set:
479 changed = True
480 else:
481 # and use it to get the type-specific records
482 server_records = getattr(record_set, record_type_metadata.get('attrname'))
483
484 # compare the input records to the server records
485 self.input_sdk_records, changed = self.records_changed(self.input_sdk_records, server_records)
486
487 # also check top-level recordset properties
488 changed |= record_set.ttl != self.time_to_live
489
490 old_metadata = self.results['state']['metadata'] if 'metadata' in self.results['state'] else dict()
491 update_metadata, self.results['state']['metadata'] = self.update_metadata(old_metadata)
492 if update_metadata:
493 changed = True
494 self.metadata = self.results['state']['metadata']
495
496 if self.target_resource is not None:
497 if not self.results['state'].get('target_resource'):
498 changed = True
499 else:
500 if self.target_resource['id'].lower() != self.results['state']['target_resource']['id'].lower():
501 changed = True
502
503 self.results['changed'] |= changed
504
505 elif self.state == 'absent':
506 if record_set:
507 self.results['changed'] = True
508
509 if self.check_mode:
510 return self.results
511
512 if self.results['changed']:
513 if self.state == 'present':
514 record_set_args = dict(
515 ttl=self.time_to_live,
516 )
517
518 record_set_args[record_type_metadata['attrname']] = self.input_sdk_records if record_type_metadata['is_list'] else self.input_sdk_records[0]
519
520 record_set = self.dns_models.RecordSet(**record_set_args)
521 if self.metadata:
522 record_set.metadata = self.metadata
523 if self.target_resource:
524 record_set.target_resource = self.dns_models.SubResource(id=self.target_resource['id'])
525
526 self.results['state'] = self.create_or_update(record_set)
527
528 elif self.state == 'absent':
529 # delete record set
530 self.delete_record_set()
531
532 return self.results
533
534 def create_or_update(self, record_set):
535 try:
536 record_set = self.dns_client.record_sets.create_or_update(resource_group_name=self.resource_group,
537 zone_name=self.zone_name,
538 relative_record_set_name=self.relative_name,
539 record_type=self.record_type,
540 parameters=record_set)
541 return self.recordset_to_dict(record_set)
542 except Exception as exc:
543 self.fail("Error creating or updating dns record {0} - {1}".format(self.relative_name, exc.message or str(exc)))
544
545 def delete_record_set(self):
546 try:
547 # delete the record set
548 self.dns_client.record_sets.delete(resource_group_name=self.resource_group,
549 zone_name=self.zone_name,
550 relative_record_set_name=self.relative_name,
551 record_type=self.record_type)
552 except Exception as exc:
553 self.fail("Error deleting record set {0} - {1}".format(self.relative_name, exc.message or str(exc)))
554 return None
555
556 def create_sdk_records(self, input_records, record_type):
557 record = RECORDSET_VALUE_MAP.get(record_type)
558 if not record:
559 self.fail('record type {0} is not supported now'.format(record_type))
560 record_sdk_class = getattr(self.dns_models, record.get('classobj'))
561 record_sdk = []
562 if input_records is not None:
563 for x in input_records:
564 record_sdk.append(record_sdk_class(**x))
565 return record_sdk
566
567 def records_changed(self, input_records, server_records):
568 # ensure we're always comparing a list, even for the single-valued types
569 if not isinstance(server_records, list):
570 server_records = [server_records]
571
572 input_set = set([self.module.jsonify(x.as_dict()) for x in input_records])
573 server = []
574 for x in server_records:
575 if x is not None:
576 server.append(self.module.jsonify(x.as_dict()))
577 server_set = set(server)
578
579 if self.record_mode == 'append': # only a difference if the server set is missing something from the input set
580 input_set = server_set.union(input_set)
581
582 # non-append mode; any difference in the sets is a change
583 changed = input_set != server_set
584
585 records = [self.module.from_json(x) for x in input_set]
586 return self.create_sdk_records(records, self.record_type), changed
587
588 def recordset_to_dict(self, recordset):
589 result = recordset.as_dict()
590 result['type'] = result['type'].strip('Microsoft.Network/dnszones/')
591 return result
592
593 def update_metadata(self, metadata):
594 metadata = metadata or dict()
595 new_metadata = copy.copy(metadata) if isinstance(metadata, dict) else dict()
596 param_metadata = self.metadata if isinstance(self.metadata, dict) else dict()
597 append_metadata = self.append_metadata if self.metadata is not None else True
598 changed = False
599 # check add or update metadata
600 for key, value in param_metadata.items():
601 if not new_metadata.get(key) or new_metadata[key] != value:
602 changed = True
603 new_metadata[key] = value
604 # check remove
605 if not append_metadata:
606 for key, value in metadata.items():
607 if not param_metadata.get(key):
608 new_metadata.pop(key)
609 changed = True
610 return changed, new_metadata
611
612
613 def main():
614 AzureRMRecordSet()
615
616
617 if __name__ == '__main__':
618 main()