Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_data_group.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_data_group
13 short_description: Manage data groups on a BIG-IP
14 description:
15 - Allows for managing data groups on a BIG-IP. Data groups provide a way to store collections
16 of values on a BIG-IP for later use in things such as LTM rules, iRules, and ASM policies.
17 version_added: "1.0.0"
18 options:
19 name:
20 description:
21 - Specifies the name of the data group.
22 type: str
23 required: True
24 description:
25 description:
26 - The description of the data group.
27 type: str
28 type:
29 description:
30 - The type of records in this data group.
31 - This parameter is important because it causes the BIG-IP to store your data
32 in different ways to optimize access to it. For example, it would be wrong
33 to specify a list of records containing IP addresses, but label them as a C(string)
34 type.
35 - This value cannot be changed once the data group is created.
36 type: str
37 choices:
38 - address
39 - addr
40 - ip
41 - string
42 - integer
43 - int
44 default: string
45 internal:
46 description:
47 - The type of this data group.
48 - You should only consider setting this value in cases where you know exactly what
49 you are doing, B(or), you are working with a pre-existing internal data group.
50 - Be aware that if you deliberately force this parameter to C(true), and you have a
51 either a large number of records or a large total records size, this large amount
52 of data will be reflected in your BIG-IP configuration. This can lead to B(long)
53 system configuration load times due to parsing and verifying the large
54 configuration.
55 - When this parameter is C(true), there is a limit for uploads of either 4 megabytes
56 or 65,000 records, whichever is more restrictive.
57 - This value cannot be changed once the data group is created.
58 type: bool
59 default: false
60 external_file_name:
61 description:
62 - When creating a new data group, this specifies the file name you want to give an
63 external data group file on the BIG-IP.
64 - This parameter is ignored when C(internal) is C(true).
65 - This parameter can be used to select an existing data group file to use with an
66 existing external data group.
67 - If this value is not provided, it will be given the value specified in C(name) and,
68 therefore, match the name of the data group.
69 - This value may only contain letters, numbers, underscores, dashes, or a period.
70 type: str
71 records:
72 description:
73 - Specifies the records you want to add to a data group.
74 - If you have a large number of records, we recommend you use C(records_src)
75 instead of typing all those records here.
76 - The technical limit of either the number of records, or the total size of all
77 records. Varies with the size of the total resources on your system; in particular,
78 RAM.
79 - When C(internal) is C(false), at least one record must be specified in either C(records)
80 or C(records_src).
81 - "When C(type) is: C(ip), C(address), C(addr) if the addresses use a non-default route domain,
82 they must be explicit about it, meaning they must contain a route domain notation C(%) e.g. 10.10.1.1%11.
83 This is true regardless if the data group resides in a partition or not."
84 type: list
85 elements: raw
86 suboptions:
87 key:
88 description:
89 - The key describing the record in the data group.
90 - The key will be used for validation of the C(type) parameter to this module.
91 type: str
92 required: True
93 value:
94 description:
95 - The value of the key describing the record in the data group.
96 type: raw
97 records_src:
98 description:
99 - Path to a file with records in it.
100 - The file should be well-formed. This means it includes records, one per line,
101 that resemble the following format "key separator value". For example, C(foo := bar).
102 - BIG-IP is strict about this format, but this module is a bit more lax. It will allow
103 you to include arbitrary amounts (including none) of empty space on either side of
104 the separator. For an illustration of this, see the Examples section.
105 - Record keys are limited in length to no more than 65520 characters.
106 - Values of record keys are limited in length to no more than 65520 characters.
107 - The total number of records you can have in your BIG-IP is limited by the memory
108 of the BIG-IP itself.
109 - The format of this content is slightly different depending on whether you specify
110 a C(type) of C(address), C(integer), or C(string). See the examples section for
111 examples of the different types of payload formats that are expected in your data
112 group file.
113 - When C(internal) is C(false), at least one record must be specified in either C(records)
114 or C(records_src).
115 type: path
116 separator:
117 description:
118 - When specifying C(records_src), this is the string of characters that will
119 be used to break apart entries in the C(records_src) into key/value pairs.
120 - By default, the value of this parameter is C(:=).
121 - This value cannot be changed once it is set.
122 - This parameter is only relevant when C(internal) is C(false). It will be ignored
123 otherwise.
124 type: str
125 default: ":="
126 delete_data_group_file:
127 description:
128 - When C(true), ensures the remote data group file is deleted.
129 - This parameter is only relevant when C(state) is C(absent) and C(internal) is C(false).
130 type: bool
131 default: false
132 partition:
133 description:
134 - Device partition to manage resources on.
135 type: str
136 default: Common
137 state:
138 description:
139 - When C(state) is C(present), ensures the data group exists.
140 - When C(state) is C(absent), ensures the data group is removed.
141 - The use of state in this module refers to the entire data group, not its members.
142 type: str
143 choices:
144 - present
145 - absent
146 default: present
147 notes:
148 - This module does NOT support atomic updates of data group members in a type C(internal) data group.
149 - Addition/Deletion of data group members in a type C(external) data group should be done through Ansible modules only,
150 if changes are made manually, the Ansible module will not detect those changes.
151 extends_documentation_fragment: f5networks.f5_modules.f5
152 author:
153 - Tim Rupp (@caphrim007)
154 - Wojciech Wypior (@wojtek0806)
155 - Greg Crosby (@crosbygw)
156 '''
157
158 EXAMPLES = r'''
159 - name: Create a data group of addresses
160 bigip_data_group:
161 name: foo
162 internal: true
163 records:
164 - key: 0.0.0.0/32
165 value: External_NAT
166 - key: 10.10.10.10
167 value: No_NAT
168 type: address
169 provider:
170 password: secret
171 server: lb.mydomain.com
172 user: admin
173 delegate_to: localhost
174
175 - name: Create a data group of strings
176 bigip_data_group:
177 name: foo
178 internal: true
179 records:
180 - key: caddy
181 value: ""
182 - key: cafeteria
183 value: ""
184 - key: cactus
185 value: ""
186 type: string
187 provider:
188 password: secret
189 server: lb.mydomain.com
190 user: admin
191 delegate_to: localhost
192
193 - name: Create a data group of IP addresses from a file
194 bigip_data_group:
195 name: foo
196 records_src: /path/to/dg-file
197 type: address
198 provider:
199 password: secret
200 server: lb.mydomain.com
201 user: admin
202 delegate_to: localhost
203
204 - name: Update an existing internal data group of strings
205 bigip_data_group:
206 name: foo
207 internal: true
208 records:
209 - key: caddy
210 value: ""
211 - key: cafeteria
212 value: ""
213 - key: cactus
214 value: ""
215 provider:
216 password: secret
217 server: lb.mydomain.com
218 user: admin
219 delegate_to: localhost
220
221 - name: Show the data format expected for records_content - address 1
222 copy:
223 dest: /path/to/addresses.txt
224 content: |
225 network 10.0.0.0 prefixlen 8 := "Network1",
226 network 172.16.0.0 prefixlen 12 := "Network2",
227 network 192.168.0.0 prefixlen 16 := "Network3",
228 network 2402:9400:1000:0:: prefixlen 64 := "Network4",
229 host 192.168.20.1 := "Host1",
230 host 172.16.1.1 := "Host2",
231 host 172.16.1.1 := "Host3",
232 host 2001:0db8:85a3:0000:0000:8a2e:0370:7334 := "Host4",
233 host 2001:0db8:85a3:0000:0000:8a2e:0370:7334 := "Host5"
234
235 - name: Show the data format expected for records_content - address 2
236 copy:
237 dest: /path/to/addresses.txt
238 content: |
239 10.0.0.0/8 := "Network1",
240 172.16.0.0/12 := "Network2",
241 192.168.0.0/16 := "Network3",
242 2402:9400:1000:0::/64 := "Network4",
243 192.168.20.1 := "Host1",
244 172.16.1.1 := "Host2",
245 172.16.1.1/32 := "Host3",
246 2001:0db8:85a3:0000:0000:8a2e:0370:7334 := "Host4",
247 2001:0db8:85a3:0000:0000:8a2e:0370:7334/128 := "Host5"
248
249 - name: Show the data format expected for records_content - string
250 copy:
251 dest: /path/to/strings.txt
252 content: |
253 a := alpha,
254 b := bravo,
255 c := charlie,
256 x := x-ray,
257 y := yankee,
258 z := zulu,
259
260 - name: Show the data format expected for records_content - integer
261 copy:
262 dest: /path/to/integers.txt
263 content: |
264 1 := bar,
265 2 := baz,
266 3,
267 4,
268 '''
269
270 RETURN = r'''
271 # only common fields returned
272 '''
273
274 import hashlib
275 import os
276 import re
277 from datetime import datetime
278
279 from ansible.module_utils.six import iteritems
280 from ansible.module_utils._text import to_text
281 from ansible.module_utils.basic import (
282 AnsibleModule, env_fallback
283 )
284
285 from ipaddress import (
286 ip_network, ip_interface
287 )
288
289 try:
290 from StringIO import StringIO
291 except ImportError:
292 from io import StringIO
293
294 from ..module_utils.bigip import F5RestClient
295 from ..module_utils.common import (
296 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, transform_name
297 )
298 from ..module_utils.compare import (
299 cmp_str_with_none
300 )
301 from ..module_utils.icontrol import (
302 upload_file, tmos_version
303 )
304 from ..module_utils.ipaddress import is_valid_ip_interface
305 from ..module_utils.teem import send_teem
306
307 LINE_LIMIT = 65000
308 SIZE_LIMIT_BYTES = 4000000
309
310
311 def zero_length(content):
312 content.seek(0, os.SEEK_END)
313 length = content.tell()
314 content.seek(0)
315 if length == 0:
316 return True
317 return False
318
319
320 def size_exceeded(content):
321 records = content
322 records.seek(0, os.SEEK_END)
323 size = records.tell()
324 records.seek(0)
325 if size > SIZE_LIMIT_BYTES:
326 return True
327 return False
328
329
330 def lines_exceeded(content):
331 result = False
332 for i, line in enumerate(content):
333 if i > LINE_LIMIT:
334 result = True
335 content.seek(0)
336 return result
337
338
339 class RecordsEncoder(object):
340 def __init__(self, record_type=None, separator=None):
341 self._record_type = record_type
342 self._separator = separator
343 self._network_pattern = re.compile(r'^network\s+(?P<addr>[^ ]+)\s+prefixlen\s+(?P<prefix>\d+)\s+.*')
344 self._rd_net_prefix_ptrn = re.compile(
345 r'^network\s+(?P<addr>[^%]+)%(?P<rd>[0-9]+)\s+prefixlen\s+(?P<prefix>\d+)\s+.*'
346 )
347 self._host_pattern = re.compile(r'^host\s+(?P<addr>[^%]+)\s+.*')
348 self._rd_host_ptrn = re.compile(r'^host\s+(?P<addr>[^%]+)%(?P<rd>[0-9]+)\s+.*')
349 self._ipv4_cidr_ptrn = re.compile(r'^(?P<addr>((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|'
350 r'2[0-4][0-9]|[01]?[0-9][0-9]?))/(?P<cidr>(3[0-2]|2[0-9]|1[0-9]|[0-9]))')
351 self._ipv4_cidr_ptrn_rd = re.compile(r'^(?P<addr>((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|'
352 r'2[0-4][0-9]|[01]?[0-9][0-9]?))%(?P<rd>[0-9]+)/'
353 r'(?P<cidr>(3[0-2]|2[0-9]|1[0-9]|[0-9]))')
354 self._ipv6_cidr_ptrn = re.compile(r'^(?P<addr>^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:)'
355 r'{1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}'
356 r'(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|'
357 r'([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}'
358 r'(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:'
359 r'((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}'
360 r'|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.)'
361 r'{3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:'
362 r'((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}'
363 r'[0-9]){0,1}[0-9])))/(?P<cidr>((1(1[0-9]|2[0-8]))|([0-9][0-9])|([0-9])))')
364 self._ipv6_cidr_ptrn_rd = re.compile(r'^(?P<addr>^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|'
365 r'([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|'
366 r'([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|'
367 r'([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|'
368 r'([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|'
369 r'([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|'
370 r'[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|'
371 r':)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}'
372 r'|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|'
373 r'1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|'
374 r'([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.)'
375 r'{3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])))%(?P<rd>[0-9]+)'
376 r'/(?P<cidr>((1(1[0-9]|2[0-8]))|([0-9][0-9])|([0-9])))')
377
378 def encode(self, record):
379 if isinstance(record, dict):
380 return self.encode_dict(record)
381 else:
382 return self.encode_string(record)
383
384 def encode_dict(self, record):
385 if self._record_type == 'ip':
386 return self.encode_address_from_dict(record)
387 elif self._record_type == 'integer':
388 return self.encode_integer_from_dict(record)
389 else:
390 return self.encode_string_from_dict(record)
391
392 def encode_rd_address(self, record, match, ipv6=False):
393 if is_valid_ip_interface(match.group('addr')):
394 key = ip_interface(u"{0}/{1}".format(match.group('addr'), match.group('cidr')))
395 else:
396 raise F5ModuleError(
397 "When specifying an 'address' type, the value to the left of the separator must be an IP."
398 )
399 if key and 'value' in record:
400 if ipv6 and key.network.prefixlen == 128:
401 return self.encode_host(str(key.ip) + '%' + match.group('rd'), record['value'])
402 else:
403 if not ipv6 and key.network.prefixlen == 32:
404 return self.encode_host(str(key.ip) + '%' + match.group('rd'), record['value'])
405 return self.encode_network(
406 str(key.network.network_address) + '%' + match.group('rd'), key.network.prefixlen, record['value']
407 )
408 elif key:
409 if ipv6 and key.network.prefixlen == 128:
410 return self.encode_host(
411 str(key.ip) + '%' + match.group('rd'), str(key.ip) + '%' + match.group('rd')
412 )
413 else:
414 if not ipv6 and key.network.prefixlen == 32:
415 return self.encode_host(
416 str(key.ip) + '%' + match.group('rd'), str(key.ip) + '%' + match.group('rd')
417 )
418 return self.encode_network(
419 str(key.network.network_address) + '%' + match.group('rd'), key.network.prefixlen,
420 str(key.network.network_address) + '%' + match.group('rd')
421 )
422
423 def encode_address_from_dict(self, record):
424 rd_match = re.match(self._ipv4_cidr_ptrn_rd, record['key'])
425 if rd_match:
426 return self.encode_rd_address(record, rd_match)
427 rd_match = re.match(self._ipv6_cidr_ptrn_rd, record['key'])
428 if rd_match:
429 return self.encode_rd_address(record, rd_match, ipv6=True)
430 if is_valid_ip_interface(record['key']):
431 key = ip_interface(u"{0}".format(str(record['key'])))
432 else:
433 raise F5ModuleError(
434 "When specifying an 'address' type, the value to the left of the separator must be an IP."
435 )
436 ipv4_match = re.match(self._ipv4_cidr_ptrn, record['key'])
437 ipv6_match = re.match(self._ipv6_cidr_ptrn, record['key'])
438
439 if key and 'value' in record:
440 if (ipv6_match and key.network.prefixlen == 128) or (ipv4_match and key.network.prefixlen == 32):
441 return self.encode_host(str(key.ip), record['value'])
442 else:
443 return self.encode_network(
444 str(key.network.network_address), key.network.prefixlen, record['value']
445 )
446 elif key:
447 if (ipv6_match and key.network.prefixlen == 128) or (ipv4_match and key.network.prefixlen == 32):
448 return self.encode_host(str(key.ip), str(key.ip))
449 else:
450 return self.encode_network(
451 str(key.network.network_address), key.network.prefixlen, str(key.network.network_address)
452 )
453
454 def encode_integer_from_dict(self, record):
455 try:
456 int(record['key'])
457 except ValueError:
458 raise F5ModuleError(
459 "When specifying an 'integer' type, the value to the left of the separator must be a number."
460 )
461 if 'key' in record and 'value' in record:
462 return '{0} {1} {2}'.format(record['key'], self._separator, record['value'])
463 elif 'key' in record:
464 return str(record['key'])
465
466 def encode_string_from_dict(self, record):
467 if 'key' in record and 'value' in record:
468 return '{0} {1} {2}'.format(record['key'], self._separator, record['value'])
469 elif 'key' in record:
470 return '{0} {1} ""'.format(record['key'], self._separator)
471
472 def encode_string(self, record):
473 record = record.strip().strip(',')
474 if self._record_type == 'ip':
475 return self.encode_address_from_string(record)
476 elif self._record_type == 'integer':
477 return self.encode_integer_from_string(record)
478 else:
479 return self.encode_string_from_string(record)
480
481 def encode_address_from_string(self, record):
482 if self._network_pattern.match(record):
483 # network 192.168.0.0 prefixlen 16 := "Network3"
484 # network 2402:9400:1000:0:: prefixlen 64 := "Network4"
485 return record
486 elif self._host_pattern.match(record):
487 # host 172.16.1.1/32 := "Host3"
488 # host 2001:0db8:85a3:0000:0000:8a2e:0370:7334 := "Host4"
489 return record
490 elif self._rd_net_prefix_ptrn.match(record) or self._rd_host_ptrn.match(record):
491 # network 192.168.0.0%11/16 := "Network3"
492 # network 2402:9400:1000:0::%11/64 := "Network4"
493 # host 192.168.1.1%11/32 := "Host3"
494 # host 2001:0db8:85a3:0000:0000:8a2e:0370:7334%11 := "Host4"
495 return record
496 elif self._ipv4_cidr_ptrn_rd.match(record) or self._ipv6_cidr_ptrn_rd.match(record):
497 # 10.0.0.0%12/8
498 # 2402:6940::%12/32 := "Network2"
499 # 192.168.1.1%12/32 := "Host1"
500 # 2402:9400:1000::%12/128
501 parts = [r.strip() for r in record.split(self._separator)]
502 if parts[0] == '':
503 return
504 pattern = re.compile(r'(?P<addr>[^%]+)%(?P<rd>[0-9]+)/(?P<prefix>[0-9]+)')
505 match = pattern.match(parts[0])
506 addr = u"{0}/{1}".format(match.group('addr'), match.group('prefix'))
507 if not is_valid_ip_interface(addr):
508 raise F5ModuleError(
509 "When specifying an 'address' type, the value to the left of the separator must be an IP."
510 )
511 key = ip_interface(addr)
512 ipv4_match = re.match(self._ipv4_cidr_ptrn, addr)
513 ipv6_match = re.match(self._ipv6_cidr_ptrn, addr)
514 if len(parts) == 2:
515 if (ipv4_match and key.network.prefixlen == 32) or (ipv6_match and key.network.prefixlen == 128):
516 return self.encode_host(str(key.ip) + '%' + str(match.group('rd')), parts[1])
517 else:
518 return self.encode_network(
519 str(key.network.network_address) + '%' + str(match.group('rd')),
520 key.network.prefixlen, parts[1]
521 )
522 elif len(parts) == 1 and parts[0] != '':
523 if (ipv4_match and key.network.prefixlen == 32) or (ipv6_match and key.network.prefixlen == 128):
524 return self.encode_host(
525 str(key.ip) + '%' + str(match.group('rd')), str(key.ip) + '%' + str(match.group('rd'))
526 )
527 return self.encode_network(
528 str(key.network.network_address) + '%' + str(match.group('rd')),
529 key.network.prefixlen, str(key.network.network_address) + '%' + str(match.group('rd'))
530 )
531 else:
532 # 192.168.0.0/16 := "Network3"
533 # 2402:9400:1000:0::/64 := "Network4"
534 # 10.0.0.0/8
535 # 2402:6940::/32 := "Network2"
536 # 192.168.1.1/32 := "Host1"
537 # 2402:9400:1000::/128
538 parts = [r.strip() for r in record.split(self._separator)]
539 if parts[0] == '':
540 return
541 if len(re.split(' ', parts[0])) == 1:
542 if not is_valid_ip_interface(parts[0]):
543 raise F5ModuleError(
544 "When specifying an 'address' type, the value to the left of the separator must be an IP."
545 )
546 key = ip_interface(u"{0}".format(str(parts[0])))
547 ipv4_match = re.match(self._ipv4_cidr_ptrn, str(parts[0]))
548 ipv6_match = re.match(self._ipv6_cidr_ptrn, str(parts[0]))
549
550 if len(parts) == 2:
551 if (ipv4_match and key.network.prefixlen == 32) or (ipv6_match and key.network.prefixlen == 128):
552 return self.encode_host(str(key.ip), parts[1])
553 else:
554 return self.encode_network(str(key.network.network_address), key.network.prefixlen, parts[1])
555 elif len(parts) == 1 and parts[0] != '':
556 if (ipv4_match and key.network.prefixlen == 32) or (ipv6_match and key.network.prefixlen == 128):
557 return self.encode_host(str(key.ip), str(key.ip))
558 return self.encode_network(
559 str(key.network.network_address), key.network.prefixlen, str(key.network.network_address)
560 )
561 else:
562 return str(parts[0])
563
564 def encode_host(self, key, value):
565 return 'host {0} {1} {2}'.format(str(key), self._separator, str(value))
566
567 def encode_network(self, key, prefixlen, value):
568 return 'network {0} prefixlen {1} {2} {3}'.format(
569 str(key), str(prefixlen), self._separator, str(value)
570 )
571
572 def encode_integer_from_string(self, record):
573 parts = record.split(self._separator)
574 if len(parts) == 1 and parts[0] == '':
575 return None
576 try:
577 int(parts[0])
578 except ValueError:
579 raise F5ModuleError(
580 "When specifying an 'integer' type, the value to the left of the separator must be a number."
581 )
582 if len(parts) == 2:
583 return '{0} {1} {2}'.format(parts[0], self._separator, parts[1])
584 elif len(parts) == 1:
585 return str(parts[0])
586
587 def encode_string_from_string(self, record):
588 parts = record.split(self._separator)
589 if len(parts) == 2:
590 return '{0} {1} {2}'.format(parts[0], self._separator, parts[1])
591 elif len(parts) == 1 and parts[0] != '':
592 return '{0} {1} ""'.format(parts[0], self._separator)
593
594
595 class RecordsDecoder(object):
596 def __init__(self, record_type=None, separator=None):
597 self._record_type = record_type
598 self._separator = separator
599 self._net_prefix_pattern = re.compile(r'^network\s+(?P<addr>[^ ]+)\s+prefixlen\s+(?P<prefix>\d+)\s+.*')
600 self._rd_net_prefix_ptrn = re.compile(r'^network\s+(?P<addr>[^%]+)%(?P<rd>[0-9]+)'
601 r'\s+prefixlen\s+(?P<prefix>\d+)\s+.*')
602 self._host_pattern = re.compile(r'^host\s+(?P<addr>[^ ,]+)\s?.*')
603 self._net_pattern = re.compile(r'^^network\s+(?P<addr>[^ ,]+)\s?.*')
604 self._rd_host_ptrn = re.compile(r'^host\s+(?P<addr>[^%]+)%(?P<rd>[0-9]+)\s+.*')
605
606 def decode(self, record):
607 record = record.strip().strip(',')
608 if self._record_type == 'ip':
609 return self.decode_address_from_string(record)
610 else:
611 return self.decode_from_string(record)
612
613 def decode_address_from_string(self, record):
614 matches = self._rd_net_prefix_ptrn.match(record)
615 if matches:
616 # network 192.168.0.0%11 prefixlen 16 := "Network3",
617 # network 2402:9400:1000:0::%11 prefixlen 64 := "Network4",
618 value = record.split(self._separator)[1].strip().strip('"')
619 addr = "{0}%{1}/{2}".format(matches.group('addr'), matches.group('rd'), matches.group('prefix'))
620 result = dict(name=addr, data=value)
621 return result
622 matches = self._net_prefix_pattern.match(record)
623 if matches:
624 # network 192.168.0.0 prefixlen 16 := "Network3",
625 # network 2402:9400:1000:0:: prefixlen 64 := "Network4",
626 key = u"{0}/{1}".format(matches.group('addr'), matches.group('prefix'))
627 addr = ip_network(key)
628 value = record.split(self._separator)[1].strip().strip('"')
629 result = dict(name=str(addr), data=value)
630 return result
631 matches = self._net_pattern.match(record)
632 if matches:
633 # network 192.168.2.0/24,
634 # network 2402:9400:1000:0:: prefixlen 64 := "Network4",
635 key = u"{0}".format(matches.group('addr'))
636 addr = ip_network(key)
637 if len(record.split(self._separator)) > 1:
638 value = record.split(self._separator)[1].strip().strip('"')
639 result = dict(name=str(addr), data=value)
640 return result
641 return str(record)
642 matches = self._rd_host_ptrn.match(record)
643 if matches:
644 # host 172.16.1.1%11/32 := "Host3"
645 # host 2001:0db8:85a3:0000:0000:8a2e:0370:7334%11 := "Host4"
646 host = ip_interface(u"{0}".format(matches.group('addr')))
647 addr = "{0}%{1}/{2}".format(matches.group('addr'), matches.group('rd'), str(host.network.prefixlen))
648 value = record.split(self._separator)[1].strip().strip('"')
649 result = dict(name=addr, data=value)
650 return result
651 matches = self._host_pattern.match(record)
652 if matches:
653 # host 172.16.1.1/32 := "Host3"
654 # host 2001:0db8:85a3:0000:0000:8a2e:0370:7334 := "Host4"
655 key = matches.group('addr')
656 addr = ip_interface(u"{0}".format(str(key)))
657 if len(record.split(self._separator)) > 1:
658 value = record.split(self._separator)[1].strip().strip('"')
659 result = dict(name=str(addr), data=value)
660 return result
661 return str(record)
662
663 raise F5ModuleError(
664 'The value "{0}" is not an address'.format(record)
665 )
666
667 def decode_from_string(self, record):
668 parts = record.split(self._separator)
669 if len(parts) == 2:
670 return dict(name=parts[0].strip(), data=parts[1].strip().strip('"'))
671 else:
672 return dict(name=parts[0].strip(), data="")
673
674
675 class Parameters(AnsibleF5Parameters):
676 api_map = {
677 'externalFileName': 'external_file_name',
678 }
679
680 api_attributes = [
681 'records',
682 'type',
683 'description',
684 ]
685
686 returnables = [
687 'type',
688 'records',
689 'description',
690 ]
691
692 updatables = [
693 'records',
694 'checksum',
695 'description',
696 ]
697
698 @property
699 def type(self):
700 if self._values['type'] in ['address', 'addr', 'ip']:
701 return 'ip'
702 elif self._values['type'] in ['integer', 'int']:
703 return 'integer'
704 elif self._values['type'] in ['string']:
705 return 'string'
706
707 @property
708 def records_src(self):
709 try:
710 self._values['records_src'].seek(0)
711 return self._values['records_src']
712 except AttributeError:
713 pass
714
715 if self._values['records_src']:
716 records = open(self._values['records_src'])
717 else:
718 records = self._values['records']
719
720 if records is None:
721 return None
722
723 # There is a 98% chance that the user will supply a data group that is < 1MB.
724 # 99.917% chance it is less than 10 MB. This is well within the range of typical
725 # memory available on a system.
726 #
727 # If this changes, this may need to be changed to use temporary files instead.
728 self._values['records_src'] = StringIO()
729
730 self._write_records_to_file(records)
731 return self._values['records_src']
732
733 def _write_records_to_file(self, records):
734 bucket_size = 1000000
735 bucket = []
736 encoder = RecordsEncoder(record_type=self.type, separator=self.separator)
737 for record in records:
738 result = encoder.encode(record)
739 if result:
740 bucket.append(to_text(result + ",\n"))
741 if len(bucket) == bucket_size:
742 self._values['records_src'].writelines(bucket)
743 bucket = []
744 self._values['records_src'].writelines(bucket)
745 self._values['records_src'].seek(0)
746
747
748 class ApiParameters(Parameters):
749 @property
750 def checksum(self):
751 if self._values['checksum'] is None:
752 return None
753 result = self._values['checksum'].split(':')[2]
754 return result
755
756 @property
757 def records(self):
758 cleaned_records_list = []
759 if self._values['records'] is None:
760 return None
761 for record in self._values['records']:
762 clean_record = {}
763 for k, v in record.items():
764 clean_record[k] = re.sub('\\\\', '', v)
765 cleaned_records_list.append(clean_record)
766 return cleaned_records_list
767
768 @property
769 def records_list(self):
770 return self._values['records']
771
772 @property
773 def description(self):
774 if self._values['description'] in [None, 'none']:
775 return None
776 return self._values['description']
777
778
779 class ModuleParameters(Parameters):
780 @property
781 def description(self):
782 if self._values['description'] is None:
783 return None
784 elif self._values['description'] in ['none', '']:
785 return ''
786 return self._values['description']
787
788 @property
789 def checksum(self):
790 if self._values['checksum']:
791 return self._values['checksum']
792 if self.records_src is None:
793 return None
794 result = hashlib.sha1()
795 records = self.records_src
796 while True:
797 data = records.read(4096)
798 if not data:
799 break
800 result.update(data.encode('utf-8'))
801 result = result.hexdigest()
802 self._values['checksum'] = result
803 return result
804
805 @property
806 def external_file_name(self):
807 if self._values['external_file_name'] is None:
808 name = self.name
809 else:
810 name = self._values['external_file_name']
811 if re.search(r'[^a-zA-Z0-9-_.]', name):
812 raise F5ModuleError(
813 "'external_file_name' may only contain letters, numbers, underscores, dashes, or a period."
814 )
815 return name
816
817 @property
818 def records(self):
819 results = []
820 if self.records_src is None:
821 return None
822 decoder = RecordsDecoder(record_type=self.type, separator=self.separator)
823 for record in self.records_src:
824 result = decoder.decode(record)
825 if result:
826 results.append(result)
827 return results
828
829 @property
830 def records_list(self):
831 if self._values['records'] is None:
832 return None
833 return self.records
834
835
836 class Changes(Parameters):
837 def to_return(self):
838 result = {}
839 try:
840 for returnable in self.returnables:
841 result[returnable] = getattr(self, returnable)
842 result = self._filter_params(result)
843 except Exception:
844 pass
845 return result
846
847
848 class UsableChanges(Changes):
849 pass
850
851
852 class ReportableChanges(Changes):
853 pass
854
855
856 class Difference(object):
857 def __init__(self, want, have=None):
858 self.want = want
859 self.have = have
860
861 def compare(self, param):
862 try:
863 result = getattr(self, param)
864 return result
865 except AttributeError:
866 return self.__default(param)
867
868 def __default(self, param):
869 attr1 = getattr(self.want, param)
870 try:
871 attr2 = getattr(self.have, param)
872 if attr1 != attr2:
873 return attr1
874 except AttributeError:
875 return attr1
876
877 def _compare_records(self):
878 want = self.want.records
879 have = self.have.records
880 if want == [] and have is None:
881 return None
882 if want is None:
883 return None
884 w = []
885 h = []
886
887 for x in want:
888 tmp = tuple((str(k), str(v)) for k, v in iteritems(x))
889 w.append(tmp)
890 for x in have:
891 tmp = tuple((str(k), str(v)) for k, v in iteritems(x))
892 h.append(tmp)
893
894 if set(w) == set(h):
895 return None
896 else:
897 return want
898
899 @property
900 def records(self):
901 # External data groups are compared by their checksum, not their records. This
902 # is because the BIG-IP does not store the actual records in the API. It instead
903 # stores the checksum of the file. External DGs have the possibility of being huge
904 # and we would never want to do a comparison of such huge files.
905 #
906 # Therefore, comparison is no-op if the DG being worked with is an external DG.
907 if self.want.internal is False:
908 return None
909 if self.have.records is None and self.want.records == []:
910 return None
911 if self.have.records is None:
912 return self.want.records
913 result = self._compare_records()
914 return result
915
916 @property
917 def type(self):
918 return None
919
920 @property
921 def checksum(self):
922 if self.want.internal:
923 return None
924 if self.want.checksum is None:
925 return None
926 if self.want.checksum != self.have.checksum:
927 return True
928
929 @property
930 def description(self):
931 return cmp_str_with_none(self.want.description, self.have.description)
932
933
934 class BaseManager(object):
935 def __init__(self, *args, **kwargs):
936 self.module = kwargs.get('module', None)
937 self.client = F5RestClient(**self.module.params)
938 self.want = ModuleParameters(params=self.module.params)
939 self.have = ApiParameters()
940 self.changes = UsableChanges()
941
942 def should_update(self):
943 result = self._update_changed_options()
944 if result:
945 return True
946 return False
947
948 def exec_module(self):
949 start = datetime.now().isoformat()
950 version = tmos_version(self.client)
951 changed = False
952 result = dict()
953 state = self.want.state
954
955 if state == "present":
956 changed = self.present()
957 elif state == "absent":
958 changed = self.absent()
959
960 reportable = ReportableChanges(params=self.changes.to_return())
961 changes = reportable.to_return()
962 result.update(**changes)
963 result.update(dict(changed=changed))
964 self._announce_deprecations(result)
965 send_teem(start, self.client, self.module, version)
966 return result
967
968 def _announce_deprecations(self, result):
969 warnings = result.pop('__warnings', [])
970 for warning in warnings:
971 self.client.module.deprecate(
972 msg=warning['msg'],
973 version=warning['version']
974 )
975
976 def _set_changed_options(self):
977 changed = {}
978 for key in ApiParameters.returnables:
979 if getattr(self.want, key) is not None:
980 changed[key] = getattr(self.want, key)
981 if changed:
982 self.changes = UsableChanges(params=changed)
983
984 def _update_changed_options(self):
985 diff = Difference(self.want, self.have)
986 updatables = ApiParameters.updatables
987 changed = dict()
988 for k in updatables:
989 change = diff.compare(k)
990 if change is None:
991 continue
992 else:
993 if isinstance(change, dict):
994 changed.update(change)
995 else:
996 changed[k] = change
997 if changed:
998 self.changes = UsableChanges(params=changed)
999 return True
1000 return False
1001
1002 def present(self):
1003 if self.exists():
1004 return self.update()
1005 else:
1006 return self.create()
1007
1008 def absent(self):
1009 if self.exists():
1010 return self.remove()
1011 return False
1012
1013 def remove(self):
1014 if self.module.check_mode:
1015 return True
1016 self.remove_from_device()
1017 if self.exists():
1018 raise F5ModuleError("Failed to delete the resource.")
1019 return True
1020
1021
1022 class InternalManager(BaseManager):
1023 def create(self):
1024 self._set_changed_options()
1025 if size_exceeded(self.want.records_src) or lines_exceeded(self.want.records_src):
1026 raise F5ModuleError(
1027 "The size of the provided data (or file) is too large for an internal data group."
1028 )
1029 if self.module.check_mode:
1030 return True
1031 self.create_on_device()
1032 return True
1033
1034 def update(self):
1035 self.have = self.read_current_from_device()
1036 if not self.should_update():
1037 return False
1038 if self.module.check_mode:
1039 return True
1040 self.update_on_device()
1041 return True
1042
1043 def exists(self):
1044 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1045 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/internal/{2}".format(
1046 self.client.provider['server'],
1047 self.client.provider['server_port'],
1048 transform_name(self.want.partition, self.want.name)
1049 )
1050 resp = self.client.api.get(uri)
1051 try:
1052 response = resp.json()
1053 except ValueError as ex:
1054 raise F5ModuleError(str(ex))
1055
1056 if resp.status == 404 or 'code' in response and response['code'] == 404:
1057 return False
1058 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1059 return True
1060
1061 if resp.status in errors or 'code' in response and response['code'] in errors:
1062 if 'message' in response:
1063 raise F5ModuleError(response['message'])
1064 else:
1065 raise F5ModuleError(resp.content)
1066
1067 def create_on_device(self):
1068 params = self.changes.api_params()
1069 params['name'] = self.want.name
1070 params['partition'] = self.want.partition
1071 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/internal/".format(
1072 self.client.provider['server'],
1073 self.client.provider['server_port'],
1074 )
1075 resp = self.client.api.post(uri, json=params)
1076 try:
1077 response = resp.json()
1078 except ValueError as ex:
1079 raise F5ModuleError(str(ex))
1080
1081 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1082 return True
1083 raise F5ModuleError(resp.content)
1084
1085 def update_on_device(self):
1086 params = self.changes.api_params()
1087 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/internal/{2}".format(
1088 self.client.provider['server'],
1089 self.client.provider['server_port'],
1090 transform_name(self.want.partition, self.want.name)
1091 )
1092 resp = self.client.api.patch(uri, json=params)
1093 try:
1094 response = resp.json()
1095 except ValueError as ex:
1096 raise F5ModuleError(str(ex))
1097
1098 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1099 return True
1100 raise F5ModuleError(resp.content)
1101
1102 def remove_from_device(self):
1103 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/internal/{2}".format(
1104 self.client.provider['server'],
1105 self.client.provider['server_port'],
1106 transform_name(self.want.partition, self.want.name)
1107 )
1108 response = self.client.api.delete(uri)
1109
1110 if response.status in [200, 201]:
1111 return True
1112 raise F5ModuleError(response.content)
1113
1114 def read_current_from_device(self):
1115 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/internal/{2}".format(
1116 self.client.provider['server'],
1117 self.client.provider['server_port'],
1118 transform_name(self.want.partition, self.want.name)
1119 )
1120 resp = self.client.api.get(uri)
1121 try:
1122 response = resp.json()
1123 except ValueError as ex:
1124 raise F5ModuleError(str(ex))
1125
1126 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1127 return ApiParameters(params=response)
1128 raise F5ModuleError(resp.content)
1129
1130
1131 class ExternalManager(BaseManager):
1132 def absent(self):
1133 result = False
1134 if self.exists():
1135 result = self.remove()
1136 if self.external_file_exists() and self.want.delete_data_group_file:
1137 result = self.remove_data_group_file_from_device()
1138 return result
1139
1140 def create(self):
1141 if zero_length(self.want.records_src):
1142 raise F5ModuleError(
1143 "An external data group cannot be empty."
1144 )
1145 self._set_changed_options()
1146 if self.module.check_mode:
1147 return True
1148 self.create_on_device()
1149 return True
1150
1151 def update(self):
1152 self.have = self.read_current_from_device()
1153 if not self.should_update():
1154 return False
1155 if self.changes.records_src and zero_length(self.want.records_src):
1156 raise F5ModuleError(
1157 "An external data group cannot be empty."
1158 )
1159 if self.module.check_mode:
1160 return True
1161 self.update_on_device()
1162 return True
1163
1164 def exists(self):
1165 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1166 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/external/{2}".format(
1167 self.client.provider['server'],
1168 self.client.provider['server_port'],
1169 transform_name(self.want.partition, self.want.name)
1170 )
1171 resp = self.client.api.get(uri)
1172 try:
1173 response = resp.json()
1174 except ValueError as ex:
1175 raise F5ModuleError(str(ex))
1176
1177 if resp.status == 404 or 'code' in response and response['code'] == 404:
1178 return False
1179 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1180 return True
1181
1182 if resp.status in errors or 'code' in response and response['code'] in errors:
1183 if 'message' in response:
1184 raise F5ModuleError(response['message'])
1185 else:
1186 raise F5ModuleError(resp.content)
1187
1188 def external_file_exists(self):
1189 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1190 uri = "https://{0}:{1}/mgmt/tm/sys/file/data-group/{2}".format(
1191 self.client.provider['server'],
1192 self.client.provider['server_port'],
1193 transform_name(self.want.partition, self.want.external_file_name)
1194 )
1195 resp = self.client.api.get(uri)
1196 try:
1197 response = resp.json()
1198 except ValueError as ex:
1199 raise F5ModuleError(str(ex))
1200
1201 if resp.status == 404 or 'code' in response and response['code'] == 404:
1202 return False
1203 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1204 return True
1205
1206 if resp.status in errors or 'code' in response and response['code'] in errors:
1207 if 'message' in response:
1208 raise F5ModuleError(response['message'])
1209 else:
1210 raise F5ModuleError(resp.content)
1211
1212 def upload_file_to_device(self, content, name):
1213 url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format(
1214 self.client.provider['server'],
1215 self.client.provider['server_port']
1216 )
1217 try:
1218 upload_file(self.client, url, content, name)
1219 except F5ModuleError:
1220 raise F5ModuleError(
1221 "Failed to upload the file."
1222 )
1223
1224 def _upload_to_file(self, name, type, remote_path, update=False):
1225 self.upload_file_to_device(self.want.records_src, name)
1226 if update:
1227 uri = "https://{0}:{1}/mgmt/tm/sys/file/data-group/{2}".format(
1228 self.client.provider['server'],
1229 self.client.provider['server_port'],
1230 transform_name(self.want.partition, name)
1231 )
1232 params = {'sourcePath': 'file:{0}'.format(remote_path)}
1233 resp = self.client.api.patch(uri, json=params)
1234
1235 try:
1236 response = resp.json()
1237 except ValueError as ex:
1238 raise F5ModuleError(str(ex))
1239
1240 else:
1241 uri = "https://{0}:{1}/mgmt/tm/sys/file/data-group/".format(
1242 self.client.provider['server'],
1243 self.client.provider['server_port'],
1244 )
1245 params = dict(
1246 name=name,
1247 type=type,
1248 sourcePath='file:{0}'.format(remote_path),
1249 partition=self.want.partition
1250 )
1251 resp = self.client.api.post(uri, json=params)
1252
1253 try:
1254 response = resp.json()
1255 except ValueError as ex:
1256 raise F5ModuleError(str(ex))
1257
1258 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1259 return response['name']
1260 raise F5ModuleError(resp.content)
1261
1262 def remove_file_on_device(self, remote_path):
1263 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm/".format(
1264 self.client.provider['server'],
1265 self.client.provider['server_port'],
1266 )
1267 args = dict(
1268 command='run',
1269 utilCmdArgs=remote_path
1270 )
1271 resp = self.client.api.post(uri, json=args)
1272 try:
1273 response = resp.json()
1274 except ValueError as ex:
1275 raise F5ModuleError(str(ex))
1276
1277 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1278 return True
1279 raise F5ModuleError(response.content)
1280
1281 def create_on_device(self):
1282 name = self.want.external_file_name
1283 remote_path = '/var/config/rest/downloads/{0}'.format(name)
1284 external_file = self._upload_to_file(name, self.want.type, remote_path, update=False)
1285
1286 params = dict(
1287 name=self.want.name,
1288 partition=self.want.partition,
1289 externalFileName=external_file,
1290 )
1291 if self.want.description:
1292 params['description'] = self.want.description
1293
1294 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/external/".format(
1295 self.client.provider['server'],
1296 self.client.provider['server_port']
1297 )
1298 resp = self.client.api.post(uri, json=params)
1299
1300 try:
1301 response = resp.json()
1302 except ValueError as ex:
1303 raise F5ModuleError(str(ex))
1304
1305 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
1306 raise F5ModuleError(response.content)
1307
1308 self.remove_file_on_device(remote_path)
1309
1310 def update_on_device(self):
1311 params = {}
1312
1313 if self.want.records_src is not None:
1314 name = self.want.external_file_name
1315 remote_path = '/var/config/rest/downloads/{0}'.format(name)
1316 external_file = self._upload_to_file(name, self.have.type, remote_path, update=True)
1317 params['externalFileName'] = external_file
1318 if self.changes.description is not None:
1319 params['description'] = self.changes.description
1320
1321 if not params:
1322 return
1323
1324 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/external/{2}".format(
1325 self.client.provider['server'],
1326 self.client.provider['server_port'],
1327 transform_name(self.want.partition, self.want.name)
1328 )
1329
1330 resp = self.client.api.patch(uri, json=params)
1331
1332 try:
1333 response = resp.json()
1334 except ValueError as ex:
1335 raise F5ModuleError(str(ex))
1336
1337 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1338 return True
1339 raise F5ModuleError(resp.content)
1340
1341 def remove_from_device(self):
1342 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/external/{2}".format(
1343 self.client.provider['server'],
1344 self.client.provider['server_port'],
1345 transform_name(self.want.partition, self.want.name)
1346 )
1347 response = self.client.api.delete(uri)
1348
1349 # Remove the remote data group file if asked to
1350 if self.want.delete_data_group_file:
1351 self.remove_data_group_file_from_device()
1352
1353 if response.status in [200, 201]:
1354 return True
1355 raise F5ModuleError(response.content)
1356
1357 def remove_data_group_file_from_device(self):
1358 uri = "https://{0}:{1}/mgmt/tm/sys/file/data-group/{2}".format(
1359 self.client.provider['server'],
1360 self.client.provider['server_port'],
1361 transform_name(self.want.partition, self.want.external_file_name)
1362 )
1363 response = self.client.api.delete(uri)
1364
1365 if response.status in [200, 201]:
1366 return True
1367 raise F5ModuleError(response.content)
1368
1369 def read_current_from_device(self):
1370 """Reads the current configuration from the device
1371
1372 For an external data group, we are interested in two things from the
1373 current configuration
1374
1375 * ``checksum``
1376 * ``type``
1377
1378 The ``checksum`` will allow us to compare the data group value we have
1379 with the data group value being provided.
1380
1381 The ``type`` will allow us to do validation on the data group value being
1382 provided (if any).
1383
1384 Returns:
1385 ExternalApiParameters: Attributes of the remote resource.
1386 """
1387
1388 uri = "https://{0}:{1}/mgmt/tm/ltm/data-group/external/{2}".format(
1389 self.client.provider['server'],
1390 self.client.provider['server_port'],
1391 transform_name(self.want.partition, self.want.name)
1392 )
1393 resp_dg = self.client.api.get(uri)
1394
1395 try:
1396 response_dg = resp_dg.json()
1397 except ValueError as ex:
1398 raise F5ModuleError(str(ex))
1399
1400 if resp_dg.status not in [200, 201] or 'code' in response_dg and response_dg['code'] not in [200, 201]:
1401 raise F5ModuleError(resp_dg.content)
1402
1403 external_file = os.path.basename(response_dg['externalFileName'])
1404 external_file_partition = os.path.dirname(response_dg['externalFileName']).strip('/')
1405
1406 uri = "https://{0}:{1}/mgmt/tm/sys/file/data-group/{2}".format(
1407 self.client.provider['server'],
1408 self.client.provider['server_port'],
1409 transform_name(external_file_partition, external_file)
1410 )
1411 resp = self.client.api.get(uri)
1412
1413 try:
1414 response = resp.json()
1415 except ValueError as ex:
1416 raise F5ModuleError(str(ex))
1417
1418 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1419 result = ApiParameters(params=response)
1420 result.update({'description': response_dg.get('description', None)})
1421 return result
1422 raise F5ModuleError(resp.content)
1423
1424
1425 class ModuleManager(object):
1426 def __init__(self, *args, **kwargs):
1427 self.kwargs = kwargs
1428 self.module = kwargs.get('module')
1429
1430 def exec_module(self):
1431 if self.module.params['internal']:
1432 manager = self.get_manager('internal')
1433 else:
1434 manager = self.get_manager('external')
1435 return manager.exec_module()
1436
1437 def get_manager(self, type):
1438 if type == 'internal':
1439 return InternalManager(**self.kwargs)
1440 elif type == 'external':
1441 return ExternalManager(**self.kwargs)
1442
1443
1444 class ArgumentSpec(object):
1445 def __init__(self):
1446 self.supports_check_mode = True
1447 argument_spec = dict(
1448 name=dict(required=True),
1449 type=dict(
1450 choices=['address', 'addr', 'ip', 'string', 'integer', 'int'],
1451 default='string'
1452 ),
1453 delete_data_group_file=dict(
1454 type='bool',
1455 default='no'
1456 ),
1457 internal=dict(type='bool', default='no'),
1458 records=dict(
1459 type='list',
1460 elements='raw',
1461 options=dict(
1462 key=dict(required=True, no_log=True),
1463 value=dict(type='raw')
1464 )
1465 ),
1466 records_src=dict(type='path'),
1467 external_file_name=dict(),
1468 separator=dict(default=':='),
1469 description=dict(),
1470 state=dict(choices=['absent', 'present'], default='present'),
1471 partition=dict(
1472 default='Common',
1473 fallback=(env_fallback, ['F5_PARTITION'])
1474 )
1475 )
1476 self.argument_spec = {}
1477 self.argument_spec.update(f5_argument_spec)
1478 self.argument_spec.update(argument_spec)
1479 self.mutually_exclusive = [
1480 ['records', 'records_src']
1481 ]
1482
1483
1484 def main():
1485 spec = ArgumentSpec()
1486
1487 module = AnsibleModule(
1488 argument_spec=spec.argument_spec,
1489 supports_check_mode=spec.supports_check_mode,
1490 mutually_exclusive=spec.mutually_exclusive
1491 )
1492
1493 try:
1494 mm = ModuleManager(module=module)
1495 results = mm.exec_module()
1496 module.exit_json(**results)
1497 except F5ModuleError as ex:
1498 module.fail_json(msg=str(ex))
1499
1500
1501 if __name__ == '__main__':
1502 main()