Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2019-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 '''
7 na_ontap_rest_cli
8 '''
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14 author: NetApp Ansible Team (@carchi8py) <[email protected]>
15 description:
16 - Run CLI commands on ONTAP through REST api/private/cli/.
17 - This module can run as admin or vsdamin and requires HTTP application to be enabled.
18 - Access permissions can be customized using ONTAP rest-role.
19 extends_documentation_fragment:
20 - netapp.ontap.netapp.na_ontap_rest
21 module: na_ontap_rest_cli
22 short_description: NetApp ONTAP run any CLI command using REST api/private/cli/
23 version_added: 2.9.0
24 options:
25 command:
26 description:
27 - A CLI command.
28 required: true
29 type: str
30 verb:
31 description:
32 - Define which action to perform with the provided command.
33 - Values are mapped to show, create, modify, delete.
34 - OPTIONS is useful to know which verbs are supported by the REST API
35 choices: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS']
36 required: true
37 type: str
38 params:
39 description:
40 - a dictionary of parameters to pass into the api call
41 type: dict
42 body:
43 description:
44 - a dictionary for info specification
45 type: dict
46 '''
47
48 EXAMPLES = """
49 - name: Run ONTAP REST CLI command
50 netapp.ontap.na_ontap_rest_cli:
51 hostname: "{{ netapp_hostname }}"
52 username: "{{ netapp_username }}"
53 password: "{{ netapp_password }}"
54 command: version
55 verb: GET
56
57 # The fields key allows returning a subset of parameters for a given object
58 - name: Run volume show command with a filter to only return volumes matching the provided vserver and policy values.
59 netapp.ontap.na_ontap_rest_cli:
60 hostname: "{{ netapp_hostname }}"
61 username: "{{ netapp_username }}"
62 password: "{{ netapp_password }}"
63 command: volume
64 verb: GET
65 params:
66 vserver: vs0
67 policy: default
68 fields: vserver,volume,policy
69 register: vs0_volumes
70
71 - name: Run security login motd modify command
72 netapp.ontap.na_ontap_rest_cli:
73 hostname: "{{ netapp_hostname }}"
74 username: "{{ netapp_username }}"
75 password: "{{ netapp_password }}"
76 command: security/login/motd
77 verb: PATCH
78 params:
79 vserver: ansibleSVM
80 body:
81 message: test
82
83 - name: Set option
84 netapp.ontap.na_ontap_rest_cli:
85 hostname: "{{ netapp_hostname }}"
86 username: "{{ netapp_username }}"
87 password: "{{ netapp_password }}"
88 command: options
89 verb: PATCH
90 params:
91 option_name: lldp.enable
92 body:
93 option_value: "on"
94
95 - name: Run security certificate delete command
96 netapp.ontap.na_ontap_rest_cli:
97 hostname: "{{ netapp_hostname }}"
98 username: "{{ netapp_username }}"
99 password: "{{ netapp_password }}"
100 command: security/certificate
101 verb: DELETE
102 body:
103 vserver: vs1
104 common-name: cluster01
105 ca: cluster01
106 type: server
107 serial: 17EBE9D26GGE91B9
108
109 - name: Run volume create command
110 netapp.ontap.na_ontap_rest_cli:
111 hostname: "{{ netapp_hostname }}"
112 username: "{{ netapp_username }}"
113 password: "{{ netapp_password }}"
114 command: volume
115 verb: POST
116 body:
117 vserver: vs1
118 volume: my_test_volume
119 size: 10g
120 aggregate: aggr1_node1
121 policy: default
122 type: RW
123 """
124
125 RETURN = """
126 """
127
128 import traceback
129 from ansible.module_utils.basic import AnsibleModule
130 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
131 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
132
133
134 class NetAppONTAPCommandREST():
135 ''' calls a CLI command '''
136
137 def __init__(self):
138 self.use_rest = False
139 self.argument_spec = netapp_utils.na_ontap_rest_only_spec()
140 self.argument_spec.update(dict(
141 command=dict(required=True, type='str'),
142 verb=dict(required=True, type='str', choices=['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS']),
143 params=dict(required=False, type='dict'),
144 body=dict(required=False, type='dict')
145 ))
146 self.module = AnsibleModule(
147 argument_spec=self.argument_spec,
148 supports_check_mode=True
149 )
150 self.rest_api = OntapRestAPI(self.module)
151 parameters = self.module.params
152 # set up state variables
153 self.command = parameters['command']
154 self.verb = parameters['verb']
155 self.params = parameters['params']
156 self.body = parameters['body']
157
158 if self.rest_api.is_rest():
159 self.use_rest = True
160 else:
161 msg = 'failed to connect to REST over %s: %s' % (parameters['hostname'], self.rest_api.errors)
162 msg += '. Use na_ontap_command for non-rest CLI.'
163 self.module.fail_json(msg=msg)
164
165 def run_command(self):
166 api = "private/cli/" + self.command
167
168 if self.verb == 'POST':
169 message, error = self.rest_api.post(api, self.body, self.params)
170 elif self.verb == 'GET':
171 message, error = self.rest_api.get(api, self.params)
172 if message is not None and isinstance(message, dict) and '_links' in message:
173 self.get_all_records(message)
174 elif self.verb == 'PATCH':
175 message, error = self.rest_api.patch(api, self.body, self.params)
176 elif self.verb == 'DELETE':
177 message, error = self.rest_api.delete(api, self.body, self.params)
178 elif self.verb == 'OPTIONS':
179 message, error = self.rest_api.options(api, self.params)
180 else:
181 self.module.fail_json(msg='Error: unexpected verb %s' % self.verb,
182 exception=traceback.format_exc())
183
184 if error:
185 self.module.fail_json(msg='Error: %s' % error)
186 return message
187
188 def get_next_records(self, api):
189 """
190 Gather next set of ONTAP information for the specified api
191 Input for REST APIs call : (api, data)
192 return gather_info
193 """
194
195 gather_info, error = self.rest_api.get(api)
196
197 if error:
198 self.module.fail_json(msg=error)
199
200 return gather_info
201
202 def get_all_records(self, message):
203 """ Iteratively get all records """
204
205 # If the response contains a next link, we need to gather all records
206 while message.get('_links', {}).get('next'):
207 next_api = message['_links']['next']['href']
208 gathered_info = self.get_next_records(next_api.replace('/api', ''))
209
210 # Update the message with the gathered info
211 message['_links'] = gathered_info.get('_links', {})
212 message['records'].extend(gathered_info['records'])
213
214 # metrocluster doesn't have a records field, so we need to skip this
215 if message.get('records') is not None:
216 # Getting total number of records
217 message['num_records'] = len(message['records'])
218
219 return message
220
221 def apply(self):
222 ''' calls the command and returns raw output '''
223 changed = False if self.verb in ['GET', 'OPTIONS'] else True
224 if self.module.check_mode and self.verb in ['POST', 'PATCH', 'DELETE']:
225 output = "Would run command: '%s'" % str(self.command)
226 else:
227 output = self.run_command()
228 self.module.exit_json(changed=changed, msg=output)
229
230
231 def main():
232 """
233 Execute action from playbook
234 """
235 command = NetAppONTAPCommandREST()
236 command.apply()
237
238
239 if __name__ == '__main__':
240 main()