Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_ml_job.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_job
11 version_added: "3.17.0"
12 short_description: Create, Cancel, Archive or Restore an Azure Machine Learning Job
13 description:
14 - Create, Cancel, Archive or Restore an Azure Machine Learning Job.
15 options:
16 name:
17 description:
18 - Name of the Azure ML job.
19 type: str
20 required: true
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 resource_definition:
32 description:
33 - Job definition in YAML
34 type: str
35 required: false
36 description:
37 description:
38 - Description of the job.
39 type: str
40 state:
41 description:
42 - State of the Job. Use C(present) to create
43 or update. C(cancel) will cancel.
44 C(archive) to archive, C(restore) to restore.
45 default: present
46 type: str
47 choices:
48 - present
49 - cancel
50 - archive
51 - restore
52
53 extends_documentation_fragment:
54 - azure.azcollection.azure
55 - azure.azcollection.azure_tags
56
57 author:
58 - Bill Peck (@p3ck)
59 '''
60
61 EXAMPLES = '''
62 - name: Create ML Job
63 azure.azcollection.azure_rm_ml_job:
64 name: jobxxxxxxxxxx
65 resource_group: xxxxx-ml-job
66 ml_workspace: workspace-xxxxxxxxxx
67 resource_definition: |
68 $schema: https://azuremlschemas.azureedge.net/latest/commandJob.schema.json
69 type: command
70 description: Trains a simple neural network on the Fashion-MNIST dataset.
71 experiment_name: "aml_command_cli"
72 compute: azureml:cluster-cpu
73 inputs:
74 fashion_mnist:
75 path: azureml:data-fashion-mnist@latest
76 outputs:
77 model:
78 type: mlflow_model
79 code: ./targets/azure_rm_ml_job/files/src
80 environment:
81 image: mcr.microsoft.com/azureml/openmpi5.0-ubuntu24.04:latest
82 conda_file: ./targets/azure_rm_ml_job/files/conda.yml
83 command: python train.py --data_dir ${{ '{{' }}inputs.fashion_mnist{{ '}}' }} --model_dir ${{ '{{' }}outputs.model{{ '}}' }}
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_job:
94 description:
95 - Job that was just created or updated.
96 returned: always
97 type: dict
98 sample: {
99 "code": "azureml:/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-job/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/codes/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/versions/1",
100 "command": "python train.py --data_dir ${{inputs.fashion_mnist}} --model_dir ${{outputs.model}}",
101 "compute": "azureml:cluster-cpu",
102 "creation_context": {
103 "created_at": "2026-03-31T17:55:36.317328+00:00",
104 "created_by": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
105 "created_by_type": "Application"
106 },
107 "description": "Trains a simple neural network on the Fashion-MNIST dataset.",
108 "display_name": "jobxxxxxxxxxx",
109 "environment": "azureml:CliV2AnonymousEnvironment:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
110 "environment_variables": {},
111 "experiment_name": "aml_command_cli",
112 "id": "azureml:/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-job/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/jobs/jobxxxxxxxxxx",
113 "inputs": {
114 "fashion_mnist": {
115 "mode": "ro_mount",
116 "path": "azureml:data-fashion-mnist:1",
117 "type": "uri_folder"
118 }
119 },
120 "name": "jobxxxxxxxxxx",
121 "outputs": {
122 "default": {
123 "mode": "rw_mount",
124 "path": "azureml://datastores/workspaceartifactstore/ExperimentRun/dcid.jobxxxxxxxxxx",
125 "type": "uri_folder"
126 },
127 "model": {
128 "mode": "rw_mount",
129 "type": "mlflow_model"
130 }
131 },
132 "parameters": {},
133 "properties": {
134 "ContentSnapshotId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
135 "EndTimeUtc": "2026-03-31 18:18:41",
136 "ProcessInfoFile": "azureml-logs/process_info.json",
137 "ProcessStatusFile": "azureml-logs/process_status.json",
138 "StartTimeUtc": "2026-03-31 18:14:56",
139 "_azureml.ClusterName": "cluster-cpu",
140 "_azureml.ComputeTargetType": "amlctrain"
141 },
142 "queue_settings": {
143 "job_tier": "null"
144 },
145 "resources": {
146 "instance_count": 1,
147 "properties": {},
148 "shm_size": "2g"
149 },
150 "services": {
151 "Studio": {
152 "endpoint": "https://ml.azure.com/runs/jobxxxxxxxxxx?wsid=/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/xxxxx-ml-job/workspaces/workspace-xxxxxxxxxx&tid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
153 "type": "Studio"
154 },
155 "Tracking": {
156 "endpoint": "azureml://eastus.api.azureml.ms/mlflow/v1.0/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-job/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx?",
157 "type": "Tracking"
158 }
159 },
160 "status": "Completed",
161 "tags": {},
162 "type": "command"
163 }
164 ''' # NOQA
165
166
167 try:
168 import io
169 import time
170 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ml import MLClientCommon
171 from azure.core.exceptions import ResourceNotFoundError
172 from azure.ai.ml.entities._load_functions import load_job
173 except ImportError:
174 # This is handled in azure_rm_common
175 pass
176
177
178 class AzureRMMLJob(MLClientCommon):
179
180 UPDATE_OVERRIDES = []
181
182 PARAM_OVERRIDES = UPDATE_OVERRIDES + ['name',
183 'description',
184 'tags']
185
186 def __init__(self):
187
188 self.module_arg_spec = dict(
189 name=dict(
190 type='str',
191 required=True,
192 ),
193 resource_definition=dict(
194 type='str',
195 required=False,
196 ),
197 resource_group=dict(
198 type='str',
199 required=True,
200 ),
201 ml_workspace=dict(
202 type='str',
203 required=True,
204 ),
205 description=dict(
206 type='str',
207 required=False,
208 ),
209 state=dict(
210 type='str',
211 default='present',
212 choices=['present', 'cancel', 'archive', 'restore'],
213 ),
214 )
215
216 self._client = None
217 self.ml_registry = None
218 self.state = None
219
220 self.results = dict(
221 changed=False,
222 compare=[],
223 ml_job={}
224 )
225
226 required_if = [
227 ('state', 'present', ['resource_definition'])
228 ]
229
230 super(AzureRMMLJob, self).__init__(self.module_arg_spec,
231 supports_check_mode=True,
232 required_if=required_if,
233 )
234
235 def exec_module(self, **kwargs):
236
237 for key in list(self.module_arg_spec.keys()) + ['tags']:
238 setattr(self, key, kwargs[key])
239
240 changed = False
241 ml_job_info = self.get(name=self.name)
242
243 if self.state == 'present':
244 if ml_job_info:
245 # Update
246 # No Updates are supported at this time.
247 changed = False
248 ml_job_info = self.entity_to_dict(ml_job_info)
249 else:
250 # Create
251 params_override = self.update_params(kwargs, self.PARAM_OVERRIDES)
252
253 # Generate ml_job based on ansible args passed in.
254 resource_definition = io.StringIO(self.resource_definition)
255 ml_job = load_job(source=resource_definition,
256 params_override=params_override)
257
258 changed = True
259 if not self.check_mode:
260 response = self.client.jobs.create_or_update(job=ml_job)
261 ml_job_info = self.entity_to_dict(response)
262 elif self.state == 'cancel':
263 # Cancel
264 if ml_job_info:
265 changed = True
266 if not self.check_mode:
267 self.cancel(name=self.name)
268 elif self.state == 'archive':
269 # Archive
270 list_view_type = self.get_list_view_type('active')
271 results = self.client.jobs.list(list_view_type=list_view_type)
272 ml_jobs = [x.name for x in results]
273
274 if self.name in ml_jobs:
275 changed = True
276 if not self.check_mode:
277 self.archive(name=self.name)
278 elif self.state == 'restore':
279 # Restore
280 list_view_type = self.get_list_view_type('archived')
281 results = self.client.jobs.list(list_view_type=list_view_type)
282 ml_jobs = [x.name for x in results]
283
284 if self.name in ml_jobs:
285 changed = True
286 if not self.check_mode:
287 self.restore(name=self.name)
288 # If we query too quick it hasn't fully restored.
289 # Seems the api shouldn't return until it's finished,
290 # but here we are.
291 time.sleep(1)
292 ml_job_info = self.get(name=self.name,
293 as_dict=True)
294
295 self.results['ml_job'] = ml_job_info
296 self.results['changed'] = changed
297 return self.results
298
299 def update_params(self, kwargs, param_overrides, ml_job=None):
300 params_override = []
301
302 # If ml_job is defined use those values as a base.
303 # Update can't change some of these values but we need
304 # to keep the same values as before the update.
305 if ml_job:
306 items = self.entity_to_dict(ml_job).items()
307 params_override = [{k: v} for k, v in items]
308
309 # Update values based on what param_overrides says we can update.
310 for key in list(self.module_arg_spec.keys()):
311 if kwargs[key] is not None and key in param_overrides:
312 params_override.append({key: kwargs[key]})
313 return params_override
314
315 def get(self, name, as_dict=False):
316 try:
317 # Attempt to retrieve ml_job based on name
318 ml_job_info = self.client.jobs.get(name=name)
319 if as_dict:
320 ml_job_info = self.entity_to_dict(ml_job_info)
321 except ResourceNotFoundError:
322 ml_job_info = None
323 return ml_job_info
324
325 def archive(self, name=None):
326 try:
327 self.client.jobs.archive(name=name)
328 except Exception as e: # pylint: disable=broad-exception-caught
329 self.fail("Error archive the job instance: {0}".format(str(e)))
330
331 def restore(self, name=None):
332 try:
333 self.client.jobs.restore(name=name)
334 except Exception as e: # pylint: disable=broad-exception-caught
335 self.fail("Error restore the job instance: {0}".format(str(e)))
336
337 def cancel(self, name=None):
338 try:
339 response = self.client.jobs.begin_cancel(name)
340 ml_job_object = self.get_poller_result(response)
341 return self.entity_to_dict(ml_job_object)
342 except Exception as e: # pylint: disable=broad-exception-caught
343 self.fail("Error cancelling the job instance: {0}".format(str(e)))
344
345
346 def main():
347 AzureRMMLJob()
348
349
350 if __name__ == '__main__':
351 main()