Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_restit.py

raw
1 #!/usr/bin/python
2 '''
3 # (c) 2020-2026, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 '''
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 ANSIBLE_METADATA = {'metadata_version': '1.1',
11 'status': ['preview'],
12 'supported_by': 'certified'}
13
14 DOCUMENTATION = '''
15 author: NetApp Ansible Team (@carchi8py) <[email protected]>
16 description:
17 - Call a REST API on ONTAP.
18 - Cluster REST API are run using a cluster admin account.
19 - Vserver REST API can be run using a vsadmin account or using vserver tunneling (cluster admin with I(vserver_) options).
20 - In case of success, a json dictionary is returned as C(response).
21 - In case of a REST API error, C(status_code), C(error_code), C(error_message) are set to help with diagnosing the issue,
22 - and the call is reported as an error ('failed').
23 - Other errors (eg connection issues) are reported as Ansible error.
24 extends_documentation_fragment:
25 - netapp.ontap.netapp.na_ontap_rest
26 module: na_ontap_restit
27 short_description: NetApp ONTAP Run any REST API on ONTAP
28 version_added: "20.4.0"
29 options:
30 api:
31 description:
32 - The REST API to call (eg I(cluster/software), I(svms/svm)).
33 required: true
34 type: str
35 method:
36 description:
37 - The REST method to use.
38 default: GET
39 type: str
40 query:
41 description:
42 - A list of dictionaries for the query parameters
43 type: dict
44 body:
45 description:
46 - A dictionary for the info parameter
47 type: dict
48 aliases: ['info']
49 vserver_name:
50 description:
51 - if provided, forces vserver tunneling. username identifies a cluster admin account.
52 type: str
53 vserver_uuid:
54 description:
55 - if provided, forces vserver tunneling. username identifies a cluster admin account.
56 type: str
57 hal_linking:
58 description:
59 - if true, HAL-encoded links are returned in the response.
60 default: false
61 type: bool
62 wait_for_completion:
63 description:
64 - when true, POST/PATCH/DELETE can be handled synchronously and asynchronously.
65 - if the response indicates that a job is in progress, the job status is checked periodically until is completes.
66 - when false, the call returns immediately.
67 type: bool
68 default: false
69 version_added: 21.14.0
70 files:
71 description:
72 - A dictionary for the parameters when using multipart/form-data.
73 - This is very infrequently needed, but required to write a file (see examples)
74 - When present, requests will automatically set the Content-Type header to multipart/form-data.
75 type: dict
76 version_added: 21.24.0
77 accept_header:
78 description:
79 - Value for the Accept request HTTP header.
80 - This is very infrequently needed, but required to read a file (see examples).
81 - For most cases, omit this field. Set it to "multipart/form-data" when expecting such a format.
82 - By default the module is using "application/json" or "application/hal+json" when hal_linking is true.
83 type: str
84 version_added: 21.24.0
85 lambda_config:
86 description:
87 - Configuration parameters for AWS Lambda proxy functionality.
88 - These option and suboptions are only supported with REST.
89 type: dict
90 version_added: 23.5.0
91 suboptions:
92 function_name:
93 description:
94 - The name of the AWS Lambda function to invoke.
95 type: str
96 required: true
97 aws_region:
98 description:
99 - The name of the AWS region.
100 type: str
101 required: true
102 aws_profile:
103 description:
104 - The name of the AWS profile to use for authentication.
105 type: str
106
107 notes:
108 - Supports AWS Lambda proxy functionality. See README for example usage.
109 '''
110
111 EXAMPLES = """
112 -
113 name: Ontap REST API
114 hosts: localhost
115 gather_facts: false
116 vars:
117 login: &login
118 hostname: "{{ admin_ip }}"
119 username: "{{ admin_username }}"
120 password: "{{ admin_password }}"
121 https: true
122 validate_certs: false
123 svm_login: &svm_login
124 hostname: "{{ svm_admin_ip }}"
125 username: "{{ svm_admin_username }}"
126 password: "{{ svm_admin_password }}"
127 https: true
128 validate_certs: false
129
130 tasks:
131 - name: Run ontap REST API command as cluster admin
132 netapp.ontap.na_ontap_restit:
133 <<: *login
134 api: cluster/software
135 register: result
136 - name: Assertions
137 ansible.builtin.assert:
138 that: result.status_code==200
139 quiet: true
140
141 - name: Run ontap REST API command as cluster admin
142 netapp.ontap.na_ontap_restit:
143 <<: *login
144 api: cluster/software
145 query:
146 fields: version
147 register: result
148 - name: Assertions
149 ansible.builtin.assert:
150 that: result.status_code==200
151 quiet: true
152
153 - name: Run ontap REST API command as cluster admin
154 netapp.ontap.na_ontap_restit:
155 <<: *login
156 api: svm/svms
157 register: result
158 - name: Assertions
159 ansible.builtin.assert:
160 that: result.status_code==200
161 quiet: true
162
163 - name: Run ontap REST API command as cluster admin
164 netapp.ontap.na_ontap_restit:
165 <<: *login
166 api: svm/svms
167 query:
168 fields: aggregates,cifs,nfs,uuid
169 query_fields: name
170 query: trident_svm
171 hal_linking: true
172 register: result
173
174 - name: Run ontap REST API command as vsadmin
175 netapp.ontap.na_ontap_restit:
176 <<: *svm_login
177 api: svm/svms
178 register: result
179 - name: Assertions
180 ansible.builtin.assert:
181 that: result.status_code==200
182 quiet: true
183
184 - name: Run ontap REST API command as vserver tunneling
185 netapp.ontap.na_ontap_restit:
186 <<: *login
187 api: storage/volumes
188 vserver_name: ansibleSVM
189 register: result
190 - name: Assertions
191 ansible.builtin.assert:
192 that: result.status_code==200
193 quiet: true
194 - name: Store UUID
195 ansible.builtin.set_fact:
196 uuid: "{{ result.response.records | json_query(get_uuid) }}"
197 vars:
198 get_uuid: "[? name=='deleteme_ln1'].uuid"
199
200 - name: Run ontap REST API command as DELETE method with vserver tunneling
201 netapp.ontap.na_ontap_restit:
202 <<: *login
203 api: "storage/volumes/{{ uuid[0] }}"
204 method: DELETE
205 vserver_name: ansibleSVM
206 query:
207 return_timeout: 60
208 register: result
209 when: uuid | length == 1
210 - name: Assertions
211 ansible.builtin.assert:
212 that: result.skipped | default(false) or result.status_code | default(404) == 200
213 quiet: true
214
215 - name: Run ontap REST API command as POST method with vserver tunneling
216 netapp.ontap.na_ontap_restit:
217 <<: *login
218 api: storage/volumes
219 method: POST
220 vserver_name: ansibleSVM
221 query:
222 return_records: "true"
223 return_timeout: 60
224 body:
225 name: deleteme_ln1
226 aggregates:
227 - name: aggr1
228 register: result
229 - name: Assertions
230 ansible.builtin.assert:
231 that: result.status_code==201
232 quiet: true
233
234 - name: Run ontap REST API command as DELETE method with vserver tunneling
235 # delete test volume if present
236 netapp.ontap.na_ontap_restit:
237 <<: *login
238 api: "storage/volumes/{{ result.response.records[0].uuid }}"
239 method: DELETE
240 vserver_name: ansibleSVM
241 query:
242 return_timeout: 60
243 register: result
244 - name: Assertions
245 ansible.builtin.assert:
246 that: result.status_code==200
247 quiet: true
248
249 - name: Create a file
250 # assuming credentials are set using module_defaults
251 netapp.ontap.na_ontap_restit:
252 api: storage/volumes/f3c003cb-2974-11ed-b2f8-005056b38dae/files/laurent123.txt
253 method: post
254 files:
255 data: 'some data'
256
257 - name: Read a file
258 # assuming credentials are set using module_defaults
259 netapp.ontap.na_ontap_restit:
260 api: storage/volumes/f3c003cb-2974-11ed-b2f8-005056b38dae/files/laurent123.txt
261 method: get
262 accept_header: "multipart/form-data"
263 query:
264 length: 100
265
266 # error cases
267 - name: Run ontap REST API command
268 netapp.ontap.na_ontap_restit:
269 <<: *login
270 api: unknown/endpoint
271 register: result
272 ignore_errors: true
273 - name: Assertions
274 ansible.builtin.assert:
275 that: result.status_code==404
276 quiet: true
277 """
278
279 RETURN = """
280 response:
281 description:
282 - If successful, a json dictionary returned by the REST API.
283 - If the REST API was executed but failed, an empty dictionary.
284 - Not present if the REST API call cannot be performed.
285 returned: On success
286 type: dict
287 status_code:
288 description:
289 - The http status code.
290 - When wait_for_completion is True, this is forced to 0.
291 returned: Always
292 type: str
293 error_code:
294 description:
295 - If the REST API was executed but failed, the error code set by the REST API.
296 - Not present if successful, or if the REST API call cannot be performed.
297 returned: On error
298 type: str
299 error_message:
300 description:
301 - If the REST API was executed but failed, the error message set by the REST API.
302 - Not present if successful, or if the REST API call cannot be performed.
303 returned: On error
304 type: str
305 """
306
307 from ansible.module_utils.basic import AnsibleModule
308 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
309 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
310 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
311
312
313 class NetAppONTAPRestAPI(object):
314 ''' calls a REST API command '''
315
316 def __init__(self):
317 self.argument_spec = netapp_utils.na_ontap_rest_only_spec()
318 self.argument_spec.update(dict(
319 api=dict(required=True, type='str'),
320 method=dict(required=False, type='str', default='GET'),
321 query=dict(required=False, type='dict'),
322 body=dict(required=False, type='dict', aliases=['info']),
323 vserver_name=dict(required=False, type='str'),
324 vserver_uuid=dict(required=False, type='str'),
325 hal_linking=dict(required=False, type='bool', default=False),
326 wait_for_completion=dict(required=False, type='bool', default=False),
327 # to support very infrequent form-data format
328 files=dict(required=False, type='dict'),
329 accept_header=dict(required=False, type='str'),
330 ))
331 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
332
333 self.module = AnsibleModule(
334 argument_spec=self.argument_spec,
335 required_if=[
336 ('use_lambda', True, ['lambda_config']),
337 ],
338 supports_check_mode=True,
339 )
340 parameters = self.module.params
341 # set up state variables
342 self.api = parameters['api']
343 self.method = parameters['method']
344 self.query = parameters['query']
345 self.body = parameters['body']
346 self.vserver_name = parameters['vserver_name']
347 self.vserver_uuid = parameters['vserver_uuid']
348 self.hal_linking = parameters['hal_linking']
349 self.wait_for_completion = parameters['wait_for_completion']
350 self.files = parameters['files']
351 self.accept_header = parameters['accept_header']
352
353 self.rest_api = OntapRestAPI(self.module)
354
355 if self.accept_header is None:
356 self.accept_header = 'application/hal+json' if self.hal_linking else 'application/json'
357
358 def build_headers(self):
359 return self.rest_api.build_headers(accept=self.accept_header, vserver_name=self.vserver_name, vserver_uuid=self.vserver_uuid)
360
361 def fail_on_error(self, status, response, error):
362 if error:
363 if isinstance(error, dict):
364 error_message = error.pop('message', None)
365 error_code = error.pop('code', None)
366 if not error:
367 # we exhausted the dictionary
368 error = 'check error_message and error_code for details.'
369 else:
370 error_message = error
371 error_code = None
372
373 msg = "Error when calling '%s': %s" % (self.api, str(error))
374 self.module.fail_json(msg=msg, status_code=status, response=response, error_message=error_message, error_code=error_code)
375
376 def run_api(self):
377 ''' calls the REST API '''
378 # TODO, log usage
379 status, response, error = self.rest_api.send_request(self.method, self.api, self.query, self.body, self.build_headers(), self.files)
380 self.fail_on_error(status, response, error)
381
382 return status, response
383
384 def run_api_async(self):
385 ''' calls the REST API '''
386 # TODO, log usage
387
388 args = [self.rest_api, self.api]
389 kwargs = {}
390 if self.method.upper() == 'POST':
391 method = rest_generic.post_async
392 kwargs['body'] = self.body
393 kwargs['files'] = self.files
394 elif self.method.upper() == 'PATCH':
395 method = rest_generic.patch_async
396 args.append(None) # uuid should be provided in the API
397 kwargs['body'] = self.body
398 kwargs['files'] = self.files
399 elif self.method.upper() == 'DELETE':
400 method = rest_generic.delete_async
401 args.append(None) # uuid should be provided in the API
402 else:
403 self.module.warn('wait_for_completion ignored for %s method.' % self.method)
404 return self.run_api()
405
406 kwargs.update({
407 'raw_error': True,
408 'headers': self.build_headers()
409 })
410 if self.query:
411 kwargs['query'] = self.query
412 response, error = method(*args, **kwargs)
413 self.fail_on_error(0, response, error)
414
415 return 0, response
416
417 def apply(self):
418 ''' calls the api and returns json output '''
419 changed_status = False if self.method.upper() == 'GET' else True
420
421 if self.module.check_mode:
422 status_code, response = None, {'check_mode': 'would run %s %s' % (self.method, self.api)}
423 elif self.wait_for_completion:
424 status_code, response = self.run_api_async()
425 else:
426 status_code, response = self.run_api()
427 self.module.exit_json(changed=changed_status, status_code=status_code, response=response)
428
429
430 def main():
431 """
432 Execute action from playbook
433 """
434 restapi = NetAppONTAPRestAPI()
435 restapi.apply()
436
437
438 if __name__ == '__main__':
439 main()