diff --git a/plugins/modules/azure_rm_batchaccount.py b/plugins/modules/azure_rm_batchaccount.py index afb4d3d51..78420abe3 100644 --- a/plugins/modules/azure_rm_batchaccount.py +++ b/plugins/modules/azure_rm_batchaccount.py @@ -108,17 +108,13 @@ sample: sampleacct.westus.batch.azure.com ''' -import time -from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import normalize_location_name from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt from ansible.module_utils.common.dict_transformations import _snake_to_camel try: - from msrestazure.azure_exceptions import CloudError - from msrest.polling import LROPoller - from msrestazure.azure_operation import AzureOperationPoller - from msrest.serialization import Model + from azure.core.polling import LROPoller from azure.mgmt.batch import BatchManagementClient + from azure.core.exceptions import ResourceNotFoundError except ImportError: # This is handled in azure_rm_common pass @@ -172,7 +168,6 @@ def __init__(self): self.resource_group = None self.name = None self.batch_account = dict() - self.tags = None self.results = dict(changed=False) self.mgmt_client = None @@ -215,7 +210,8 @@ def exec_module(self, **kwargs): response = None self.mgmt_client = self.get_mgmt_svc_client(BatchManagementClient, - base_url=self._cloud_environment.endpoints.resource_manager) + base_url=self._cloud_environment.endpoints.resource_manager, + is_track2=True) old_response = self.get_batchaccount() @@ -232,7 +228,13 @@ def exec_module(self, **kwargs): elif self.state == 'present': self.results['old'] = old_response self.results['new'] = self.batch_account - if not self.idempotency_check(old_response, self.batch_account): + + update_tags, self.tags = self.update_tags(old_response['tags']) + + if self.batch_account.get('auto_storage_account') is not None: + if old_response['auto_storage']['storage_account_id'] != self.batch_account['auto_storage']['storage_account_id']: + self.to_do = Actions.Update + if update_tags: self.to_do = Actions.Update if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): @@ -275,17 +277,17 @@ def create_update_batchaccount(self): try: if self.to_do == Actions.Create: - response = self.mgmt_client.batch_account.create(resource_group_name=self.resource_group, - account_name=self.name, - parameters=self.batch_account) + response = self.mgmt_client.batch_account.begin_create(resource_group_name=self.resource_group, + account_name=self.name, + parameters=self.batch_account) else: response = self.mgmt_client.batch_account.update(resource_group_name=self.resource_group, account_name=self.name, - tags=self.tags, - auto_storage=self.batch_account.get('auto_storage')) - if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller): + parameters=dict(tags=self.tags, + auto_storage=self.batch_account.get('self.batch_account'))) + if isinstance(response, LROPoller): response = self.get_poller_result(response) - except CloudError as exc: + except Exception as exc: self.log('Error attempting to create the Batch Account instance.') self.fail("Error creating the Batch Account instance: {0}".format(str(exc))) return response.as_dict() @@ -298,13 +300,13 @@ def delete_batchaccount(self): ''' self.log("Deleting the Batch Account instance {0}".format(self.name)) try: - response = self.mgmt_client.batch_account.delete(resource_group_name=self.resource_group, - account_name=self.name) - except CloudError as e: + response = self.mgmt_client.batch_account.begin_delete(resource_group_name=self.resource_group, + account_name=self.name) + except Exception as e: self.log('Error attempting to delete the Batch Account instance.') self.fail("Error deleting the Batch Account instance: {0}".format(str(e))) - if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller): + if isinstance(response, LROPoller): response = self.get_poller_result(response) return True @@ -321,12 +323,30 @@ def get_batchaccount(self): found = True self.log("Response : {0}".format(response)) self.log("Batch Account instance : {0} found".format(response.name)) - except CloudError as e: - self.log('Did not find the Batch Account instance.') + except ResourceNotFoundError as e: + self.log('Did not find the Batch Account instance. Exception as {0}'.format(e)) if found is True: - return response.as_dict() + return self.format_item(response.as_dict()) return False + def format_item(self, item): + result = { + 'id': item['id'], + 'name': item['name'], + 'type': item['type'], + 'location': item['location'], + 'account_endpoint': item['account_endpoint'], + 'provisioning_state': item['provisioning_state'], + 'pool_allocation_mode': item['pool_allocation_mode'], + 'auto_storage': item['auto_storage'], + 'dedicated_core_quota': item['dedicated_core_quota'], + 'low_priority_core_quota': item['low_priority_core_quota'], + 'pool_quota': item['pool_quota'], + 'active_job_and_job_schedule_quota': item['active_job_and_job_schedule_quota'], + 'tags': item.get('tags') + } + return result + def main(): """Main execution""" diff --git a/plugins/modules/azure_rm_batchaccount_info.py b/plugins/modules/azure_rm_batchaccount_info.py new file mode 100644 index 000000000..eb7f6e38b --- /dev/null +++ b/plugins/modules/azure_rm_batchaccount_info.py @@ -0,0 +1,196 @@ +#!/usr/bin/python +# +# Copyright (c) 2023 xuzhang3 (@xuzhang3), Fred-sun (@Fred-sun) +# +# 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 + +DOCUMENTATION = ''' +--- +module: azure_rm_batchaccount_info +version_added: "0.1.2" +short_description: Get the Batch Account on Azure facts +description: + - Get the Batch Account on Azure facts. + +options: + resource_group: + description: + - The name of the resource group in which to create the Batch Account. + type: str + name: + description: + - The name of the Batch Account. + type: str + tags: + description: + - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. + type: list + elements: str + +extends_documentation_fragment: + - azure.azcollection.azure + +author: + - xuzhang3 (@xuzhang3) + - Fred Sun (@Fred-sun) +''' + +EXAMPLES = ''' + - name: Get the Batch Account by name + azure_rm_batchaccount_info: + resource_group: MyResGroup + name: mybatchaccount + + - name: List the Batch Account by subscription + azure_rm_batchaccount_info: + tags: + - key1 +''' + +RETURN = ''' +id: + description: + - The ID of the Batch account. + returned: always + type: str + sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Batch/batchAccounts/sampleacct" +account_endpoint: + description: + - The account endpoint used to interact with the Batch service. + returned: always + type: str + sample: sampleacct.westus.batch.azure.com +''' + +from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt + +try: + from azure.core.exceptions import ResourceNotFoundError + from azure.mgmt.batch import BatchManagementClient +except ImportError: + # This is handled in azure_rm_common + pass + + +class AzureRMBatchAccountInfo(AzureRMModuleBaseExt): + """Configuration class for an Azure RM Batch Account resource""" + + def __init__(self): + self.module_arg_spec = dict( + resource_group=dict( + type='str', + ), + name=dict( + type='str', + ), + tags=dict( + type='list', + elements='str' + ) + ) + + self.resource_group = None + self.name = None + self.tags = None + + self.results = dict(changed=False) + self.mgmt_client = None + + super(AzureRMBatchAccountInfo, 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()) + ['tags']: + setattr(self, key, kwargs[key]) + + response = [] + + self.mgmt_client = self.get_mgmt_svc_client(BatchManagementClient, + base_url=self._cloud_environment.endpoints.resource_manager, + is_track2=True) + + if self.resource_group is not None and self.name is not None: + response = [self.get_batchaccount()] + elif self.resource_group is not None: + response = self.list_by_resourcegroup() + else: + response = self.list_all() + + self.results['batch_account'] = [self.format_item(item) for item in response if item and self.has_tags(item.get('tags'), self.tags)] + + return self.results + + def list_by_resourcegroup(self): + self.log("List all Batch Account in the rsource group {0}".format(self.resource_group)) + result = [] + response = [] + try: + response = self.mgmt_client.batch_account.list_by_resource_group(resource_group_name=self.resource_group) + self.log("Response : {0}".format(response)) + except Exception as e: + self.log('Did not find the Batch Account instance. Exception as {0}'.format(e)) + for item in response: + result.append(item.as_dict()) + return result + + def list_all(self): + self.log("List all Batch Account in the same subscritpion") + result = [] + response = [] + try: + response = self.mgmt_client.batch_account.list() + self.log("Response : {0}".format(response)) + except Exception as e: + self.log('Did not find the Batch Account instance.') + for item in response: + result.append(item.as_dict()) + return result + + def get_batchaccount(self): + ''' + Gets the properties of the specified Batch Account + :return: deserialized Batch Account instance state dictionary + ''' + self.log("Checking if the Batch Account instance {0} is present".format(self.name)) + try: + response = self.mgmt_client.batch_account.get(resource_group_name=self.resource_group, + account_name=self.name) + self.log("Response : {0}".format(response)) + self.log("Batch Account instance : {0} found".format(response.name)) + except ResourceNotFoundError as e: + self.log('Did not find the Batch Account instance.') + return + return response.as_dict() + + def format_item(self, item): + result = { + 'id': item['id'], + 'name': item['name'], + 'type': item['type'], + 'location': item['location'], + 'account_endpoint': item['account_endpoint'], + 'provisioning_state': item['provisioning_state'], + 'pool_allocation_mode': item['pool_allocation_mode'], + 'auto_storage': item['auto_storage'], + 'dedicated_core_quota': item['dedicated_core_quota'], + 'low_priority_core_quota': item['low_priority_core_quota'], + 'pool_quota': item['pool_quota'], + 'active_job_and_job_schedule_quota': item['active_job_and_job_schedule_quota'], + 'tags': item.get('tags') + } + return result + + +def main(): + """Main execution""" + AzureRMBatchAccountInfo() + + +if __name__ == '__main__': + main() diff --git a/requirements-azure.txt b/requirements-azure.txt index a72560210..68526c81f 100644 --- a/requirements-azure.txt +++ b/requirements-azure.txt @@ -7,7 +7,7 @@ azure-common==1.1.11 azure-identity==1.7.0 azure-mgmt-authorization==2.0.0 azure-mgmt-apimanagement==3.0.0 -azure-mgmt-batch==5.0.1 +azure-mgmt-batch==16.2.0 azure-mgmt-cdn==11.0.0 azure-mgmt-compute==26.1.0 azure-mgmt-containerinstance==9.0.0 diff --git a/tests/integration/targets/azure_rm_batchaccount/tasks/main.yml b/tests/integration/targets/azure_rm_batchaccount/tasks/main.yml index e62cb67cf..255a20afd 100644 --- a/tests/integration/targets/azure_rm_batchaccount/tasks/main.yml +++ b/tests/integration/targets/azure_rm_batchaccount/tasks/main.yml @@ -31,6 +31,9 @@ auto_storage_account: name: "{{ storage_account_name }}" pool_allocation_mode: batch_service + tags: + key1: value1 + key2: value2 register: output - name: Assert the resource was created @@ -46,6 +49,9 @@ auto_storage_account: name: "{{ storage_account_name }}" pool_allocation_mode: batch_service + tags: + key1: value1 + key2: value2 register: output - name: Assert the resource was created @@ -53,14 +59,22 @@ that: - not output.changed +- name: Get Batch Account facts + azure_rm_batchaccount_info: + resource_group: "{{ resource_group }}" + name: "{{ batch_account_name }}" + register: output + +- name: Assert the facts + assert: + that: + - output.batch_account | length == 1 + - output.batch_account[0].tags | length == 2 + - name: Delete Batch Account azure_rm_batchaccount: resource_group: "{{ resource_group }}" name: "{{ batch_account_name }}" - location: eastus - auto_storage_account: - name: "{{ storage_account_name }}" - pool_allocation_mode: batch_service state: absent register: output