Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade azure mgmt batch 17.0.0 #1202

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 43 additions & 23 deletions plugins/modules/azure_rm_batchaccount.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand All @@ -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):
Expand Down Expand Up @@ -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()
Expand All @@ -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

Expand All @@ -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"""
Expand Down
196 changes: 196 additions & 0 deletions plugins/modules/azure_rm_batchaccount_info.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 1 addition & 1 deletion requirements-azure.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,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
Expand Down
22 changes: 18 additions & 4 deletions tests/integration/targets/azure_rm_batchaccount/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -46,21 +49,32 @@
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
assert:
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

Expand Down