Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_ml_batch_endpoint_invoke.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_endpoint_invoke
11 version_added: "3.18.0"
12 short_description: Invoke ML Batch Endpoint resources
13 description:
14 - Invoke ML Batch Endpoint resources.
15 options:
16 name:
17 description:
18 - Name of the Azure ML batch endpoint.
19 type: str
20 required: false
21 resource_group:
22 description:
23 - Name of resource group.
24 required: true
25 type: str
26 ml_workspace:
27 description:
28 - Name of the Azure ML workspace.
29 required: true
30 type: str
31 invocation_definition:
32 description:
33 - Batch Endpoint Invocations definition in YAML.
34 required: false
35 type: str
36 deployment_name:
37 description:
38 - Name of the deployment to target.
39 required: false
40 type: str
41 experiment_name:
42 description:
43 - Name of the experiment for pipeline component deployment.
44 required: false
45 type: str
46 input:
47 description:
48 - Reference to input data to use for batch inferencing.
49 It can be a path on the datastore, public URI, a registered
50 data asset, or a local folder path.
51 required: false
52 type: str
53 input_type:
54 description:
55 - Type of the input, specifying whether it's a file or a folder.
56 Use this when you are using a path on datastore or public URI.
57 required: false
58 type: str
59 choices:
60 - uri_folder
61 - uri_file
62 inputs:
63 description:
64 - Dictionary of Inputs of invoke jobs.
65 required: false
66 type: dict
67 instance_count:
68 description:
69 - Number of instances the prediction will run on.
70 required: false
71 type: int
72 job_name:
73 description:
74 - Name of the job for batch invoke.
75 required: false
76 type: str
77 mini_batch_size:
78 description:
79 - Size of each mini batch that the input data will be split into
80 for prediction.
81 required: false
82 type: int
83 output_path:
84 description:
85 - Path on the datastore where output files will be uploaded to.
86 required: false
87 type: str
88 outputs:
89 description:
90 - Dictionary to specify where to store the results.
91 required: false
92 type: dict
93
94 extends_documentation_fragment:
95 - azure.azcollection.azure
96
97 author:
98 - Bill Peck (@p3ck)
99 '''
100
101 EXAMPLES = '''
102 - name: Invoke ML Batch Endpoint
103 azure.azcollection.azure_rm_ml_batch_endpoint_invoke:
104 resource_group: myResourceGroup
105 ml_workspace: myMLWorkspace
106 '''
107
108 RETURN = '''
109 changed:
110 description:
111 - Will return True if successfully invoked
112 returned: always
113 type: bool
114 sample: true
115 ml_batch_endpoint_invoke:
116 description:
117 - Batch Endpoints that match the query.
118 returned: always
119 type: dict
120 sample: {
121 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-batch_endpoint_invoke/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/batchEndpoints//jobs/pipelinejob-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
122 "name": "pipelinejob-xxxxxxxx-xxxx-xxxxxxxxx-xxxxxxxxxxxx",
123 "properties": {
124 "compute": {
125 "is_local": false
126 },
127 "interaction_endpoints": {
128 "Studio": {
129 "endpoint": "https://ml.azure.com/runs/pipelinejob-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx?wsid=/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/xxxxx-ml-batch_endpoint_invoke/workspaces/workspace-xxxxxxxxxx",
130 "job_endpoint_type": "Studio"
131 },
132 "Tracking": {
133 "endpoint": "azureml://eastus.api.azureml.ms/mlflow/v1.0/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-batch_endpoint_invoke/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx?",
134 "job_endpoint_type": "Tracking"
135 }
136 },
137 "name": "bold_egg_xxxxxxxx",
138 "output": {},
139 "properties": {
140 "azureml.DatasetAccessMode": "Asset",
141 "azureml.DevPlatv2": "true",
142 "azureml.SourceComponentId": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-batch_endpoint_invoke/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/components/hello_batch/versions/1",
143 "azureml.continue_on_failed_optional_input": "True",
144 "azureml.continue_on_step_failure": "True",
145 "azureml.defaultComputeName": "batch-cluster",
146 "azureml.defaultDataStoreName": "workspaceblobstore",
147 "azureml.deploymentname": "deployment-xxxxxxxxxx-ansible",
148 "azureml.endpointname": "endpoint-xxxxxxxxxx-ansible",
149 "azureml.enforceRerun": "False",
150 "azureml.parameters": "{}",
151 "azureml.pipelineComponent": "pipelinerun",
152 "azureml.runLineageType": "batchDeployment",
153 "azureml.runsource": "azureml.PipelineRun",
154 "azureml.sourcepipelinerunid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
155 "runSource": "BatchDeployment",
156 "runType": "HTTP"
157 },
158 "provisioning_state": "Succeeded",
159 "status": "Preparing",
160 "tags": {
161 "azureml.batchrun": "true",
162 "azureml.deploymentname": "deployment-xxxxxxxxxx-ansible",
163 "azureml.jobtype": "azureml.pipelinejob"
164 }
165 },
166 "system_data": {
167 "created_at": "2026-05-04T13:56:02.890323Z",
168 "created_by": "xxxx xxxx-xxxxxxxxxx",
169 "last_modified_at": "2026-05-04T13:56:02.890323Z",
170 "last_modified_by": "xxxx xxxx-xxxxxxxxxx"
171 },
172 "type": "Microsoft.MachineLearningServices/workspaces/batchEndpoints/jobs"
173 }
174 ''' # NOQA
175
176
177 try:
178 import io
179 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ml import MLClientCommon
180 from azure.core.exceptions import ResourceNotFoundError
181 from azure.ai.ml.constants._endpoint import BatchEndpointInvoke, EndpointYamlFields
182 from azure.ai.ml.constants._common import ARM_ID_PREFIX, AssetTypes, InputTypes
183 from azure.ai.ml.entities._inputs_outputs import Input, Output
184 from azure.ai.ml.entities._load_functions import _try_load_yaml_dict
185 from azure.ai.ml._utils._arm_id_utils import parse_name_version, remove_aml_prefix
186 from azure.ai.ml._utils._storage_utils import AzureMLDatastorePathUri
187 except ImportError:
188 # This is handled in azure_rm_common
189 pass
190
191
192 class AzureRMMLBatchEndpointInvoke(MLClientCommon):
193 def __init__(self):
194
195 self.module_arg_spec = dict(
196 name=dict(
197 type='str',
198 required=False,
199 ),
200 resource_group=dict(
201 type='str',
202 required=True,
203 ),
204 ml_workspace=dict(
205 type='str',
206 required=True,
207 ),
208 invocation_definition=dict(
209 type='str',
210 required=False,
211 ),
212 deployment_name=dict(
213 type='str',
214 required=False,
215 ),
216 experiment_name=dict(
217 type='str',
218 required=False,
219 ),
220 input=dict(
221 type='str',
222 required=False,
223 ),
224 input_type=dict(
225 type='str',
226 required=False,
227 choices=['uri_folder', 'uri_file'],
228 ),
229 inputs=dict(
230 type='dict',
231 required=False,
232 ),
233 instance_count=dict(
234 type='int',
235 required=False,
236 ),
237 job_name=dict(
238 type='str',
239 required=False,
240 ),
241 mini_batch_size=dict(
242 type='int',
243 required=False,
244 ),
245 output_path=dict(
246 type='str',
247 required=False,
248 ),
249 outputs=dict(
250 type='dict',
251 required=False,
252 ),
253 )
254
255 self._client = None
256 self.ml_registry = None
257
258 self.results = dict(
259 ml_batch_endpoint_invoke=None,
260 changed=False,
261 )
262
263 required_if = [
264 ('invocation_definition', None, ['name'])
265 ]
266
267 super(AzureRMMLBatchEndpointInvoke, self).__init__(self.module_arg_spec,
268 supports_tags=False,
269 supports_check_mode=False,
270 facts_module=True,
271 required_if=required_if,
272 )
273
274 def exec_module(self, **kwargs):
275
276 for key in list(self.module_arg_spec.keys()):
277 setattr(self, key, kwargs[key])
278
279 params_override = []
280 input = None
281 inputs = None
282 outputs = None
283
284 try:
285 if self.deployment_name:
286 self.client.batch_endpoints._validate_deployment_name(
287 self.name, self.deployment_name
288 )
289
290 if self.invocation_definition:
291 invocation_definition = io.StringIO(self.invocation_definition)
292 batch_endpoint_invocation = _try_load_yaml_dict(invocation_definition)
293
294 inputs_dict = batch_endpoint_invocation.get(BatchEndpointInvoke.INPUTS)
295 if inputs_dict:
296 inputs = _parse_inputs(inputs_dict)
297 outputs_dict = batch_endpoint_invocation.get(BatchEndpointInvoke.OUTPUTS)
298 if outputs_dict:
299 outputs = {}
300 for key, data in outputs_dict.items():
301 output = Output(
302 type=data.get(BatchEndpointInvoke.TYPE),
303 path=data.get(BatchEndpointInvoke.PATH),
304 mode=data.get(BatchEndpointInvoke.MODE),
305 )
306 outputs[key] = output
307 if not self.deployment_name:
308 self.deployment_name = batch_endpoint_invocation.get(BatchEndpointInvoke.DEPLOYMENT)
309 if not self.name:
310 self.name = batch_endpoint_invocation.get(BatchEndpointInvoke.ENDPOINT)
311 elif self.input or self.input_type:
312 if self.input and not self.input_type:
313 if self.input.startswith(ARM_ID_PREFIX): # azureml:data:version
314 self.input = remove_aml_prefix(self.input)
315 asset_name, asset_version = parse_name_version(self.input)
316 try:
317 data = self.client.data.get(asset_name, asset_version)
318 # invoke input should be of type Input based on the data type
319 if data.type == AssetTypes.URI_FOLDER:
320 input = Input(type=AssetTypes.URI_FOLDER, path=data.id)
321 elif data.type == AssetTypes.URI_FILE:
322 input = Input(type=AssetTypes.URI_FILE, path=data.id)
323 except ResourceNotFoundError:
324 # We have a case that the input is not a registered data asset
325 self.fail(
326 "Value passed to input is not a supported data. "
327 "Please use an Azure Machine Learning registered V2 data asset "
328 "(with the type of either `uri_file` or `uri_folder`). Refer to how-to guide for "
329 "batch endpoint for more information on supported input data types."
330 )
331 else: # ./path
332 input = Input(type=AssetTypes.URI_FOLDER, path=self.input)
333 elif self.input_type == AssetTypes.URI_FOLDER:
334 input = Input(type=AssetTypes.URI_FOLDER, path=self.input)
335 elif self.input_type == AssetTypes.URI_FILE:
336 input = Input(type=AssetTypes.URI_FILE, path=self.input)
337 else:
338 self.fail(
339 "Unsupported input please use either a path on the datastore, "
340 "public URI, a registered data asset, or a local folder path."
341 )
342 properties = {}
343 if self.mini_batch_size:
344 params_override.append({EndpointYamlFields.MINI_BATCH_SIZE: self.mini_batch_size})
345 if self.instance_count:
346 params_override.append({EndpointYamlFields.BATCH_JOB_INSTANCE_COUNT: self.instance_count})
347 if self.output_path:
348 try:
349 output = validate_and_split_output_path(self.output_path)
350 except ValueError as err:
351 self.fail(err)
352 params_override.append(
353 {EndpointYamlFields.BATCH_JOB_OUTPUT_PATH: output.path}
354 )
355 params_override.append(
356 {EndpointYamlFields.BATCH_JOB_OUTPUT_DATSTORE: "azureml:" + output.datastore}
357 )
358 if self.job_name:
359 params_override.append(
360 {EndpointYamlFields.BATCH_JOB_NAME: self.job_name}
361 )
362 if self.experiment_name:
363 properties["experimentName"] = self.experiment_name
364 if properties:
365 params_override.append(
366 {EndpointYamlFields.BATCH_JOB_PROPERTIES: properties}
367 )
368 if self.inputs:
369 inputs = _parse_inputs(self.inputs)
370 if self.outputs:
371 outputs = {}
372 for key, data in self.outputs.items():
373 output = Output(
374 type=data.get(BatchEndpointInvoke.TYPE),
375 path=data.get(BatchEndpointInvoke.PATH),
376 mode=data.get(BatchEndpointInvoke.MODE),
377 )
378 outputs[key] = output
379
380 ml_batch_endpoint_invoke = self.client.batch_endpoints.invoke(
381 endpoint_name=self.name,
382 input=input,
383 inputs=inputs,
384 outputs=outputs,
385 deployment_name=self.deployment_name,
386 params_override=params_override,
387 )
388
389 except Exception as err:
390 if isinstance(err, ResourceNotFoundError) and self.deployment_name is None:
391 self.fail("Set a default deployment or provide a deployment name.")
392 else:
393 self.fail(err)
394
395 self.results['ml_batch_endpoint_invoke'] = self.entity_to_dict(
396 ml_batch_endpoint_invoke
397 )
398 self.results['changed'] = True
399 return self.results
400
401 def get(self, name):
402 try:
403 result = self.client.batch_endpoints.get(name=name)
404 ml_batch_endpoint = self.entity_to_dict(result)
405 jobs = self.client.batch_endpoints.list_jobs(endpoint_name=name)
406 ml_batch_endpoint['jobs'] = jobs
407 except ResourceNotFoundError:
408 ml_batch_endpoint = None
409
410 return ml_batch_endpoint
411
412
413 def _parse_inputs(inputs_dict):
414 inputs = {}
415 if inputs_dict:
416 for key, data in inputs_dict.items():
417 if isinstance(data, str):
418 inputs[key] = Input(type=InputTypes.STRING, default=data)
419 elif isinstance(data, bool):
420 inputs[key] = Input(type=InputTypes.BOOLEAN, default=data)
421 elif isinstance(data, int):
422 inputs[key] = Input(type=InputTypes.INTEGER, default=data)
423 elif isinstance(data, float):
424 inputs[key] = Input(type=InputTypes.NUMBER, default=data)
425 else:
426 if data.get(BatchEndpointInvoke.TYPE) in [InputTypes.NUMBER, InputTypes.INTEGER]:
427 inputs[key] = Input(
428 type=data.get(BatchEndpointInvoke.TYPE, None),
429 default=data.get(BatchEndpointInvoke.DEFAULT, None),
430 min=data.get(BatchEndpointInvoke.MIN, None),
431 max=data.get(BatchEndpointInvoke.MAX, None),
432 )
433 elif data.get(BatchEndpointInvoke.TYPE) in [InputTypes.STRING, InputTypes.BOOLEAN]:
434 inputs[key] = Input(
435 type=data.get(BatchEndpointInvoke.TYPE, None),
436 default=data.get(BatchEndpointInvoke.DEFAULT, None),
437 )
438 else:
439 inputs[key] = Input(
440 type=data.get(BatchEndpointInvoke.TYPE, None),
441 path=data.get(BatchEndpointInvoke.PATH, None),
442 mode=data.get(BatchEndpointInvoke.MODE, None),
443 )
444 return inputs
445
446
447 def validate_and_split_output_path(output_path):
448 if output_path.startswith(ARM_ID_PREFIX):
449 datastore_path = AzureMLDatastorePathUri(output_path)
450 return datastore_path
451 raise ValueError("Not a valid output_path, it should start with 'azureml:'")
452
453
454 def main():
455 AzureRMMLBatchEndpointInvoke()
456
457
458 if __name__ == '__main__':
459 main()