Debian Codegraph @

ansible_collections/community/routeros/plugins/modules/api.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2020, Nikolay Dachev <[email protected]>
5 # GNU General Public License v3.0+ https://www.gnu.org/licenses/gpl-3.0.txt
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import (absolute_import, division, print_function)
9 __metaclass__ = type
10
11 DOCUMENTATION = r"""
12 module: api
13 author: "Nikolay Dachev (@NikolayDachev)"
14 short_description: Ansible module for RouterOS API
15 description:
16 - Ansible module for RouterOS API with the Python C(librouteros) library.
17 - This module can add, remove, update, query, and execute arbitrary command in RouterOS through the API.
18 notes:
19 - O(add), O(remove), O(update), O(cmd), and O(query) are mutually exclusive.
20 - Use the M(community.routeros.api_modify) and M(community.routeros.api_find_and_modify) modules for more specific modifications,
21 and the M(community.routeros.api_info) module for a more controlled way of returning all entries for a path.
22 extends_documentation_fragment:
23 - community.routeros.api
24 - community.routeros.attributes
25 - community.routeros.attributes.actiongroup_api
26 attributes:
27 check_mode:
28 support: none
29 diff_mode:
30 support: none
31 platform:
32 support: full
33 platforms: RouterOS
34 action_group:
35 version_added: 2.1.0
36 idempotent:
37 support: N/A
38 details:
39 - Whether the executed command is idempotent depends on the operation performed.
40 options:
41 path:
42 description:
43 - Main path for all other arguments.
44 - If other arguments are not set, the module will return all items in selected path.
45 - Example V(ip address). Equivalent of RouterOS CLI C(/ip address print).
46 required: true
47 type: str
48 add:
49 description:
50 - Will add selected arguments in selected path to RouterOS config.
51 - Example V(address=1.1.1.1/32 interface=ether1).
52 - Equivalent in RouterOS CLI C(/ip address add address=1.1.1.1/32 interface=ether1).
53 type: str
54 remove:
55 description:
56 - Remove config/value from RouterOS by '.id'.
57 - Example V(*03) will remove config/value with C(id=*03) in selected path.
58 - Equivalent in RouterOS CLI C(/ip address remove numbers=1).
59 - Note C(number) in RouterOS CLI is different from C(.id).
60 type: str
61 update:
62 description:
63 - Update config/value in RouterOS by '.id' in selected path.
64 - Example V(.id=*03 address=1.1.1.3/32) and path V(ip address) will replace the existing IP address with C(.id=*03).
65 - Equivalent in RouterOS CLI C(/ip address set address=1.1.1.3/32 numbers=1).
66 - Note C(number) in RouterOS CLI is different from C(.id).
67 type: str
68 query:
69 description:
70 - Query given path for selected query attributes from RouterOS API.
71 - WHERE is key word which extend query. WHERE format is key operator value - with spaces.
72 - WHERE valid operators are V(==) or V(eq), V(!=) or V(not), V(>) or V(more), V(<) or V(less).
73 - Example path V(ip address) and query V(.id address) will return only C(.id) and C(address) for all items in V(ip address)
74 path.
75 - Example path V(ip address) and query V(.id address WHERE address == 1.1.1.3/32). will return only C(.id) and C(address)
76 for items in V(ip address) path, where address is eq to 1.1.1.3/32.
77 - Example path V(interface) and query V(mtu name WHERE mut > 1400) will return only interfaces C(mtu,name) where mtu
78 is bigger than 1400.
79 - Equivalent in RouterOS CLI C(/interface print where mtu > 1400).
80 type: str
81 extended_query:
82 description:
83 - Extended query given path for selected query attributes from RouterOS API.
84 - Extended query allow conjunctive input. If there is no matching entry, an empty list will be returned.
85 type: dict
86 suboptions:
87 attributes:
88 description:
89 - The list of attributes to return.
90 - Every attribute used in a O(extended_query.where[]) clause need to be listed here.
91 type: list
92 elements: str
93 required: true
94 where:
95 description:
96 - Allows to restrict the objects returned.
97 - The conditions here must all match. An O(extended_query.where[].or) condition needs at least one of its conditions
98 to match.
99 type: list
100 elements: dict
101 suboptions:
102 attribute:
103 description:
104 - The attribute to match. Must be part of O(extended_query.attributes).
105 - Either O(extended_query.where[].or) or all of O(extended_query.where[].attribute), O(extended_query.where[].is),
106 and O(extended_query.where[].value) have to be specified.
107 type: str
108 is:
109 description:
110 - The operator to use for matching.
111 - For equality use V(==) or V(eq). For less use V(<) or V(less). For more use V(>) or V(more).
112 - Use V(in) to check whether the value is part of a list. In that case, O(extended_query.where[].value) must
113 be a list.
114 - Either O(extended_query.where[].or) or all of O(extended_query.where[].attribute), O(extended_query.where[].is),
115 and O(extended_query.where[].value) have to be specified.
116 type: str
117 choices: ["==", "!=", ">", "<", "in", "eq", "not", "more", "less"]
118 value:
119 description:
120 - The value to compare to. Must be a list for O(extended_query.where[].is=in).
121 - Either O(extended_query.where[].or) or all of O(extended_query.where[].attribute), O(extended_query.where[].is),
122 and O(extended_query.where[].value) have to be specified.
123 type: raw
124 or:
125 description:
126 - A list of conditions so that at least one of them has to match.
127 - Either O(extended_query.where[].or) or all of O(extended_query.where[].attribute), O(extended_query.where[].is),
128 and O(extended_query.where[].value) have to be specified.
129 type: list
130 elements: dict
131 suboptions:
132 attribute:
133 description:
134 - The attribute to match. Must be part of O(extended_query.attributes).
135 type: str
136 required: true
137 is:
138 description:
139 - The operator to use for matching.
140 - For equality use V(==) or V(eq). For less use V(<) or V(less). For more use V(>) or V(more).
141 - Use V(in) to check whether the value is part of a list. In that case, O(extended_query.where[].or[].value)
142 must be a list.
143 type: str
144 choices: ["==", "!=", ">", "<", "in", "eq", "not", "more", "less"]
145 required: true
146 value:
147 description:
148 - The value to compare to. Must be a list for O(extended_query.where[].or[].is=in).
149 type: raw
150 required: true
151 cmd:
152 description:
153 - Execute any/arbitrary command in selected path, after the command we can add C(.id).
154 - Example path V(system script) and cmd V(run .id=*03) is equivalent in RouterOS CLI C(/system script run number=0).
155 - Example path V(ip address) and cmd V(print) is equivalent in RouterOS CLI C(/ip address print).
156 type: str
157 seealso:
158 - ref: ansible_collections.community.routeros.docsite.quoting
159 description: How to quote and unquote commands and arguments.
160 - module: community.routeros.api_facts
161 - module: community.routeros.api_find_and_modify
162 - module: community.routeros.api_info
163 - module: community.routeros.api_modify
164 """
165
166 EXAMPLES = r"""
167 ---
168 - name: Get example - ip address print
169 community.routeros.api:
170 hostname: "{{ hostname }}"
171 password: "{{ password }}"
172 username: "{{ username }}"
173 path: "ip address"
174 register: ipaddrd_printout
175
176 - name: Dump "Get example" output
177 ansible.builtin.debug:
178 msg: '{{ ipaddrd_printout }}'
179
180 - name: Add example - ip address
181 community.routeros.api:
182 hostname: "{{ hostname }}"
183 password: "{{ password }}"
184 username: "{{ username }}"
185 path: "ip address"
186 add: "address=192.168.255.10/24 interface=ether2"
187
188 - name: Query example - ".id, address" in "ip address WHERE address == 192.168.255.10/24"
189 community.routeros.api:
190 hostname: "{{ hostname }}"
191 password: "{{ password }}"
192 username: "{{ username }}"
193 path: "ip address"
194 query: ".id address WHERE address == {{ ip2 }}"
195 register: queryout
196
197 - name: Dump "Query example" output
198 ansible.builtin.debug:
199 msg: '{{ queryout }}'
200
201 - name: Extended query example - ".id,address,network" where address is not 192.168.255.10/24 or is 10.20.36.20/24
202 community.routeros.api:
203 hostname: "{{ hostname }}"
204 password: "{{ password }}"
205 username: "{{ username }}"
206 path: "ip address"
207 extended_query:
208 attributes:
209 - network
210 - address
211 - .id
212 where:
213 - attribute: "network"
214 is: "=="
215 value: "192.168.255.0"
216 - or:
217 - attribute: "address"
218 is: "!="
219 value: "192.168.255.10/24"
220 - attribute: "address"
221 is: "eq"
222 value: "10.20.36.20/24"
223 - attribute: "network"
224 is: "in"
225 value:
226 - "10.20.36.0"
227 - "192.168.255.0"
228 register: extended_queryout
229
230 - name: Dump "Extended query example" output
231 ansible.builtin.debug:
232 msg: '{{ extended_queryout }}'
233
234 - name: Update example - ether2 ip address with ".id = *14"
235 community.routeros.api:
236 hostname: "{{ hostname }}"
237 password: "{{ password }}"
238 username: "{{ username }}"
239 path: "ip address"
240 update: >-
241 .id=*14
242 address=192.168.255.20/24
243 comment={{ 'Update 192.168.255.10/24 to 192.168.255.20/24 on ether2' | community.routeros.quote_argument_value }}
244
245 - name: Remove example - ether2 ip 192.168.255.20/24 with ".id = *14"
246 community.routeros.api:
247 hostname: "{{ hostname }}"
248 password: "{{ password }}"
249 username: "{{ username }}"
250 path: "ip address"
251 remove: "*14"
252
253 - name: Arbitrary command example "/system identity print"
254 community.routeros.api:
255 hostname: "{{ hostname }}"
256 password: "{{ password }}"
257 username: "{{ username }}"
258 path: "system identity"
259 cmd: "print"
260 register: arbitraryout
261
262 - name: Dump "Arbitrary command example" output
263 ansible.builtin.debug:
264 msg: '{{ arbitraryout }}'
265 """
266
267 RETURN = r"""
268 message:
269 description: All outputs are in list with dictionary elements returned from RouterOS API.
270 sample:
271 - address: 1.2.3.4
272 - address: 2.3.4.5
273 type: list
274 returned: always
275 """
276
277 from ansible.module_utils.basic import AnsibleModule
278 from ansible.module_utils.common.text.converters import to_native
279
280 from ansible_collections.community.routeros.plugins.module_utils.quoting import (
281 ParseError,
282 convert_list_to_dictionary,
283 parse_argument_value,
284 split_routeros_command,
285 )
286
287 from ansible_collections.community.routeros.plugins.module_utils.api import (
288 api_argument_spec,
289 check_has_library,
290 create_api,
291 )
292
293 import re
294
295 try:
296 from librouteros.exceptions import LibRouterosError
297 from librouteros.query import Key, Or
298 except Exception:
299 # Handled in api module_utils
300 pass
301
302
303 class ROS_api_module:
304 def __init__(self):
305 module_args = dict(
306 path=dict(type='str', required=True),
307 add=dict(type='str'),
308 remove=dict(type='str'),
309 update=dict(type='str'),
310 cmd=dict(type='str'),
311 query=dict(type='str'),
312 extended_query=dict(type='dict', options=dict(
313 attributes=dict(type='list', elements='str', required=True),
314 where=dict(
315 type='list',
316 elements='dict',
317 options={
318 'attribute': dict(type='str'),
319 'is': dict(type='str', choices=["==", "!=", ">", "<", "in", "eq", "not", "more", "less"]),
320 'value': dict(type='raw'),
321 'or': dict(type='list', elements='dict', options={
322 'attribute': dict(type='str', required=True),
323 'is': dict(type='str', choices=["==", "!=", ">", "<", "in", "eq", "not", "more", "less"], required=True),
324 'value': dict(type='raw', required=True),
325 }),
326 },
327 required_together=[('attribute', 'is', 'value')],
328 mutually_exclusive=[('attribute', 'or')],
329 required_one_of=[('attribute', 'or')],
330 ),
331 )),
332 )
333 module_args.update(api_argument_spec())
334
335 self.module = AnsibleModule(argument_spec=module_args,
336 supports_check_mode=False,
337 mutually_exclusive=(('add', 'remove', 'update',
338 'cmd', 'query', 'extended_query'),),)
339
340 check_has_library(self.module)
341
342 self.api = create_api(self.module)
343
344 self.path = self.module.params['path'].split()
345 self.add = self.module.params['add']
346 self.remove = self.module.params['remove']
347 self.update = self.module.params['update']
348 self.arbitrary = self.module.params['cmd']
349
350 self.where = None
351 self.query = self.module.params['query']
352 self.extended_query = self.module.params['extended_query']
353
354 self.result = dict(
355 message=[])
356
357 # create api base path
358 self.api_path = self.api_add_path(self.api, self.path)
359
360 # api calls
361 try:
362 if self.add:
363 self.api_add()
364 elif self.remove:
365 self.api_remove()
366 elif self.update:
367 self.api_update()
368 elif self.query:
369 self.check_query()
370 self.api_query()
371 elif self.extended_query:
372 self.check_extended_query()
373 self.api_extended_query()
374 elif self.arbitrary:
375 self.api_arbitrary()
376 else:
377 self.api_get_all()
378 except UnicodeEncodeError as exc:
379 self.module.fail_json(msg='Error while encoding text: {error}'.format(error=exc))
380
381 def check_query(self):
382 where_index = self.query.find(' WHERE ')
383 if where_index < 0:
384 self.query = self.split_params(self.query)
385 else:
386 where = self.query[where_index + len(' WHERE '):]
387 self.query = self.split_params(self.query[:where_index])
388 # where must be of the format '<attribute> <operator> <value>'
389 m = re.match(r'^\s*([^ ]+)\s+([^ ]+)\s+(.*)$', where)
390 if not m:
391 self.errors("invalid syntax for 'WHERE %s'" % where)
392 try:
393 self.where = [
394 m.group(1), # attribute
395 m.group(2), # operator
396 parse_argument_value(m.group(3).rstrip())[0], # value
397 ]
398 except ParseError as exc:
399 self.errors("invalid syntax for 'WHERE %s': %s" % (where, exc))
400 try:
401 idx = self.query.index('WHERE')
402 self.where = self.query[idx + 1:]
403 self.query = self.query[:idx]
404 except ValueError:
405 # Raised when WHERE has not been found
406 pass
407
408 def check_extended_query_syntax(self, test_atr, or_msg=''):
409 if test_atr['is'] == "in" and not isinstance(test_atr['value'], list):
410 self.errors("invalid syntax 'extended_query':'where':%s%s 'value' must be a type list" % (or_msg, test_atr))
411
412 def check_extended_query(self):
413 if self.extended_query["where"]:
414 for i in self.extended_query['where']:
415 if i["or"] is not None:
416 if len(i['or']) < 2:
417 self.errors("invalid syntax 'extended_query':'where':'or':%s 'or' requires minimum two items" % i["or"])
418 for orv in i['or']:
419 self.check_extended_query_syntax(orv, ":'or':")
420 else:
421 self.check_extended_query_syntax(i)
422
423 def list_to_dic(self, ldict):
424 return convert_list_to_dictionary(ldict, skip_empty_values=True, require_assignment=True)
425
426 def split_params(self, params):
427 if not isinstance(params, str):
428 raise AssertionError('Parameters can only be a string, received %s' % type(params))
429 try:
430 return split_routeros_command(params)
431 except ParseError as e:
432 self.module.fail_json(msg=to_native(e))
433
434 def api_add_path(self, api, path):
435 api_path = api.path()
436 for p in path:
437 api_path = api_path.join(p)
438 return api_path
439
440 def api_get_all(self):
441 try:
442 for i in self.api_path:
443 self.result['message'].append(i)
444 self.return_result(False, True)
445 except LibRouterosError as e:
446 self.errors(e)
447
448 def api_add(self):
449 param = self.list_to_dic(self.split_params(self.add))
450 try:
451 self.result['message'].append("added: .id= %s"
452 % self.api_path.add(**param))
453 self.return_result(True)
454 except LibRouterosError as e:
455 self.errors(e)
456
457 def api_remove(self):
458 try:
459 self.api_path.remove(self.remove)
460 self.result['message'].append("removed: .id= %s" % self.remove)
461 self.return_result(True)
462 except LibRouterosError as e:
463 self.errors(e)
464
465 def api_update(self):
466 param = self.list_to_dic(self.split_params(self.update))
467 if '.id' not in param.keys():
468 self.errors("missing '.id' for %s" % param)
469 try:
470 self.api_path.update(**param)
471 self.result['message'].append("updated: %s" % param)
472 self.return_result(True)
473 except LibRouterosError as e:
474 self.errors(e)
475
476 def api_query(self):
477 keys = {}
478 for k in self.query:
479 if k == "id":
480 self.errors("'%s' must be '.id'" % k)
481 keys[k] = Key(k)
482 try:
483 if self.where:
484 if self.where[1] in ('==', 'eq'):
485 select = self.api_path.select(*keys).where(keys[self.where[0]] == self.where[2])
486 elif self.where[1] in ('!=', 'not'):
487 select = self.api_path.select(*keys).where(keys[self.where[0]] != self.where[2])
488 elif self.where[1] in ('>', 'more'):
489 select = self.api_path.select(*keys).where(keys[self.where[0]] > self.where[2])
490 elif self.where[1] in ('<', 'less'):
491 select = self.api_path.select(*keys).where(keys[self.where[0]] < self.where[2])
492 else:
493 self.errors("'%s' is not operator for 'where'"
494 % self.where[1])
495 else:
496 select = self.api_path.select(*keys)
497 for row in select:
498 self.result['message'].append(row)
499 if len(self.result['message']) < 1:
500 msg = "no results for '%s 'query' %s" % (' '.join(self.path),
501 ' '.join(self.query))
502 if self.where:
503 msg = msg + ' WHERE %s' % ' '.join(self.where)
504 self.result['message'].append(msg)
505 self.return_result(False)
506 except LibRouterosError as e:
507 self.errors(e)
508
509 def build_api_extended_query(self, item):
510 if item['attribute'] not in self.extended_query['attributes']:
511 self.errors("'%s' attribute is not in attributes: %s"
512 % (item, self.extended_query['attributes']))
513 if item['is'] in ('eq', '=='):
514 return self.query_keys[item['attribute']] == item['value']
515 elif item['is'] in ('not', '!='):
516 return self.query_keys[item['attribute']] != item['value']
517 elif item['is'] in ('less', '<'):
518 return self.query_keys[item['attribute']] < item['value']
519 elif item['is'] in ('more', '>'):
520 return self.query_keys[item['attribute']] > item['value']
521 elif item['is'] == 'in':
522 return self.query_keys[item['attribute']].In(*item['value'])
523 else:
524 self.errors("'%s' is not operator for 'is'" % item['is'])
525
526 def api_extended_query(self):
527 self.query_keys = {}
528 for k in self.extended_query['attributes']:
529 if k == 'id':
530 self.errors("'extended_query':'attributes':'%s' must be '.id'" % k)
531 self.query_keys[k] = Key(k)
532 try:
533 if self.extended_query['where']:
534 where_args = []
535 for i in self.extended_query['where']:
536 if i['or']:
537 where_or_args = []
538 for ior in i['or']:
539 where_or_args.append(self.build_api_extended_query(ior))
540 where_args.append(Or(*where_or_args))
541 else:
542 where_args.append(self.build_api_extended_query(i))
543 select = self.api_path.select(*self.query_keys).where(*where_args)
544 else:
545 select = self.api_path.select(*self.extended_query['attributes'])
546 for row in select:
547 self.result['message'].append(row)
548 self.return_result(False)
549 except LibRouterosError as e:
550 self.errors(e)
551
552 def api_arbitrary(self):
553 param = {}
554 self.arbitrary = self.split_params(self.arbitrary)
555 arb_cmd = self.arbitrary[0]
556 if len(self.arbitrary) > 1:
557 param = self.list_to_dic(self.arbitrary[1:])
558 try:
559 arbitrary_result = self.api_path(arb_cmd, **param)
560 for i in arbitrary_result:
561 self.result['message'].append(i)
562 self.return_result(False)
563 except LibRouterosError as e:
564 self.errors(e)
565
566 def return_result(self, ch_status=False, status=True):
567 if not status:
568 self.module.fail_json(msg=self.result['message'])
569 else:
570 self.module.exit_json(changed=ch_status,
571 msg=self.result['message'])
572
573 def errors(self, e):
574 if e.__class__.__name__ == 'TrapError':
575 self.result['message'].append("%s" % e)
576 self.return_result(False, False)
577 self.result['message'].append("%s" % e)
578 self.return_result(False, False)
579
580
581 def main():
582
583 ROS_api_module()
584
585
586 if __name__ == '__main__':
587 main()