Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_ml_component.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_component
11 version_added: "3.16.0"
12 short_description: Create, Archive or Restore an Azure Machine Learning Component
13 description:
14 - Create, Archive or Restore an Azure Machine Learning Component.
15 options:
16 name:
17 description:
18 - Name of the Azure ML component.
19 type: str
20 required: true
21 resource_group:
22 description:
23 - Name of resource group.
24 required: false
25 type: str
26 ml_workspace:
27 description:
28 - Name of the Azure ML workspace.
29 required: false
30 type: str
31 ml_registry:
32 description:
33 - Name of the Azure ML registry.
34 required: false
35 type: str
36 resource_definition:
37 description:
38 - Component definition in YAML
39 type: str
40 required: false
41 version:
42 description:
43 - Data Asset version. Mutually exclusive with label.
44 type: str
45 label:
46 description:
47 - Label of the data asset. Mutually exclusive with version.
48 type: str
49 state:
50 description:
51 - State of the Component. Use C(present) to create
52 or update. C(archive) to archive, C(restore) to
53 restore.
54 default: present
55 type: str
56 choices:
57 - present
58 - archive
59 - restore
60
61 extends_documentation_fragment:
62 - azure.azcollection.azure
63
64 author:
65 - Bill Peck (@p3ck)
66 '''
67
68 EXAMPLES = '''
69 - name: Create ML Component
70 azure.azcollection.azure_rm_ml_component:
71 name: MyComponent
72 resource_group: myResourceGroup
73 ml_workspace: myMLWorkspace
74 version: 1b
75 resource_definition: |
76 $schema: https://azuremlschemas.azureedge.net/latest/commandComponent.schema.json
77 name: my_train
78 display_name: Train_upper_case
79 type: command
80 inputs:
81 training_data:
82 type: uri_folder
83 max_epocs:
84 type: integer
85 min: 0
86 max: 100
87 learning_rate:
88 type: number
89 default: 0.01
90 learning_rate_schedule:
91 type: string
92 default: time-based
93 enum:
94 - "step"
95 - "time-based"
96 outputs:
97 model_output:
98 type: uri_folder
99 code: ./targets/azure_rm_ml_component/files/train_src
100 environment: azureml://registries/azureml/environments/sklearn-1.5/labels/latest
101 command: >-
102 python train.py
103 --training_data ${{ '{{' }}inputs.training_data{{ '}}' }}
104 --max_epocs ${{ '{{' }}inputs.max_epocs{{ '}}' }}
105 --learning_rate ${{ '{{' }}inputs.learning_rate{{ '}}' }}
106 --learning_rate_schedule ${{ '{{' }}inputs.learning_rate_schedule{{ '}}' }}
107 --model_output ${{ '{{' }}outputs.model_output{{ '}}' }}
108 '''
109
110 RETURN = '''
111 changed:
112 description:
113 - Whether the resource is changed.
114 returned: always
115 type: bool
116 sample: false
117 ml_component:
118 description:
119 - Component that was just created or updated.
120 returned: always
121 type: dict
122 sample: {
123 "$schema": "https://azuremlschemas.azureedge.net/latest/commandComponent.schema.json",
124 "code": "azureml:/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-component/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/codes/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/versions/1",
125 "command": "python train.py --training_data ${{inputs.training_data}} --max_epocs ${{inputs.max_epocs}} --learning_rate ${{inputs.learning_rate}} --learning_rate_schedule ${{inputs.learning_rate_schedule}} --model_output ${{outputs.model_output}}",
126 "creation_context": {
127 "created_at": "2026-03-18T14:02:54.635544+00:00",
128 "created_by": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
129 "created_by_type": "Application",
130 "last_modified_at": "2026-03-18T14:02:54.773038+00:00",
131 "last_modified_by": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
132 "last_modified_by_type": "Application"
133 },
134 "display_name": "Train_upper_case",
135 "environment": "azureml://registries/azureml/environments/sklearn-1.5/versions/41",
136 "id": "azureml:/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxxx-ml-component/providers/Microsoft.MachineLearningServices/workspaces/workspace-xxxxxxxxxx/components/componentxxxxxxxxxx/labels/default",
137 "inputs": {
138 "learning_rate": {
139 "default": "0.01",
140 "optional": false,
141 "type": "number"
142 },
143 "learning_rate_schedule": {
144 "default": "time-based",
145 "enum": [
146 "step",
147 "time-based"
148 ],
149 "optional": false,
150 "type": "string"
151 },
152 "max_epocs": {
153 "max": "100",
154 "min": "0",
155 "optional": false,
156 "type": "integer"
157 },
158 "training_data": {
159 "optional": false,
160 "type": "uri_folder"
161 }
162 },
163 "is_deterministic": true,
164 "name": "componentxxxxxxxxxx",
165 "outputs": {
166 "model_output": {
167 "type": "uri_folder"
168 }
169 },
170 "resources": {
171 "instance_count": 1
172 },
173 "type": "command",
174 "version": "2"
175 }
176 ''' # NOQA
177
178
179 try:
180 import io
181 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ml import MLClientCommon
182 from azure.core.exceptions import ResourceNotFoundError
183 from azure.ai.ml.entities._load_functions import load_component
184 except ImportError:
185 # This is handled in azure_rm_common
186 pass
187
188
189 class AzureRMMLComponent(MLClientCommon):
190
191 UPDATE_OVERRIDES = []
192
193 PARAM_OVERRIDES = UPDATE_OVERRIDES + ['name', 'version']
194
195 def __init__(self):
196
197 self.module_arg_spec = dict(
198 name=dict(
199 type='str',
200 required=True,
201 ),
202 resource_definition=dict(
203 type='str',
204 required=False,
205 ),
206 resource_group=dict(
207 type='str',
208 required=False,
209 ),
210 ml_workspace=dict(
211 type='str',
212 required=False,
213 ),
214 ml_registry=dict(
215 type='str',
216 required=False,
217 ),
218 version=dict(
219 type='str',
220 required=False,
221 ),
222 label=dict(
223 type='str',
224 required=False,
225 ),
226 state=dict(
227 type='str',
228 default='present',
229 choices=['present', 'archive', 'restore'],
230 ),
231 )
232
233 self._client = None
234 self.ml_registry = None
235 self.state = None
236
237 self.results = dict(
238 changed=False,
239 compare=[],
240 ml_component={}
241 )
242
243 required_if = [
244 ('state', 'present', ['resource_definition'])
245 ]
246 required_one_of = [('ml_workspace', 'ml_registry')]
247 mutually_exclusive = [('version', 'label'),
248 ('ml_workspace', 'ml_registry')]
249 required_together = [('ml_workspace', 'resource_group')]
250
251 super(AzureRMMLComponent, self).__init__(self.module_arg_spec,
252 supports_check_mode=True,
253 supports_tags=False,
254 required_one_of=required_one_of,
255 mutually_exclusive=mutually_exclusive,
256 required_together=required_together,
257 required_if=required_if,
258 )
259
260 def exec_module(self, **kwargs):
261
262 for key in list(self.module_arg_spec.keys()):
263 setattr(self, key, kwargs[key])
264
265 if self.resource_definition:
266 resource_definition = io.StringIO(self.resource_definition)
267 else:
268 resource_definition = None
269
270 changed = False
271 ml_component_info = self.get(name=self.name,
272 version=self.version,
273 label=self.label)
274
275 if self.state == 'present':
276 if ml_component_info:
277 # Update
278 # No Updates are supported at this time.
279 changed = False
280 ml_component_info = self.entity_to_dict(ml_component_info)
281 else:
282 # Create
283 params_override = self.update_params(kwargs, self.PARAM_OVERRIDES)
284
285 # Generate ml_component based on ansible args passed in.
286 ml_component = load_component(source=resource_definition,
287 params_override=params_override)
288 changed = True
289 if not self.check_mode:
290 response = self.client.create_or_update(ml_component)
291 ml_component_info = self.entity_to_dict(response)
292 elif self.state == 'archive':
293 # Archive
294 list_view_type = self.get_list_view_type('active')
295 results = self.client.components.list(list_view_type=list_view_type)
296 ml_components = [x.name for x in results]
297
298 if self.name in ml_components:
299 changed = True
300 if not self.check_mode:
301 self.archive(name=self.name)
302 ml_component_info = self.get(name=self.name,
303 version=self.version,
304 label=self.label,
305 as_dict=True)
306 elif self.state == 'restore':
307 # Restore
308 list_view_type = self.get_list_view_type('archived')
309 results = self.client.components.list(list_view_type=list_view_type)
310 ml_components = [x.name for x in results]
311
312 if self.name in ml_components:
313 changed = True
314 if not self.check_mode:
315 self.restore(name=self.name)
316 ml_component_info = self.get(name=self.name,
317 version=self.version,
318 label=self.label,
319 as_dict=True)
320
321 self.results['ml_component'] = ml_component_info
322 self.results['changed'] = changed
323 return self.results
324
325 def update_params(self, kwargs, param_overrides, ml_component=None):
326 params_override = []
327
328 # If ml_ccomponent is defined use those values as a base.
329 # Update can't change some of these values but we need
330 # to keep the same values as before the update.
331 if ml_component:
332 items = self.entity_to_dict(ml_component).items()
333 params_override = [{k: v} for k, v in items]
334
335 # Update values based on what param_overrides says we can update.
336 for key in list(self.module_arg_spec.keys()):
337 if kwargs[key] is not None and key in param_overrides:
338 params_override.append({key: kwargs[key]})
339 return params_override
340
341 def get(self, name, version=None, label=None, as_dict=False):
342 try:
343 # Attempt to retrieve ml_component based on name
344 ml_component_info = self.client.components.get(name=name,
345 version=version,
346 label=label)
347 if as_dict:
348 ml_component_info = self.entity_to_dict(ml_component_info)
349 except ResourceNotFoundError:
350 ml_component_info = None
351 return ml_component_info
352
353 def archive(self, name=None):
354 try:
355 self.client.components.archive(name=name)
356 except Exception as e: # pylint: disable=broad-exception-caught
357 self.fail("Error archive the component instance: {0}".format(str(e)))
358
359 def restore(self, name=None):
360 try:
361 self.client.components.restore(name=name)
362 except Exception as e: # pylint: disable=broad-exception-caught
363 self.fail("Error restore the component instance: {0}".format(str(e)))
364
365
366 def main():
367 AzureRMMLComponent()
368
369
370 if __name__ == '__main__':
371 main()