Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8 DOCUMENTATION = '''
9 ---
10 module: azure_rm_ml_batch_deployment
11 version_added: "3.18.0"
12 short_description: Create, Delete for an Azure Machine Learning Batch Deployment
13 description:
14 - Create, Delete for an Azure Machine Learning Batch Deployment.
15 options:
16 name:
17 description:
18 - Name of the Azure ML batch_deployment.
19 type: str
20 required: false
21 endpoint_name:
22 description:
23 - Name of the batch endpoint. If not specified here will need to
24 be referenced in the I(resource_definition).
25 type: str
26 required: false
27 resource_group:
28 description:
29 - Name of resource group.
30 required: true
31 type: str
32 ml_workspace:
33 description:
34 - Name of the Azure ML workspace.
35 required: true
36 type: str
37 resource_definition:
38 description:
39 - Batch Deployment definition in YAML
40 type: str
41 required: false
42 description:
43 description:
44 - Description of the batch_deployment.
45 type: str
46 set_default:
47 description:
48 - Sets endpoint defaults.deployment_name to this deployment
49 after successful creation.
50 type: bool
51 default: false
52 state:
53 description:
54 - State of the Batch Deployment. Use C(present) to create
55 or update.
56 default: present
57 type: str
58 choices:
59 - present
60 - absent
61
62 extends_documentation_fragment:
63 - azure.azcollection.azure
64 - azure.azcollection.azure_tags
65
66 author:
67 - Bill Peck (@p3ck)
68 '''
69
70 EXAMPLES = '''
71 - name: Create ML Batch Deployment
72 azure.azcollection.azure_rm_ml_batch_deployment:
73 endpoint_name: endpoint-command-ansible
74 resource_group: xxxxx-ml-batch_deployment
75 ml_workspace: workspace-xxxxxxxxxx
76 resource_definition: |
77 $schema: https://azuremlschemas.azureedge.net/latest/pipelineComponentBatchDeployment.schema.json
78 name: {{ batch_deployment_name }}
79 endpoint_name: hello-pipeline-batch
80 type: pipeline
81 component: azureml:hello_batch@latest
82 settings:
83 default_compute: batch-cluster
84 '''
85
86 RETURN = '''
87 changed:
88 description:
89 - Whether the resource is changed.
90 returned: always
91 type: bool
92 sample: false
93 ml_batch_deployment:
94 description:
95 - Batch Deployment that was just created or updated.
96 returned: always
97 type: dict
98 sample: {
99 "creation_context": {
100 "created_at": "2026-04-24T15:39:01.058441+00:00",
101 "created_by": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
102 "last_modified_at": "2026-04-24T15:39:01.058431+00:00"
103 },
104 "endpoint_name": "endpoint-command-ansible",
105 "environment_variables": {},
106 "error_threshold": 0,
107 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-batch_deployment/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/batchEndpoints/endpoint-command-ansible/deployments/deployment-command-xxxxxxxxxx",
108 "jobs": [],
109 "logging_level": "Info",
110 "max_concurrency_per_instance": 0,
111 "mini_batch_size": 0,
112 "name": "deployment-command-xxxxxxxxxx",
113 "output_action": "summary_only",
114 "properties": {
115 "componentDeployment.Settings.continue_on_step_failure": null,
116 "default_compute": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-batch_deployment/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/computes/batch-cluster",
117 "default_datastore": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-batch_deployment/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/datastores/workspaceblobstore",
118 "deployment_configuration_type": "PipelineComponent"
119 },
120 "provisioning_state": "Succeeded",
121 "resources": {
122 "instance_count": 1,
123 "properties": {}
124 },
125 "retry_settings": {
126 "max_retries": 0,
127 "timeout": 0
128 },
129 "tags": {
130 "PipelineDeployment.ComponentId": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-batch_deployment/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/components/hello_batch/versions/1"
131 }
132 }
133 ''' # NOQA
134
135
136 try:
137 import io
138 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ml import MLClientCommon
139 from azure.core.exceptions import ResourceNotFoundError
140 from azure.ai.ml.exceptions import ValidationException
141 from azure.ai.ml.entities._load_functions import load_batch_deployment
142 from azure.ai.ml.entities._load_functions import (
143 load_batch_deployment, _try_load_yaml_dict,
144 load_pipeline_component_batch_deployment,
145 load_model_batch_deployment
146 )
147 from azure.ai.ml.constants._deployment import BatchDeploymentType
148 except ImportError:
149 # This is handled in azure_rm_common
150 pass
151
152
153 class AzureRMMLBatchDeployment(MLClientCommon):
154
155 UPDATE_OVERRIDES = ['description',
156 'tags',
157 'endpoint_name']
158
159 PARAM_OVERRIDES = UPDATE_OVERRIDES + ['name']
160
161 def __init__(self):
162
163 self.module_arg_spec = dict(
164 name=dict(
165 type='str',
166 required=False,
167 ),
168 endpoint_name=dict(
169 type='str',
170 required=False,
171 ),
172 resource_definition=dict(
173 type='str',
174 required=False,
175 ),
176 resource_group=dict(
177 type='str',
178 required=True,
179 ),
180 ml_workspace=dict(
181 type='str',
182 required=True,
183 ),
184 description=dict(
185 type='str',
186 required=False,
187 ),
188 set_default=dict(
189 type='bool',
190 default=False,
191 ),
192 state=dict(
193 type='str',
194 default='present',
195 choices=['present', 'absent'],
196 ),
197 )
198
199 self._client = None
200 self.ml_registry = None
201 self.state = None
202
203 self.results = dict(
204 changed=False,
205 compare=[],
206 ml_batch_deployment={}
207 )
208
209 required_if = [
210 ('state', 'present', ['resource_definition']),
211 ('resource_definition', None, ['name', 'endpoint_name'])
212 ]
213
214 super(AzureRMMLBatchDeployment, self).__init__(self.module_arg_spec,
215 supports_check_mode=True,
216 required_if=required_if,
217 )
218
219 def exec_module(self, **kwargs):
220
221 for key in list(self.module_arg_spec.keys()) + ['tags']:
222 setattr(self, key, kwargs[key])
223
224 changed = False
225
226 # Process resource_file yaml and passed in parameters
227 try:
228 resource_definition = io.StringIO(self.resource_definition)
229 yaml_dict = _try_load_yaml_dict(resource_definition)
230 except ValidationException:
231 yaml_dict = dict()
232 deployment_name = self.name or yaml_dict.get('name', None)
233 endpoint_name = self.endpoint_name or yaml_dict.get('endpoint_name', None)
234
235 ml_batch_deployment_info = self.get(deployment_name,
236 endpoint_name)
237
238 if self.state == 'present':
239
240 if ml_batch_deployment_info:
241 # Update
242 resource_definition = io.StringIO(self.resource_definition)
243 params_override = self.update_params(
244 kwargs,
245 self.UPDATE_OVERRIDES,
246 ml_batch_deployment=ml_batch_deployment_info
247 )
248 ml_batch_deployment = self.get_model(yaml_dict,
249 resource_definition,
250 params_override)
251
252 orig_deployment_info = self.entity_to_dict(ml_batch_deployment_info)
253 orig_deployment_info.pop('creation_context')
254 if not self.check_mode:
255 # If requested make this deployment the default for the endpoint
256 endpoint_changed = False
257 if self.set_default:
258 endpoint = self.client.batch_endpoints.get(
259 ml_batch_deployment.endpoint_name
260 )
261 if endpoint.defaults.deployment_name != ml_batch_deployment.name:
262
263 endpoint.defaults = {"deployment_name": ml_batch_deployment.name}
264 endpoint = self.client.begin_create_or_update(entity=endpoint)
265 endpoint = self.get_poller_result(endpoint)
266 endpoint_changed = True
267 response = self.client.begin_create_or_update(
268 entity=ml_batch_deployment
269 )
270 ml_batch_deployment_object = self.get_poller_result(response)
271 ml_batch_deployment_info = self.entity_to_dict(ml_batch_deployment_object)
272 new_deployment_info = self.entity_to_dict(
273 self.get(deployment_name, endpoint_name)
274 )
275 new_deployment_info.pop('creation_context')
276 changed = not self.default_compare(
277 {},
278 new_deployment_info,
279 orig_deployment_info,
280 '',
281 self.results
282 )
283 # We flag as changed on either endpoint default or deployment
284 changed = changed or endpoint_changed
285 else:
286 # Create
287 params_override = self.update_params(kwargs,
288 self.PARAM_OVERRIDES)
289 resource_definition = io.StringIO(self.resource_definition)
290
291 ml_batch_deployment = self.get_model(yaml_dict,
292 resource_definition,
293 params_override)
294 changed = True
295 if not self.check_mode:
296 response = self.client.begin_create_or_update(
297 entity=ml_batch_deployment
298 )
299 ml_batch_deployment = self.get_poller_result(response)
300 ml_batch_deployment_info = self.entity_to_dict(ml_batch_deployment)
301 # If requested make this deployment the default for the endpoint
302 if self.set_default:
303 endpoint = self.client.batch_endpoints.get(
304 ml_batch_deployment.endpoint_name
305 )
306 endpoint.defaults = {"deployment_name": ml_batch_deployment.name}
307 endpoint = self.client.begin_create_or_update(entity=endpoint)
308 endpoint = self.get_poller_result(endpoint)
309 elif self.state == 'absent':
310 if ml_batch_deployment_info:
311 # Delete
312 changed = True
313 if not self.check_mode:
314 response = self.client.batch_deployments.begin_delete(
315 name=deployment_name,
316 endpoint_name=endpoint_name
317 )
318 ml_batch_deployment_info = self.get_poller_result(response)
319
320 self.results['ml_batch_deployment'] = ml_batch_deployment_info
321 self.results['changed'] = changed
322 return self.results
323
324 def update_params(self, kwargs, param_overrides, ml_batch_deployment=None):
325 params_override = []
326
327 skip_params = ["creation_context", "properties", "id", "output_action",
328 "retry_settings", "resources", "error_threshold",
329 "provisioning_state", "environment_variables",
330 "mini_batch_size", "logging_level",
331 "max_concurrency_per_instance"]
332
333 # If ml_batch_deployment is defined use those values as a base.
334 # Update can't change some of these values but we need
335 # to keep the same values as before the update.
336 if ml_batch_deployment:
337 items = ml_batch_deployment._to_dict().items()
338 params_override = [{k: v} for k, v in items if k not in skip_params]
339
340 # Update values based on what param_overrides says we can update.
341 for key in list(self.module_arg_spec.keys()):
342 if kwargs[key] is not None and key in param_overrides:
343 params_override.append({key: kwargs[key]})
344 return params_override
345
346 def get(self, name, endpoint_name, as_dict=False):
347 try:
348 # Attempt to retrieve ml_batch_deployment based on name
349 ml_batch_deployment_info = self.client.batch_deployments.get(
350 name=name,
351 endpoint_name=endpoint_name
352 )
353 if as_dict:
354 ml_batch_deployment_info = self.entity_to_dict(ml_batch_deployment_info)
355 except ResourceNotFoundError:
356 ml_batch_deployment_info = None
357 return ml_batch_deployment_info
358
359 def get_model(self, yaml_dict, resource_definition, params_override):
360 if yaml_dict.get('type') == BatchDeploymentType.MODEL:
361 ml_batch_deployment = load_model_batch_deployment(
362 source=resource_definition,
363 params_override=params_override
364 )
365 elif yaml_dict.get('type') == BatchDeploymentType.PIPELINE:
366 ml_batch_deployment = load_pipeline_component_batch_deployment(
367 source=resource_definition,
368 params_override=params_override
369 )
370 else:
371 ml_batch_deployment = load_batch_deployment(
372 source=resource_definition,
373 params_override=params_override
374 )
375 return ml_batch_deployment
376
377
378 def main():
379 AzureRMMLBatchDeployment()
380
381
382 if __name__ == '__main__':
383 main()