diff --git a/plugins/module_utils/azure_rm_common.py b/plugins/module_utils/azure_rm_common.py index 6ba328695..5eeb5b382 100644 --- a/plugins/module_utils/azure_rm_common.py +++ b/plugins/module_utils/azure_rm_common.py @@ -227,6 +227,8 @@ def default_api_version(self): from azure.mgmt.storage import StorageManagementClient from azure.mgmt.compute import ComputeManagementClient from azure.mgmt.dns import DnsManagementClient + from azure.mgmt.privatedns import PrivateDnsManagementClient + import azure.mgmt.privatedns.models as PrivateDnsModels from azure.mgmt.monitor import MonitorManagementClient from azure.mgmt.web import WebSiteManagementClient from azure.mgmt.containerservice import ContainerServiceClient @@ -327,6 +329,10 @@ def normalize_location_name(name): 'package_name': 'dns', 'expected_version': '2.1.0' }, + 'PrivateDnsManagementClient': { + 'package_name': 'privatedns', + 'expected_version': '0.1.0' + }, 'WebSiteManagementClient': { 'package_name': 'web', 'expected_version': '0.41.0' @@ -386,6 +392,7 @@ def __init__(self, derived_arg_spec, bypass_checks=False, no_log=False, self._resource_client = None self._compute_client = None self._dns_client = None + self._private_dns_client = None self._web_client = None self._marketplace_client = None self._sql_client = None @@ -989,6 +996,20 @@ def dns_models(self): self.log("Getting dns models...") return DnsManagementClient.models('2018-05-01') + @property + def private_dns_client(self): + self.log('Getting private dns client') + if not self._private_dns_client: + self._private_dns_client = self.get_mgmt_svc_client( + PrivateDnsManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + return self._private_dns_client + + @property + def private_dns_models(self): + self.log('Getting private dns models') + return PrivateDnsModels + @property def web_client(self): self.log('Getting web client') diff --git a/plugins/modules/azure_rm_privatednszone.py b/plugins/modules/azure_rm_privatednszone.py new file mode 100644 index 000000000..be729f7f4 --- /dev/null +++ b/plugins/modules/azure_rm_privatednszone.py @@ -0,0 +1,231 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2020 Jose Angel Munoz, +# +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = ''' +--- +module: azure_rm_privatednszone + +version_added: "2.10" + +short_description: Manage Azure private DNS zones + +description: + - Creates and deletes Azure private DNS zones. + +options: + resource_group: + description: + - Name of resource group. + type: str + required: true + name: + description: + - Name of the private DNS zone. + type: str + required: true + state: + description: + - Assert the state of the zone. Use C(present) to create or update and C(absent) to delete. + default: present + type: str + choices: + - absent + - present + +extends_documentation_fragment: + - azure.azcollection.azure + - azure.azcollection.azure_tags + +author: + - Jose Angel Munoz (@imjoseangel) +''' + +EXAMPLES = ''' + +- name: Create a private DNS zone + azure_rm_privatednszone: + resource_group: myResourceGroup + name: example.com + +- name: Delete a private DNS zone + azure_rm_privatednszone: + resource_group: myResourceGroup + name: example.com + state: absent + +''' + +RETURN = ''' +state: + description: + - Current state of the zone. + returned: always + type: dict + sample: { + "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup", + "location": "global", + "name": "Testing", + "number_of_record_sets": 2, + "number_of_virtual_network_links": 0, + "number_of_virtual_network_links_with_registration": 0 + } + +''' + +from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase, format_resource_id +from ansible.module_utils._text import to_native + +try: + from msrestazure.azure_exceptions import CloudError + from msrest.polling import LROPoller +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMPrivateDNSZone(AzureRMModuleBase): + def __init__(self): + + # define user inputs from playbook + self.module_arg_spec = dict(resource_group=dict(type='str', + required=True), + name=dict(type='str', required=True), + state=dict(choices=['present', 'absent'], + default='present', + type='str')) + + # store the results of the module operation + self.results = dict(changed=False, state=dict()) + + self.resource_group = None + self.name = None + self.state = None + self.tags = None + + super(AzureRMPrivateDNSZone, self).__init__(self.module_arg_spec, + supports_check_mode=True, + supports_tags=True) + + def exec_module(self, **kwargs): + + # create a new zone variable in case the 'try' doesn't find a zone + zone = None + for key in list(self.module_arg_spec.keys()) + ['tags']: + setattr(self, key, kwargs[key]) + + self.results['check_mode'] = self.check_mode + + # retrieve resource group to make sure it exists + self.get_resource_group(self.resource_group) + + changed = False + results = dict() + + try: + self.log('Fetching private DNS zone {0}'.format(self.name)) + zone = self.private_dns_client.private_zones.get( + self.resource_group, self.name) + + # serialize object into a dictionary + results = zone_to_dict(zone) + + # don't change anything if creating an existing zone, but change if deleting it + if self.state == 'present': + changed = False + + update_tags, results['tags'] = self.update_tags( + results['tags']) + if update_tags: + changed = True + elif self.state == 'absent': + changed = True + + except CloudError: + # the zone does not exist so create it + if self.state == 'present': + changed = True + else: + # you can't delete what is not there + changed = False + + self.results['changed'] = changed + self.results['state'] = results + + # return the results if your only gathering information + if self.check_mode: + return self.results + + if changed: + if self.state == 'present': + zone = self.private_dns_models.PrivateZone(tags=self.tags, + location='global') + self.results['state'] = self.create_or_update_zone(zone) + elif self.state == 'absent': + # delete zone + self.delete_zone() + # the delete does not actually return anything. if no exception, then we'll assume + # it worked. + self.results['state']['status'] = 'Deleted' + + return self.results + + def create_or_update_zone(self, zone): + try: + # create or update the new Zone object we created + new_zone = self.private_dns_client.private_zones.create_or_update( + self.resource_group, self.name, zone) + + if isinstance(new_zone, LROPoller): + new_zone = self.get_poller_result(new_zone) + + except Exception as exc: + self.fail("Error creating or updating zone {0} - {1}".format( + self.name, exc.message or str(exc))) + return zone_to_dict(new_zone) + + def delete_zone(self): + try: + # delete the Zone + poller = self.private_dns_client.private_zones.delete( + self.resource_group, self.name) + result = self.get_poller_result(poller) + except Exception as exc: + self.fail("Error deleting zone {0} - {1}".format( + self.name, exc.message or str(exc))) + return result + + +def zone_to_dict(zone): + # turn Zone object into a dictionary (serialization) + result = dict( + id=zone.id, + name=zone.name, + number_of_record_sets=zone.number_of_record_sets, + number_of_virtual_network_links=zone.number_of_virtual_network_links, + number_of_virtual_network_links_with_registration=zone. + number_of_virtual_network_links_with_registration, + tags=zone.tags) + return result + + +def main(): + AzureRMPrivateDNSZone() + + +if __name__ == '__main__': + main() diff --git a/plugins/modules/azure_rm_privatednszone_info.py b/plugins/modules/azure_rm_privatednszone_info.py new file mode 100644 index 000000000..a95c66450 --- /dev/null +++ b/plugins/modules/azure_rm_privatednszone_info.py @@ -0,0 +1,251 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2020 Jose Angel Munoz, +# +# +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = ''' +--- +module: azure_rm_privatednszone_info + +version_added: "2.10" + +short_description: Get private DNS zone facts + +description: + - Get facts for a specific private DNS zone or all private DNS zones within a resource group. + +options: + resource_group: + description: + - Limit results by resource group. Required when filtering by name. + type: str + name: + description: + - Only show results for a specific zone. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + +extends_documentation_fragment: + - azure.azcollection.azure + - azure.azcollection.azure_tags + +author: + - Jose Angel Munoz (@imjoseangel) + +''' + +EXAMPLES = ''' +- name: Get facts for one zone + azure_rm_privatednszone_info: + resource_group: myResourceGroup + name: foobar22 + +- name: Get facts for all zones in a resource group + azure_rm_privatednszone_info: + resource_group: myResourceGroup + +- name: Get facts for privatednszone with tags + azure_rm_privatednszone_info: + tags: + - testing + - foo:bar +''' + +RETURN = ''' +azure_privatednszones: + description: + - List of private zone dicts. + returned: always + type: list + example: [{ + "etag": "00000002-0000-0000-0dcb-df5776efd201", + "location": "global", + "properties": { + "maxNumberOfRecordSets": 5000, + "number_of_virtual_network_links": 0, + "number_of_virtual_network_links_with_registration": 0 + }, + "tags": {} + }] +privatednszones: + description: + - List of private zone dicts, which share the same layout as azure_rm_privatednszone module parameter. + returned: always + type: list + contains: + id: + description: + - id of the private DNS Zone. + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/privatednszones/azure.com" + type: str + name: + description: + - name of the private DNS zone. + sample: azure.com + type: str + number_of_record_sets: + description: + - The current number of record sets in this private DNS zone. + type: int + sample: 2 + number_of_virtual_network_links: + description: + - The current number of network links in this private DNS zone. + type: int + sample: 0 + number_of_virtual_network_links_with_registration: + description: + - The current number of network links with registration in this private DNS zone. + type: int + sample: 0 +''' + +from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase +from ansible.module_utils._text import to_native + +try: + from msrestazure.azure_exceptions import CloudError + from azure.common import AzureMissingResourceHttpError, AzureHttpError +except Exception: + # This is handled in azure_rm_common + pass + +AZURE_OBJECT_CLASS = 'PrivateDnsZone' + + +class AzurePrivateRMDNSZoneInfo(AzureRMModuleBase): + def __init__(self): + + # define user inputs into argument + self.module_arg_spec = dict(name=dict(type='str'), + resource_group=dict(type='str'), + tags=dict(type='list')) + + # store the results of the module operation + self.results = dict(changed=False, + ansible_info=dict(azure_privatednszones=[])) + + self.name = None + self.resource_group = None + self.tags = None + + super(AzurePrivateRMDNSZoneInfo, self).__init__(self.module_arg_spec) + + def exec_module(self, **kwargs): + + is_old_facts = self.module._name == 'azure_rm_privatednszone_facts' + if is_old_facts: + self.module.deprecate( + "The 'azure_rm_privatednszone_facts' module has been renamed to 'azure_rm_privatednszone_info'", + version=(2.9, )) + + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if self.name and not self.resource_group: + self.fail( + "Parameter error: resource group required when filtering by name." + ) + + results = [] + # list the conditions and what to return based on user input + if self.name is not None: + # if there is a name, facts about that specific zone + results = self.get_item() + elif self.resource_group: + # all the zones listed in that specific resource group + results = self.list_resource_group() + else: + # all the zones in a subscription + results = self.list_items() + + self.results['ansible_info'][ + 'azure_privatednszones'] = self.serialize_items(results) + self.results['privatednszones'] = self.curated_items(results) + + return self.results + + def get_item(self): + self.log('Get properties for {0}'.format(self.name)) + item = None + results = [] + # get specific zone + try: + item = self.private_dns_client.private_zones.get( + self.resource_group, self.name) + except CloudError: + pass + + # serialize result + if item and self.has_tags(item.tags, self.tags): + results = [item] + return results + + def list_resource_group(self): + self.log('List items for resource group') + try: + response = self.private_dns_client.private_zones.list_by_resource_group( + self.resource_group) + except AzureHttpError as exc: + self.fail("Failed to list for resource group {0} - {1}".format( + self.resource_group, str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item) + return results + + def list_items(self): + self.log('List all items') + try: + response = self.private_dns_client.private_zones.list() + except AzureHttpError as exc: + self.fail("Failed to list all items - {0}".format(str(exc))) + + results = [] + for item in response: + if self.has_tags(item.tags, self.tags): + results.append(item) + return results + + def serialize_items(self, raws): + return [self.serialize_obj(item, AZURE_OBJECT_CLASS) + for item in raws] if raws else [] + + def curated_items(self, raws): + return [self.zone_to_dict(item) for item in raws] if raws else [] + + def zone_to_dict(self, zone): + return dict(id=zone.id, + name=zone.name, + number_of_record_sets=zone.number_of_record_sets, + number_of_virtual_network_links=zone. + number_of_virtual_network_links, + number_of_virtual_network_links_with_registration=zone. + number_of_virtual_network_links_with_registration, + tags=zone.tags) + + +def main(): + AzurePrivateRMDNSZoneInfo() + + +if __name__ == '__main__': + main() diff --git a/pr-pipelines.yml b/pr-pipelines.yml index 8aa5f1596..744123069 100644 --- a/pr-pipelines.yml +++ b/pr-pipelines.yml @@ -50,6 +50,7 @@ parameters: - "azure_rm_mysqlserver" - "azure_rm_networkinterface" - "azure_rm_postgresqlserver" + - "azure_rm_privatednszone" - "azure_rm_publicipaddress" - "azure_rm_rediscache" - "azure_rm_resource" diff --git a/requirements-azure.txt b/requirements-azure.txt index 19d71b1bc..f1e75b537 100644 --- a/requirements-azure.txt +++ b/requirements-azure.txt @@ -17,6 +17,7 @@ azure-mgmt-marketplaceordering==0.1.0 azure-mgmt-monitor==0.5.2 azure-mgmt-network==10.2.0 azure-mgmt-nspkg==2.0.0 +azure-mgmt-privatedns==0.1.0 azure-mgmt-redis==5.0.0 azure-mgmt-resource==2.1.0 azure-mgmt-rdbms==1.4.1 diff --git a/tests/integration/targets/azure_rm_privatednszone/aliases b/tests/integration/targets/azure_rm_privatednszone/aliases new file mode 100644 index 000000000..90d5921a5 --- /dev/null +++ b/tests/integration/targets/azure_rm_privatednszone/aliases @@ -0,0 +1,4 @@ +cloud/azure +shippable/azure/group2 +destructive +azure_rm_privatednszone_info diff --git a/tests/integration/targets/azure_rm_privatednszone/meta/main.yml b/tests/integration/targets/azure_rm_privatednszone/meta/main.yml new file mode 100644 index 000000000..95e1952f9 --- /dev/null +++ b/tests/integration/targets/azure_rm_privatednszone/meta/main.yml @@ -0,0 +1,2 @@ +dependencies: + - setup_azure diff --git a/tests/integration/targets/azure_rm_privatednszone/tasks/main.yml b/tests/integration/targets/azure_rm_privatednszone/tasks/main.yml new file mode 100644 index 000000000..eba80899d --- /dev/null +++ b/tests/integration/targets/azure_rm_privatednszone/tasks/main.yml @@ -0,0 +1,77 @@ +- name: Create random domain name + set_fact: + domain_name: "{{ resource_group | hash('md5') | truncate(16, True, '') + (65535 | random | string) }}" + +- name: Create a private DNS zone (check mode) + azure_rm_privatednszone: + resource_group: "{{ resource_group }}" + name: "{{ domain_name }}.com" + register: results + check_mode: true + +- assert: + that: results.changed + +- name: Create a private DNS zone + azure_rm_privatednszone: + resource_group: "{{ resource_group }}" + name: "{{ domain_name }}.com" + register: results + +- assert: + that: results.changed + +- name: Update private DNS zone with tags + azure_rm_privatednszone: + resource_group: "{{ resource_group }}" + name: "{{ domain_name }}.com" + tags: + test: modified + register: results + +- assert: + that: + - results.changed + - results.state.tags.test == 'modified' + +- name: Test idempotent + azure_rm_privatednszone: + name: "{{ domain_name }}.com" + resource_group: "{{ resource_group }}" + register: results + +- assert: + that: + - not results.changed + +- name: Retrieve DNS Zone Facts + azure_rm_privatednszone_info: + resource_group: "{{ resource_group }}" + name: "{{ domain_name }}.com" + register: zones + +- name: Assert that facts module returned result + assert: + that: + - zones.privatednszones[0].tags.test == 'modified' + - zones.privatednszones[0].number_of_record_sets == 1 + +# +# azure_rm_privatednszone cleanup +# + +- name: Delete private DNS zone + azure_rm_privatednszone: + resource_group: "{{ resource_group }}" + name: "{{ domain_name }}.com" + state: absent + +- name: Delete private DNS zone (idempotent) + azure_rm_privatednszone: + resource_group: "{{ resource_group }}" + name: "{{ domain_name }}.com" + state: absent + register: results + +- assert: + that: not results.changed diff --git a/tests/sanity/ignore-2.11.txt b/tests/sanity/ignore-2.11.txt index fa4bad195..9113b6329 100644 --- a/tests/sanity/ignore-2.11.txt +++ b/tests/sanity/ignore-2.11.txt @@ -867,5 +867,12 @@ plugins/modules/azure_rm_azurefirewall.py validate-modules:required_if-unknown-k plugins/modules/azure_rm_azurefirewall_info.py validate-modules:deprecation-either-date-or-version plugins/modules/azure_rm_azurefirewall_info.py validate-modules:required_if-requirements-unknown plugins/modules/azure_rm_azurefirewall_info.py validate-modules:required_if-unknown-key +plugins/modules/azure_rm_privatednszone.py validate-modules:deprecation-either-date-or-version +plugins/modules/azure_rm_privatednszone.py validate-modules:required_if-requirements-unknown +plugins/modules/azure_rm_privatednszone.py validate-modules:required_if-unknown-key +plugins/modules/azure_rm_privatednszone_info.py validate-modules:deprecation-either-date-or-version +plugins/modules/azure_rm_privatednszone_info.py validate-modules:parameter-list-no-elements +plugins/modules/azure_rm_privatednszone_info.py validate-modules:required_if-requirements-unknown +plugins/modules/azure_rm_privatednszone_info.py validate-modules:required_if-unknown-key tests/utils/shippable/check_matrix.py replace-urlopen tests/utils/shippable/timing.py shebang