From a03e69550cbe91309ad4c42fb24e6d707157f0b6 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Thu, 21 Mar 2019 03:22:18 -0400 Subject: [PATCH] add azure_rm_mariadbdatabase (#54147) --- .../cloud/azure/azure_rm_mariadbdatabase.py | 308 ++++++++++++++++++ .../azure/azure_rm_mariadbdatabase_facts.py | 203 ++++++++++++ .../targets/azure_rm_mariadbserver/aliases | 2 + .../azure_rm_mariadbserver/tasks/main.yml | 149 +++++++++ 4 files changed, 662 insertions(+) create mode 100644 lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase.py create mode 100644 lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase_facts.py diff --git a/lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase.py b/lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase.py new file mode 100644 index 00000000000..d98550dfb72 --- /dev/null +++ b/lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase.py @@ -0,0 +1,308 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# Copyright (c) 2019 Matti Ranta, (@techknowlogick) +# +# 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_mariadbdatabase +version_added: "2.8" +short_description: Manage MariaDB Database instance. +description: + - Create, update and delete instance of MariaDB Database. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + server_name: + description: + - The name of the server. + required: True + name: + description: + - The name of the database. + required: True + charset: + description: + - The charset of the database. Check MariaDB documentation for possible values. + - This is only set on creation, use I(force_update) to recreate a database if the + values don't match. + collation: + description: + - The collation of the database. Check MariaDB documentation for possible values. + - This is only set on creation, use I(force_update) to recreate a database if the + values don't match. + force_update: + description: + - When set to C(true), will delete and recreate the existing MariaDB database if any + of the properties don't match what is set. + - When set to C(false), no change will occur to the database even if any + of the properties do not match. + type: bool + default: 'no' + state: + description: + - Assert the state of the MariaDB Database. Use C(present) to create or update a database and C(absent) to delete it. + default: present + choices: + - absent + - present + +extends_documentation_fragment: + - azure + +author: + - "Zim Kalinowski (@zikalino)" + - "Matti Ranta (@techknowlogick)" + +''' + +EXAMPLES = ''' + - name: Create (or update) MariaDB Database + azure_rm_mariadbdatabase: + resource_group: myResourceGroup + server_name: testserver + name: db1 +''' + +RETURN = ''' +id: + description: + - Resource ID + returned: always + type: str + sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/testserver/databases/db1 +name: + description: + - Resource name. + returned: always + type: str + sample: db1 +''' + +import time +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from azure.mgmt.rdbms.mariadb import MariaDBManagementClient + from msrestazure.azure_exceptions import CloudError + from msrest.polling import LROPoller + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class Actions: + NoAction, Create, Update, Delete = range(4) + + +class AzureRMMariaDbDatabase(AzureRMModuleBase): + """Configuration class for an Azure RM MariaDB Database resource""" + + def __init__(self): + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str', + required=True + ), + charset=dict( + type='str' + ), + collation=dict( + type='str' + ), + force_update=dict( + type='bool', + default=False + ), + state=dict( + type='str', + default='present', + choices=['present', 'absent'] + ) + ) + + self.resource_group = None + self.server_name = None + self.name = None + self.force_update = None + self.parameters = dict() + + self.results = dict(changed=False) + self.mgmt_client = None + self.state = None + self.to_do = Actions.NoAction + + super(AzureRMMariaDbDatabase, self).__init__(derived_arg_spec=self.module_arg_spec, + supports_check_mode=True, + supports_tags=False) + + def exec_module(self, **kwargs): + """Main module execution method""" + + for key in list(self.module_arg_spec.keys()): + if hasattr(self, key): + setattr(self, key, kwargs[key]) + elif kwargs[key] is not None: + if key == "charset": + self.parameters["charset"] = kwargs[key] + elif key == "collation": + self.parameters["collation"] = kwargs[key] + + old_response = None + response = None + + self.mgmt_client = self.get_mgmt_svc_client(MariaDBManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager) + + resource_group = self.get_resource_group(self.resource_group) + + old_response = self.get_mariadbdatabase() + + if not old_response: + self.log("MariaDB Database instance doesn't exist") + if self.state == 'absent': + self.log("Old instance didn't exist") + else: + self.to_do = Actions.Create + else: + self.log("MariaDB Database instance already exists") + if self.state == 'absent': + self.to_do = Actions.Delete + elif self.state == 'present': + self.log("Need to check if MariaDB Database instance has to be deleted or may be updated") + if ('collation' in self.parameters) and (self.parameters['collation'] != old_response['collation']): + self.to_do = Actions.Update + if ('charset' in self.parameters) and (self.parameters['charset'] != old_response['charset']): + self.to_do = Actions.Update + if self.to_do == Actions.Update: + if self.force_update: + if not self.check_mode: + self.delete_mariadbdatabase() + else: + self.fail("Database properties cannot be updated without setting 'force_update' option") + self.to_do = Actions.NoAction + + if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): + self.log("Need to Create / Update the MariaDB Database instance") + + if self.check_mode: + self.results['changed'] = True + return self.results + + response = self.create_update_mariadbdatabase() + self.results['changed'] = True + self.log("Creation / Update done") + elif self.to_do == Actions.Delete: + self.log("MariaDB Database instance deleted") + self.results['changed'] = True + + if self.check_mode: + return self.results + + self.delete_mariadbdatabase() + # make sure instance is actually deleted, for some Azure resources, instance is hanging around + # for some time after deletion -- this should be really fixed in Azure + while self.get_mariadbdatabase(): + time.sleep(20) + else: + self.log("MariaDB Database instance unchanged") + self.results['changed'] = False + response = old_response + + if response: + self.results["id"] = response["id"] + self.results["name"] = response["name"] + + return self.results + + def create_update_mariadbdatabase(self): + ''' + Creates or updates MariaDB Database with the specified configuration. + + :return: deserialized MariaDB Database instance state dictionary + ''' + self.log("Creating / Updating the MariaDB Database instance {0}".format(self.name)) + + try: + response = self.mgmt_client.databases.create_or_update(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name, + parameters=self.parameters) + if isinstance(response, LROPoller): + response = self.get_poller_result(response) + + except CloudError as exc: + self.log('Error attempting to create the MariaDB Database instance.') + self.fail("Error creating the MariaDB Database instance: {0}".format(str(exc))) + return response.as_dict() + + def delete_mariadbdatabase(self): + ''' + Deletes specified MariaDB Database instance in the specified subscription and resource group. + + :return: True + ''' + self.log("Deleting the MariaDB Database instance {0}".format(self.name)) + try: + response = self.mgmt_client.databases.delete(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name) + except CloudError as e: + self.log('Error attempting to delete the MariaDB Database instance.') + self.fail("Error deleting the MariaDB Database instance: {0}".format(str(e))) + + return True + + def get_mariadbdatabase(self): + ''' + Gets the properties of the specified MariaDB Database. + + :return: deserialized MariaDB Database instance state dictionary + ''' + self.log("Checking if the MariaDB Database instance {0} is present".format(self.name)) + found = False + try: + response = self.mgmt_client.databases.get(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name) + found = True + self.log("Response : {0}".format(response)) + self.log("MariaDB Database instance : {0} found".format(response.name)) + except CloudError as e: + self.log('Did not find the MariaDB Database instance.') + if found is True: + return response.as_dict() + + return False + + +def main(): + """Main execution""" + AzureRMMariaDbDatabase() + + +if __name__ == '__main__': + main() diff --git a/lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase_facts.py b/lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase_facts.py new file mode 100644 index 00000000000..7a66e68e97f --- /dev/null +++ b/lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase_facts.py @@ -0,0 +1,203 @@ +#!/usr/bin/python +# +# Copyright (c) 2017 Zim Kalinowski, +# Copyright (c) 2019 Matti Ranta, (@techknowlogick) +# +# 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_mariadbdatabase_facts +version_added: "2.8" +short_description: Get Azure MariaDB Database facts. +description: + - Get facts of MariaDB Database. + +options: + resource_group: + description: + - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + required: True + server_name: + description: + - The name of the server. + required: True + name: + description: + - The name of the database. + +extends_documentation_fragment: + - azure + +author: + - "Zim Kalinowski (@zikalino)" + - "Matti Ranta (@techknowlogick)" + +''' + +EXAMPLES = ''' + - name: Get instance of MariaDB Database + azure_rm_mariadbdatabase_facts: + resource_group: myResourceGroup + server_name: server_name + name: database_name + + - name: List instances of MariaDB Database + azure_rm_mariadbdatabase_facts: + resource_group: myResourceGroup + server_name: server_name +''' + +RETURN = ''' +databases: + description: A list of dictionaries containing facts for MariaDB Databases. + returned: always + type: complex + contains: + id: + description: + - Resource ID + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DBforMariaDB/servers/testser + ver/databases/db1" + resource_group: + description: + - Resource group name. + returned: always + type: str + sample: testrg + server_name: + description: + - Server name. + returned: always + type: str + sample: testserver + name: + description: + - Resource name. + returned: always + type: str + sample: db1 + charset: + description: + - The charset of the database. + returned: always + type: str + sample: UTF8 + collation: + description: + - The collation of the database. + returned: always + type: str + sample: English_United States.1252 +''' + +from ansible.module_utils.azure_rm_common import AzureRMModuleBase + +try: + from msrestazure.azure_exceptions import CloudError + from azure.mgmt.rdbms.mariadb import MariaDBManagementClient + from msrest.serialization import Model +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMMariaDbDatabaseFacts(AzureRMModuleBase): + def __init__(self): + # define user inputs into argument + self.module_arg_spec = dict( + resource_group=dict( + type='str', + required=True + ), + server_name=dict( + type='str', + required=True + ), + name=dict( + type='str' + ) + ) + # store the results of the module operation + self.results = dict( + changed=False + ) + self.resource_group = None + self.server_name = None + self.name = None + super(AzureRMMariaDbDatabaseFacts, self).__init__(self.module_arg_spec, supports_tags=False) + + def exec_module(self, **kwargs): + for key in self.module_arg_spec: + setattr(self, key, kwargs[key]) + + if (self.resource_group is not None and + self.server_name is not None and + self.name is not None): + self.results['databases'] = self.get() + elif (self.resource_group is not None and + self.server_name is not None): + self.results['databases'] = self.list_by_server() + return self.results + + def get(self): + response = None + results = [] + try: + response = self.mariadb_client.databases.get(resource_group_name=self.resource_group, + server_name=self.server_name, + database_name=self.name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.log('Could not get facts for Databases.') + + if response is not None: + results.append(self.format_item(response)) + + return results + + def list_by_server(self): + response = None + results = [] + try: + response = self.mariadb_client.databases.list_by_server(resource_group_name=self.resource_group, + server_name=self.server_name) + self.log("Response : {0}".format(response)) + except CloudError as e: + self.fail("Error listing for server {0} - {1}".format(self.server_name, str(e))) + + if response is not None: + for item in response: + results.append(self.format_item(item)) + + return results + + def format_item(self, item): + d = item.as_dict() + d = { + 'resource_group': self.resource_group, + 'server_name': self.server_name, + 'name': d['name'], + 'charset': d['charset'], + 'collation': d['collation'] + } + return d + + +def main(): + AzureRMMariaDbDatabaseFacts() + + +if __name__ == '__main__': + main() diff --git a/test/integration/targets/azure_rm_mariadbserver/aliases b/test/integration/targets/azure_rm_mariadbserver/aliases index 5fec1897423..1ca78d093c5 100644 --- a/test/integration/targets/azure_rm_mariadbserver/aliases +++ b/test/integration/targets/azure_rm_mariadbserver/aliases @@ -2,5 +2,7 @@ cloud/azure destructive shippable/azure/group8 azure_rm_mariadbserver_facts +azure_rm_mariadbdatabase +azure_rm_mariadbdatabase_facts azure_rm_mariadbfirewallrule azure_rm_mariadbfirewallrule_facts diff --git a/test/integration/targets/azure_rm_mariadbserver/tasks/main.yml b/test/integration/targets/azure_rm_mariadbserver/tasks/main.yml index 1f847fa02b7..5b33ffb951c 100644 --- a/test/integration/targets/azure_rm_mariadbserver/tasks/main.yml +++ b/test/integration/targets/azure_rm_mariadbserver/tasks/main.yml @@ -176,6 +176,155 @@ - output.servers[1]['user_visible_state'] != None - output.servers[1]['fully_qualified_domain_name'] != None +# +# azure_rm_mariadbdatabase tests below +# +- name: Create instance of MariaDB Database -- check mode + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + check_mode: yes + register: output +- name: Assert the resource instance is well created + assert: + that: + - output.changed + +- name: Create instance of MariaDB Database + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + collation: latin1_swedish_ci + charset: latin1 + register: output +- name: Assert the resource instance is well created + assert: + that: + - output.changed + - output.name == 'testdatabase' + +- name: Create again instance of MariaDB Database + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + collation: latin1_swedish_ci + charset: latin1 + register: output +- name: Assert the state has not changed + assert: + that: + - output.changed == false + - output.name == 'testdatabase' + +- name: Try to update database without force_update + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + collation: latin1_czech_ci + charset: latin1 + ignore_errors: yes + register: output +- name: Assert that nothing has changed + assert: + that: + - output.changed == False + +- name: Update instance of database using force_update + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + collation: latin1_czech_ci + charset: latin1 + force_update: yes + register: output +- name: Assert the state has changed + assert: + that: + - output.changed + - output.name == 'testdatabase' + +- name: Create second instance of MariaDB Database + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase2 + +- name: Gather facts MariaDB Database + azure_rm_mariadbdatabase_facts: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + register: output + +- name: Assert that facts are returned + assert: + that: + - output.changed == False + - output.databases[0]['server_name'] != None + - output.databases[0]['name'] != None + - output.databases[0]['charset'] != None + - output.databases[0]['collation'] != None + +- name: Gather facts MariaDB Database + azure_rm_mariadbdatabase_facts: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + register: output +- name: Assert that facts are returned + assert: + that: + - output.changed == False + - output.databases[0]['server_name'] != None + - output.databases[0]['name'] != None + - output.databases[0]['charset'] != None + - output.databases[0]['collation'] != None + - output.databases[1]['server_name'] != None + - output.databases[1]['name'] != None + - output.databases[1]['charset'] != None + - output.databases[1]['collation'] != None + +- name: Delete instance of MariaDB Database -- check mode + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + state: absent + check_mode: yes + register: output +- name: Assert the state has changed + assert: + that: + - output.changed + +- name: Delete instance of MariaDB Database + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + state: absent + register: output +- name: Assert the state has changed + assert: + that: + - output.changed + +- name: Delete unexisting instance of MariaDB Database + azure_rm_mariadbdatabase: + resource_group: "{{ resource_group }}" + server_name: mariadbsrv{{ rpfx }} + name: testdatabase + state: absent + register: output +- name: Assert the state has changed + assert: + that: + - output.changed == false + # # azure_rm_firewallrule tests below #