Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2019 Junyi Yi (@JunyiYi)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 # ----------------------------------------------------------------------------
8 #
9 # *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
10 #
11 # ----------------------------------------------------------------------------
12 #
13 # This file is automatically generated by Magic Modules and manual
14 # changes will be clobbered when the file is regenerated.
15 #
16 #
17 # ----------------------------------------------------------------------------
18
19 from __future__ import absolute_import, division, print_function
20 __metaclass__ = type
21
22 DOCUMENTATION = '''
23 ---
24 module: azure_rm_batchaccount
25 version_added: "0.1.2"
26 short_description: Manages a Batch Account on Azure
27 description:
28 - Create, update and delete instance of Azure Batch Account.
29
30 options:
31 resource_group:
32 description:
33 - The name of the resource group in which to create the Batch Account.
34 required: true
35 type: str
36 name:
37 description:
38 - The name of the Batch Account.
39 required: true
40 type: str
41 location:
42 description:
43 - Specifies the supported Azure location where the resource exists.
44 type: str
45 auto_storage_account:
46 description:
47 - Existing storage account with which to associate the Batch Account.
48 - It can be the storage account name which is in the same resource group.
49 - It can be the storage account ID. Fox example "/subscriptions/{subscription_id}/resourceGroups/
50 {resource_group}/providers/Microsoft.Storage/storageAccounts/{name}".
51 - It can be a dict which contains I(name) and I(resource_group) of the storage account.
52 type: raw
53 key_vault:
54 description:
55 - Existing key vault with which to associate the Batch Account.
56 - It can be the key vault name which is in the same resource group.
57 - It can be the key vault ID. For example "/subscriptions/{subscription_id}/resourceGroups/
58 {resource_group}/providers/Microsoft.KeyVault/vaults/{name}".
59 - It can be a dict which contains I(name) and I(resource_group) of the key vault.
60 type: raw
61 pool_allocation_mode:
62 description:
63 - The pool acclocation mode of the Batch Account.
64 default: batch_service
65 choices:
66 - batch_service
67 - user_subscription
68 type: str
69 state:
70 description:
71 - Assert the state of the Batch Account.
72 - Use C(present) to create or update a Batch Account and C(absent) to delete it.
73 default: present
74 type: str
75 choices:
76 - present
77 - absent
78
79 extends_documentation_fragment:
80 - azure.azcollection.azure
81 - azure.azcollection.azure_tags
82 - azure.azcollection.azure_identity_single
83
84 author:
85 - Junyi Yi (@JunyiYi)
86 '''
87
88 EXAMPLES = '''
89 - name: Create Batch Account
90 azure_rm_batchaccount:
91 resource_group: MyResGroup
92 name: mybatchaccount
93 location: eastus
94 auto_storage_account:
95 name: mystorageaccountname
96 pool_allocation_mode: batch_service
97 '''
98
99 RETURN = '''
100 id:
101 description:
102 - The ID of the Batch account.
103 returned: always
104 type: str
105 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Batch/batchAccounts/sampleacct"
106 account_endpoint:
107 description:
108 - The account endpoint used to interact with the Batch service.
109 returned: always
110 type: str
111 sample: sampleacct.westus.batch.azure.com
112 '''
113
114 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
115 from ansible.module_utils.common.dict_transformations import _snake_to_camel
116
117 try:
118 from azure.core.polling import LROPoller
119 from azure.core.exceptions import ResourceNotFoundError
120 from azure.mgmt.batch.models import BatchAccountIdentity, UserAssignedIdentities
121 except ImportError:
122 # This is handled in azure_rm_common
123 pass
124
125
126 class Actions:
127 NoAction, Create, Update, Delete = range(4)
128
129
130 class AzureRMBatchAccount(AzureRMModuleBaseExt):
131 """Configuration class for an Azure RM Batch Account resource"""
132
133 def __init__(self):
134 self.module_arg_spec = dict(
135 resource_group=dict(
136 required=True,
137 type='str'
138 ),
139 name=dict(
140 required=True,
141 type='str'
142 ),
143 location=dict(
144 type='str'
145 ),
146 auto_storage_account=dict(
147 type='raw'
148 ),
149 key_vault=dict(
150 type='raw',
151 no_log=True
152 ),
153 pool_allocation_mode=dict(
154 default='batch_service',
155 type='str',
156 choices=['batch_service', 'user_subscription']
157 ),
158 identity=dict(
159 type="dict",
160 options=self.managed_identity_single_spec
161 ),
162 state=dict(
163 type='str',
164 default='present',
165 choices=['present', 'absent']
166 )
167 )
168
169 self.resource_group = None
170 self.name = None
171 self.batch_account = dict()
172
173 self.results = dict(changed=False)
174 self.state = None
175 self.to_do = Actions.NoAction
176 self._managed_identity = None
177 self.identity = None
178
179 super(AzureRMBatchAccount, self).__init__(derived_arg_spec=self.module_arg_spec,
180 supports_check_mode=True,
181 supports_tags=True)
182
183 @property
184 def managed_identity(self):
185 if not self._managed_identity:
186 self._managed_identity = {
187 "identity": BatchAccountIdentity,
188 "user_assigned": UserAssignedIdentities,
189 }
190 return self._managed_identity
191
192 def exec_module(self, **kwargs):
193 """Main module execution method"""
194
195 for key in list(self.module_arg_spec.keys()) + ['tags']:
196 if hasattr(self, key):
197 setattr(self, key, kwargs[key])
198 elif kwargs[key] is not None:
199 self.batch_account[key] = kwargs[key]
200
201 resource_group = self.get_resource_group(self.resource_group)
202 if self.batch_account.get('location') is None:
203 self.batch_account['location'] = resource_group.location
204 if self.batch_account.get('auto_storage_account') is not None:
205 self.batch_account['auto_storage'] = {
206 'storage_account_id': self.normalize_resource_id(
207 self.batch_account.pop('auto_storage_account'),
208 '/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.Storage/storageAccounts/{name}')
209 }
210 if self.batch_account.get('key_vault') is not None:
211 id = self.normalize_resource_id(
212 self.batch_account.pop('key_vault'),
213 '/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.KeyVault/vaults/{name}')
214 url = 'https://' + id.split('/').pop() + '.vault.azure.net/'
215 self.batch_account['key_vault_reference'] = {
216 'id': id,
217 'url': url
218 }
219 self.batch_account['pool_allocation_mode'] = _snake_to_camel(self.batch_account['pool_allocation_mode'], True)
220
221 response = None
222
223 old_response = self.get_batchaccount()
224 curr_identity = old_response["identity"] if old_response else None
225
226 update_identity = False
227 if self.identity:
228 update_identity, identity_result = self.update_single_managed_identity(curr_identity=curr_identity, new_identity=self.identity)
229 self.batch_account["identity"] = identity_result.as_dict()
230
231 if not old_response:
232 self.log("Batch Account instance doesn't exist")
233 if self.state == 'absent':
234 self.log("Old instance didn't exist")
235 else:
236 self.to_do = Actions.Create
237 else:
238 self.log("Batch Account instance already exists")
239 if self.state == 'absent':
240 self.to_do = Actions.Delete
241 elif self.state == 'present':
242 self.results['old'] = old_response
243 self.results['new'] = self.batch_account
244
245 update_tags, self.tags = self.update_tags(old_response['tags'])
246
247 if self.batch_account.get('auto_storage_account') is not None:
248 if old_response['auto_storage']['storage_account_id'] != self.batch_account['auto_storage']['storage_account_id']:
249 self.to_do = Actions.Update
250 if update_tags or update_identity:
251 self.to_do = Actions.Update
252
253 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
254 self.log("Need to Create / Update the Batch Account instance")
255
256 self.results['changed'] = True
257 if self.check_mode:
258 return self.results
259
260 response = self.create_update_batchaccount()
261
262 self.log("Creation / Update done")
263 elif self.to_do == Actions.Delete:
264 self.log("Batch Account instance deleted")
265 self.results['changed'] = True
266
267 if self.check_mode:
268 return self.results
269
270 self.delete_batchaccount()
271 else:
272 self.log("Batch Account instance unchanged")
273 self.results['changed'] = False
274 response = old_response
275
276 if self.state == 'present':
277 self.results.update({
278 'id': response.get('id', None),
279 'account_endpoint': response.get('account_endpoint', None),
280 'new': response
281 })
282 return self.results
283
284 def create_update_batchaccount(self):
285 '''
286 Creates or updates Batch Account with the specified configuration.
287
288 :return: deserialized Batch Account instance state dictionary
289 '''
290 self.log("Creating / Updating the Batch Account instance {0}".format(self.name))
291
292 try:
293 if self.to_do == Actions.Create:
294 response = self.batch_account_client.batch_account.begin_create(resource_group_name=self.resource_group,
295 account_name=self.name,
296 parameters=self.batch_account)
297 else:
298 response = self.batch_account_client.batch_account.update(resource_group_name=self.resource_group,
299 account_name=self.name,
300 parameters=dict(tags=self.tags,
301 auto_storage=self.batch_account.get('auto_storage'),
302 identity=self.batch_account.get('identity')))
303 if isinstance(response, LROPoller):
304 response = self.get_poller_result(response)
305 except Exception as exc:
306 self.log('Error attempting to create the Batch Account instance.')
307 self.fail("Error creating the Batch Account instance: {0}".format(str(exc)))
308 return response.as_dict()
309
310 def delete_batchaccount(self):
311 '''
312 Deletes specified Batch Account instance in the specified subscription and resource group.
313
314 :return: True
315 '''
316 self.log("Deleting the Batch Account instance {0}".format(self.name))
317 try:
318 response = self.batch_account_client.batch_account.begin_delete(resource_group_name=self.resource_group,
319 account_name=self.name)
320 except Exception as e:
321 self.log('Error attempting to delete the Batch Account instance.')
322 self.fail("Error deleting the Batch Account instance: {0}".format(str(e)))
323
324 if isinstance(response, LROPoller):
325 response = self.get_poller_result(response)
326 return True
327
328 def get_batchaccount(self):
329 '''
330 Gets the properties of the specified Batch Account
331 :return: deserialized Batch Account instance state dictionary
332 '''
333 self.log("Checking if the Batch Account instance {0} is present".format(self.name))
334 found = False
335 try:
336 response = self.batch_account_client.batch_account.get(resource_group_name=self.resource_group,
337 account_name=self.name)
338 found = True
339 self.log("Response : {0}".format(response))
340 self.log("Batch Account instance : {0} found".format(response.name))
341 except ResourceNotFoundError as e:
342 self.log('Did not find the Batch Account instance. Exception as {0}'.format(e))
343 if found is True:
344 return self.format_item(response.as_dict())
345 return False
346
347 def format_item(self, item):
348 result = {
349 'id': item['id'],
350 'name': item['name'],
351 'type': item['type'],
352 'location': item['location'],
353 'account_endpoint': item['account_endpoint'],
354 'provisioning_state': item['provisioning_state'],
355 'pool_allocation_mode': item['pool_allocation_mode'],
356 'auto_storage': item['auto_storage'],
357 'dedicated_core_quota': item['dedicated_core_quota'],
358 'low_priority_core_quota': item['low_priority_core_quota'],
359 'pool_quota': item['pool_quota'],
360 'active_job_and_job_schedule_quota': item['active_job_and_job_schedule_quota'],
361 'tags': item.get('tags'),
362 'identity': item.get('identity')
363 }
364 return result
365
366
367 def main():
368 """Main execution"""
369 AzureRMBatchAccount()
370
371
372 if __name__ == '__main__':
373 main()