Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2016, 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_node
13 short_description: Manages F5 BIG-IP LTM nodes
14 description:
15 - Manages F5 BIG-IP LTM nodes.
16 version_added: "1.0.0"
17 options:
18 state:
19 description:
20 - Specifies the current state of the node. C(enabled) (All traffic
21 allowed), specifies the system sends traffic to this node regardless
22 of the node's state. C(disabled) (Only persistent or active connections
23 allowed), specifies the node can handle only persistent or
24 active connections. C(offline) (Only active connections allowed),
25 specifies the node can handle only active connections. In all
26 cases except C(absent), the node will be created if it does not yet
27 exist.
28 - Be particularly careful about changing the status of a node whose FQDN
29 cannot be resolved. These situations disable your ability to change their
30 C(state) to C(disabled) or C(offline). They will remain in an
31 *Unavailable - Enabled* state.
32 type: str
33 choices:
34 - present
35 - absent
36 - enabled
37 - disabled
38 - offline
39 default: present
40 name:
41 description:
42 - Specifies the name of the node.
43 type: str
44 required: True
45 monitors:
46 description:
47 - Specifies the health monitors the system currently uses to
48 monitor this node.
49 type: list
50 elements: str
51 address:
52 description:
53 - IP address of the node. This can be either IPv4 or IPv6. When creating a
54 new node, you must provide one of either C(address) or C(fqdn). This
55 parameter cannot be updated after it is set.
56 type: str
57 aliases:
58 - ip
59 - host
60 fqdn:
61 description:
62 - FQDN name of the node. This can be any name that is a valid RFC 1123 DNS
63 name. Therefore, the only characters that can be used are "A" to "Z",
64 "a" to "z", "0" to "9", the hyphen ("-") and the period (".").
65 - FQDN names must include at least one period; delineating the host from
66 the domain. For example, C(host.domain).
67 - FQDN names must end with a letter or a number.
68 - When creating a new node, you must provide one of either C(address) or C(fqdn) provided.
69 This parameter cannot be updated after it is set.
70 type: str
71 aliases:
72 - hostname
73 fqdn_address_type:
74 description:
75 - Specifies whether the FQDN of the node resolves to an IPv4 or IPv6 address.
76 - When creating a new node, if this parameter is not specified and C(fqdn) is
77 specified, this parameter will default to C(ipv4).
78 - This parameter cannot be changed after it has been set.
79 type: str
80 choices:
81 - ipv4
82 - ipv6
83 - all
84 fqdn_auto_populate:
85 description:
86 - Specifies whether the system automatically creates ephemeral nodes using
87 the IP addresses returned by the resolution of a DNS query for a node defined
88 by an FQDN.
89 - When C(true), the system generates an ephemeral node for each IP address
90 returned in response to a DNS query for the FQDN of the node. Additionally,
91 when a DNS response indicates the IP address of an ephemeral node no longer
92 exists, the system deletes the ephemeral node.
93 - When C(false), the system resolves a DNS query for the FQDN of the node with the
94 single IP address associated with the FQDN.
95 - When creating a new node, if this parameter is not specified and C(fqdn) is
96 specified, this parameter defaults to C(true).
97 - This parameter cannot be changed after it has been set.
98 type: bool
99 fqdn_up_interval:
100 description:
101 - Specifies the interval at which a query occurs, when the DNS server is up.
102 The associated monitor attempts to probe three times, and marks the server
103 down if it there is no response within the span of three times the interval
104 value, in seconds.
105 - This parameter accepts a value of C(ttl) to query, based off of the TTL of
106 the FQDN. The default TTL interval is similar to specifying C(3600).
107 - When creating a new node, if this parameter is not specified and C(fqdn) is
108 specified, this parameter will default to C(3600).
109 type: str
110 fqdn_down_interval:
111 description:
112 - Specifies the interval in which a query occurs, when the DNS server is down.
113 The associated monitor continues polling as long as the DNS server is down.
114 - When creating a new node, if this parameter is not specified and C(fqdn) is
115 specified, this parameter will default to C(5).
116 type: int
117 description:
118 description:
119 - Specifies descriptive text that identifies the node.
120 - You can remove a description by either specifying an empty string, or by
121 specifying the special value C(none).
122 type: str
123 connection_limit:
124 description:
125 - Node connection limit. Setting this to C(0) disables the limit.
126 type: int
127 rate_limit:
128 description:
129 - Node rate limit (connections-per-second). Setting this to C(0) disables the limit.
130 type: int
131 ratio:
132 description:
133 - Node ratio weight. Valid values range from 1 through 100.
134 - When creating a new node, if this parameter is not specified, the default of
135 C(1) will be used.
136 type: int
137 dynamic_ratio:
138 description:
139 - The dynamic ratio number for the node. Used for dynamic ratio load balancing.
140 - When creating a new node, if this parameter is not specified, the default of
141 C(1) will be used.
142 type: int
143 availability_requirements:
144 description:
145 - If you activate more than one health monitor, specifies the number of health
146 monitors that must receive successful responses in order for the link to be
147 considered available.
148 type: dict
149 suboptions:
150 type:
151 description:
152 - Monitor rule type when C(monitors) is specified.
153 - When creating a new pool, if this value is not specified, the default of
154 'all' will be used.
155 type: str
156 required: True
157 choices:
158 - all
159 - at_least
160 at_least:
161 description:
162 - Specifies the minimum number of active health monitors that must be successful
163 before the link is considered up.
164 - This parameter is only relevant when a C(type) of C(at_least) is used.
165 - This parameter will be ignored if a type of C(all) is used.
166 type: int
167 partition:
168 description:
169 - Device partition to manage resources on.
170 type: str
171 default: Common
172 extends_documentation_fragment: f5networks.f5_modules.f5
173 author:
174 - Tim Rupp (@caphrim007)
175 - Wojciech Wypior (@wojtek0806)
176 '''
177
178 EXAMPLES = r'''
179 - name: Add node
180 bigip_node:
181 host: 10.20.30.40
182 name: 10.20.30.40
183 provider:
184 server: lb.mydomain.com
185 user: admin
186 password: secret
187 delegate_to: localhost
188
189 - name: Add node with a single 'ping' monitor
190 bigip_node:
191 host: 10.20.30.40
192 name: mytestserver
193 monitors:
194 - /Common/icmp
195 provider:
196 server: lb.mydomain.com
197 user: admin
198 password: secret
199 delegate_to: localhost
200
201 - name: Modify node description
202 bigip_node:
203 name: 10.20.30.40
204 description: Our best server yet
205 provider:
206 server: lb.mydomain.com
207 user: admin
208 password: secret
209 delegate_to: localhost
210
211 - name: Delete node
212 bigip_node:
213 state: absent
214 name: 10.20.30.40
215 provider:
216 server: lb.mydomain.com
217 user: admin
218 password: secret
219 delegate_to: localhost
220
221 - name: Force node offline
222 bigip_node:
223 state: disabled
224 name: 10.20.30.40
225 provider:
226 server: lb.mydomain.com
227 user: admin
228 password: secret
229 delegate_to: localhost
230
231 - name: Add node by their FQDN
232 bigip_node:
233 fqdn: foo.bar.com
234 name: foobar.net
235 provider:
236 server: lb.mydomain.com
237 user: admin
238 password: secret
239 delegate_to: localhost
240 '''
241
242 RETURN = r'''
243 monitors:
244 description:
245 - Changed list of monitors for the node.
246 returned: changed and success
247 type: list
248 sample: ['icmp', 'tcp_echo']
249 description:
250 description:
251 - Changed value for the description of the node.
252 returned: changed and success
253 type: str
254 sample: E-Commerce webserver in ORD
255 session:
256 description:
257 - Changed value for the internal session of the node.
258 returned: changed and success
259 type: str
260 sample: user-disabled
261 state:
262 description:
263 - Changed value for the internal state of the node.
264 returned: changed and success
265 type: str
266 sample: user-down
267 '''
268
269 import re
270 import time
271 from datetime import datetime
272
273 from ansible.module_utils.basic import (
274 AnsibleModule, env_fallback
275 )
276 from ansible.module_utils.parsing.convert_bool import (
277 BOOLEANS_FALSE, BOOLEANS_TRUE
278 )
279
280 from ..module_utils.bigip import F5RestClient
281 from ..module_utils.common import (
282 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
283 )
284 from ..module_utils.icontrol import tmos_version
285 from ..module_utils.teem import send_teem
286
287
288 class Parameters(AnsibleF5Parameters):
289 api_map = {
290 'monitor': 'monitors',
291 'connectionLimit': 'connection_limit',
292 'rateLimit': 'rate_limit'
293 }
294
295 api_attributes = [
296 'description',
297 'address',
298 'fqdn',
299 'ratio',
300 'connectionLimit',
301 'rateLimit',
302 'monitor',
303
304 # Used for changing state
305 #
306 # user-enabled (enabled)
307 # user-disabled (disabled)
308 # user-disabled (offline)
309 'session',
310
311 # Used for changing state
312 # user-down (offline)
313 'state'
314 ]
315
316 returnables = [
317 'monitors',
318 'description',
319 'fqdn',
320 'address',
321 'session',
322 'state',
323 'fqdn_auto_populate',
324 'fqdn_address_type',
325 'fqdn_up_interval',
326 'fqdn_down_interval',
327 'fqdn_name',
328 'connection_limit',
329 'ratio',
330 'rate_limit',
331 'availability_requirements'
332 ]
333
334 updatables = [
335 'monitors',
336 'description',
337 'state',
338 'fqdn_up_interval',
339 'fqdn_down_interval',
340 'tmName',
341 'fqdn_auto_populate',
342 'fqdn_address_type',
343 'connection_limit',
344 'ratio',
345 'rate_limit',
346 ]
347
348 def to_return(self):
349 result = {}
350 try:
351 for returnable in self.returnables:
352 result[returnable] = getattr(self, returnable)
353 result = self._filter_params(result)
354 return result
355 except Exception:
356 return result
357
358 @property
359 def rate_limit(self):
360 if self._values['rate_limit'] is None:
361 return None
362 if self._values['rate_limit'] == 'disabled':
363 return 0
364 return int(self._values['rate_limit'])
365
366
367 class Changes(Parameters):
368 pass
369
370
371 class UsableChanges(Changes):
372 @property
373 def fqdn(self):
374 result = dict()
375 if self._values['fqdn_up_interval'] is not None:
376 result['interval'] = self._values['fqdn_up_interval']
377 if self._values['fqdn_down_interval'] is not None:
378 result['downInterval'] = self._values['fqdn_down_interval']
379 if self._values['fqdn_auto_populate'] is not None:
380 result['autopopulate'] = self._values['fqdn_auto_populate']
381 if self._values['fqdn_name'] is not None:
382 result['tmName'] = self._values['fqdn_name']
383 if self._values['fqdn_address_type'] is not None:
384 result['addressFamily'] = self._values['fqdn_address_type']
385 if not result:
386 return None
387 return result
388
389 @property
390 def monitors(self):
391 monitor_string = self._values['monitors']
392 if monitor_string is None:
393 return None
394 if '{' in monitor_string and '}' in monitor_string:
395 tmp = monitor_string.strip('}').split('{')
396 monitor = ''.join(tmp).rstrip()
397 return monitor
398 return monitor_string
399
400
401 class ReportableChanges(Changes):
402 @property
403 def monitors(self):
404 if self._values['monitors'] is None:
405 return []
406 try:
407 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
408 result.sort()
409 return result
410 except Exception:
411 return self._values['monitors']
412
413 @property
414 def availability_requirement_type(self):
415 if self._values['monitors'] is None:
416 return None
417 if 'min ' in self._values['monitors']:
418 return 'at_least'
419 else:
420 return 'all'
421
422 @property
423 def at_least(self):
424 """Returns the 'at least' value from the monitor string.
425 The monitor string for a Require monitor looks like this.
426 min 1 of { /Common/gateway_icmp }
427 This method parses out the first of the numeric values. This values represents
428 the "at_least" value that can be updated in the module.
429 Returns:
430 int: The at_least value if found. None otherwise.
431 """
432 if self._values['monitors'] is None:
433 return None
434 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
435 matches = re.search(pattern, self._values['monitors'])
436 if matches is None:
437 return None
438 return int(matches.group('least'))
439
440 @property
441 def availability_requirements(self):
442 if self._values['monitors'] is None:
443 return None
444 result = dict()
445 result['type'] = self.availability_requirement_type
446 result['at_least'] = self.at_least
447 return result
448
449
450 class ModuleParameters(Parameters):
451 def _get_availability_value(self, type):
452 if self._values['availability_requirements'] is None:
453 return None
454 if self._values['availability_requirements'][type] is None:
455 return None
456 return self._values['availability_requirements'][type]
457
458 @property
459 def monitors_list(self):
460 if self._values['monitors'] is None:
461 return []
462 try:
463 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
464 except Exception:
465 result = self._values['monitors']
466 result.sort()
467 return result
468
469 @property
470 def monitors(self):
471 if self._values['monitors'] is None:
472 return None
473 if self._values['monitors'] == 'default':
474 return 'default'
475 if len(self._values['monitors']) == 1 and self._values['monitors'][0] == '':
476 return '/Common/none'
477 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
478 if len(self.monitors_list) > 1:
479 if self.availability_requirement_type == 'at_least':
480 if self.at_least > len(self.monitors_list):
481 raise F5ModuleError(
482 "The 'at_least' value must not exceed the number of 'monitors'."
483 )
484 monitors = ' '.join(monitors)
485 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
486 else:
487 result = ' and '.join(monitors).strip()
488 return result
489 if len(self.monitors_list) == 1:
490 return monitors[0]
491
492 @property
493 def availability_requirement_type(self):
494 if self._values['availability_requirements'] is None:
495 return None
496 return self._values['availability_requirements']['type']
497
498 @property
499 def at_least(self):
500 return self._get_availability_value('at_least')
501
502 @property
503 def fqdn_up_interval(self):
504 if self._values['fqdn_up_interval'] is None:
505 return None
506 return str(self._values['fqdn_up_interval'])
507
508 @property
509 def fqdn_down_interval(self):
510 if self._values['fqdn_down_interval'] is None:
511 return None
512 return str(self._values['fqdn_down_interval'])
513
514 @property
515 def fqdn_auto_populate(self):
516 auto_populate = self._values.get('fqdn_auto_populate', None)
517 if auto_populate in BOOLEANS_TRUE:
518 return 'enabled'
519 elif auto_populate in BOOLEANS_FALSE:
520 return 'disabled'
521
522 @property
523 def fqdn_name(self):
524 return self._values.get('fqdn', None)
525
526 @property
527 def fqdn(self):
528 if self._values['fqdn'] is None:
529 return None
530 result = dict(
531 addressFamily=self._values.get('fqdn_address_type', None),
532 downInterval=self._values.get('fqdn_down_interval', None),
533 interval=self._values.get('fqdn_up_interval', None),
534 autopopulate=None,
535 tmName=self._values.get('fqdn', None)
536 )
537 auto_populate = self._values.get('fqdn_auto_populate', None)
538 if auto_populate in BOOLEANS_TRUE:
539 result['autopopulate'] = 'enabled'
540 elif auto_populate in BOOLEANS_FALSE:
541 result['autopopulate'] = 'disabled'
542 return result
543
544 @property
545 def description(self):
546 if self._values['description'] is None:
547 return None
548 elif self._values['description'] in ['none', '']:
549 return ''
550 return self._values['description']
551
552
553 class ApiParameters(Parameters):
554 @property
555 def fqdn_up_interval(self):
556 if self._values['fqdn'] is None:
557 return None
558 if 'interval' in self._values['fqdn']:
559 return str(self._values['fqdn']['interval'])
560
561 @property
562 def fqdn_down_interval(self):
563 if self._values['fqdn'] is None:
564 return None
565 if 'downInterval' in self._values['fqdn']:
566 return str(self._values['fqdn']['downInterval'])
567
568 @property
569 def fqdn_address_type(self):
570 if self._values['fqdn'] is None:
571 return None
572 if 'addressFamily' in self._values['fqdn']:
573 return str(self._values['fqdn']['addressFamily'])
574
575 @property
576 def fqdn_auto_populate(self):
577 if self._values['fqdn'] is None:
578 return None
579 if 'autopopulate' in self._values['fqdn']:
580 return str(self._values['fqdn']['autopopulate'])
581
582 @property
583 def description(self):
584 if self._values['description'] in [None, 'none']:
585 return None
586 return self._values['description']
587
588 @property
589 def availability_requirement_type(self):
590 if self._values['monitors'] is None:
591 return None
592 if 'min ' in self._values['monitors']:
593 return 'at_least'
594 else:
595 return 'all'
596
597 @property
598 def monitors_list(self):
599 if self._values['monitors'] is None:
600 return []
601 try:
602 result = re.findall(r'/\w+/[^\s}]+', self._values['monitors'])
603 except Exception:
604 result = self._values['monitors']
605 result.sort()
606 return result
607
608 @property
609 def monitors(self):
610 if self._values['monitors'] is None:
611 return None
612 if self._values['monitors'] == 'default':
613 return 'default'
614 monitors = [fq_name(self.partition, x) for x in self.monitors_list]
615 if len(self.monitors_list) > 1:
616 if self.availability_requirement_type == 'at_least':
617 monitors = ' '.join(monitors)
618 result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors)
619 else:
620 result = ' and '.join(monitors).strip()
621 return result
622 if len(self.monitors_list) == 1:
623 return monitors[0]
624
625 @property
626 def at_least(self):
627 """Returns the 'at least' value from the monitor string.
628
629 The monitor string for a Require monitor looks like this.
630
631 min 1 of { /Common/gateway_icmp }
632
633 This method parses out the first of the numeric values. This values represents
634 the "at_least" value that can be updated in the module.
635
636 Returns:
637 int: The at_least value if found. None otherwise.
638 """
639 if self._values['monitors'] is None:
640 return None
641 pattern = r'min\s+(?P<least>\d+)\s+of\s+'
642 matches = re.search(pattern, self._values['monitors'])
643 if matches is None:
644 return None
645 return matches.group('least')
646
647
648 class Difference(object):
649 def __init__(self, want, have=None):
650 self.want = want
651 self.have = have
652
653 def compare(self, param):
654 try:
655 result = getattr(self, param)
656 return result
657 except AttributeError:
658 return self.__default(param)
659
660 def __default(self, param):
661 attr1 = getattr(self.want, param)
662 try:
663 attr2 = getattr(self.have, param)
664 if attr1 != attr2:
665 return attr1
666 except AttributeError:
667 return attr1
668
669 @property
670 def monitors(self):
671 if self.want.monitors is None:
672 return None
673 if self.want.monitors == 'default' and self.have.monitors == 'default':
674 return None
675 if self.want.monitors == 'default' and self.have.monitors is None:
676 return None
677 if self.want.monitors == '/Common/none' and self.have.monitors == '/Common/none':
678 return None
679 if self.want.monitors == 'default' and len(self.have.monitors) > 0:
680 return 'default'
681 if self.have.monitors is None:
682 return self.want.monitors
683 if self.have.monitors != self.want.monitors:
684 return self.want.monitors
685
686 @property
687 def state(self):
688 result = None
689 if self.want.state in ['present', 'enabled']:
690 if self.have.session not in ['user-enabled', 'monitor-enabled']:
691 result = dict(
692 session='user-enabled',
693 state='user-up',
694 )
695 elif self.want.state == 'disabled':
696 if self.have.session != 'user-disabled' or self.have.state == 'user-down':
697 result = dict(
698 session='user-disabled',
699 state='user-up'
700 )
701 elif self.want.state == 'offline':
702 if self.have.state != 'user-down':
703 result = dict(
704 session='user-disabled',
705 state='user-down'
706 )
707 return result
708
709 @property
710 def description(self):
711 if self.want.description is None:
712 return None
713 if self.have.description is None and self.want.description == '':
714 return None
715 if self.want.description != self.have.description:
716 return self.want.description
717
718
719 class ModuleManager(object):
720 def __init__(self, *args, **kwargs):
721 self.module = kwargs.get('module', None)
722 self.client = F5RestClient(**self.module.params)
723 self.have = None
724 self.want = ModuleParameters(params=self.module.params)
725 self.changes = UsableChanges()
726
727 def _set_changed_options(self):
728 changed = {}
729 for key in Parameters.returnables:
730 if getattr(self.want, key) is not None:
731 changed[key] = getattr(self.want, key)
732 if changed:
733 self.changes = UsableChanges(params=changed)
734
735 def _update_changed_options(self):
736 diff = Difference(self.want, self.have)
737 updatables = Parameters.updatables
738 changed = dict()
739 for k in updatables:
740 change = diff.compare(k)
741 if change is None:
742 continue
743 else:
744 if isinstance(change, dict):
745 changed.update(change)
746 else:
747 changed[k] = change
748 if changed:
749 self.changes = UsableChanges(params=changed)
750 return True
751 return False
752
753 def _announce_deprecations(self):
754 warnings = []
755 if self.want:
756 warnings += self.want._values.get('__warnings', [])
757 if self.have:
758 warnings += self.have._values.get('__warnings', [])
759 for warning in warnings:
760 self.module.deprecate(
761 msg=warning['msg'],
762 version=warning['version']
763 )
764
765 def exec_module(self):
766 start = datetime.now().isoformat()
767 version = tmos_version(self.client)
768 changed = False
769 result = dict()
770 state = self.want.state
771
772 try:
773 if state in ['present', 'enabled', 'disabled', 'offline']:
774 changed = self.present()
775 elif state == "absent":
776 changed = self.absent()
777 except IOError as e:
778 raise F5ModuleError(str(e))
779
780 changes = self.changes.to_return()
781 result.update(**changes)
782 result.update(dict(changed=changed))
783 self._announce_deprecations()
784 send_teem(start, self.client, self.module, version)
785 return result
786
787 def present(self):
788 if self.exists():
789 return self.update()
790 else:
791 return self.create()
792
793 def _check_required_creation_vars(self):
794 if self.want.address is None and self.want.fqdn is None:
795 raise F5ModuleError(
796 "At least one of 'address' or 'fqdn' is required when creating a node"
797 )
798 elif self.want.address is not None and self.want.fqdn is not None:
799 raise F5ModuleError(
800 "Only one of 'address' or 'fqdn' can be provided when creating a node"
801 )
802 elif self.want.fqdn is not None:
803 self.want.update(dict(address='any6'))
804
805 def _munge_creation_state_for_device(self):
806 # Modifying the state before sending to BIG-IP
807 #
808 # The 'state' must be set to None to exclude the values (accepted by this
809 # module) from being sent to the BIG-IP because for specific Ansible states,
810 # BIG-IP will consider those state values invalid.
811 if self.want.state in ['present', 'enabled']:
812 self.want.update(dict(
813 session='user-enabled',
814 state='user-up',
815 ))
816 elif self.want.state in 'disabled':
817 self.want.update(dict(
818 session='user-disabled',
819 state='user-up'
820 ))
821 else:
822 # State 'offline'
823 # Offline state will result in the monitors stopping for the node
824 self.want.update(dict(
825 session='user-disabled',
826
827 # only a valid state can be specified. The module's value is "offline",
828 # but this is an invalid value for the BIG-IP. Therefore set it to user-down.
829 state='user-down',
830
831 # Even user-down wil not work when _creating_ a node, so we register another
832 # want value (that is not sent to the API). This is checked for later to
833 # determine if we have to PATCH the node to be offline.
834 is_offline=True
835 ))
836
837 def create(self):
838 self._check_required_creation_vars()
839 self._munge_creation_state_for_device()
840
841 if self.want.fqdn_name:
842 if self.want.fqdn_auto_populate is None:
843 self.want.update({'fqdn_auto_populate': True})
844 if self.want.fqdn_address_type is None:
845 self.want.update({'fqdn_address_type': 'ipv4'})
846 if self.want.fqdn_up_interval is None:
847 self.want.update({'fqdn_up_interval': 3600})
848 if self.want.fqdn_down_interval is None:
849 self.want.update({'fqdn_down_interval': 5})
850 if self.want.ratio is None:
851 self.want.update({'ratio': 1})
852 if self.want.dynamic_ratio is None:
853 self.want.update({'dynamic_ratio': 1})
854
855 self._set_changed_options()
856 if self.module.check_mode:
857 return True
858
859 # These are being set here because the ``create_on_device`` method
860 # uses ``self.changes`` (to get formatting of parameters correct)
861 # but these two parameters here cannot be changed and also it is
862 # not easy to get the current versions of them for comparison.
863 if self.want.address:
864 self.changes.update({'address': self.want.address})
865 if self.want.fqdn_up_interval is not None:
866 self.changes.update({'fqdn_up_interval': self.want.fqdn_up_interval})
867 if self.want.fqdn_down_interval is not None:
868 self.changes.update({'fqdn_down_interval': self.want.fqdn_down_interval})
869 if self.want.fqdn_auto_populate is not None:
870 self.changes.update({'fqdn_auto_populate': self.want.fqdn_auto_populate})
871 if self.want.fqdn_name is not None:
872 self.changes.update({'fqdn_name': self.want.fqdn_name})
873 if self.want.fqdn_address_type is not None:
874 self.changes.update({'fqdn_address_type': self.want.fqdn_address_type})
875
876 self.create_on_device()
877 if not self.exists():
878 raise F5ModuleError("Failed to create the node")
879 # It appears that you cannot create a node in an 'offline' state, so instead
880 # we update its status to offline after we create it.
881 if self.want.is_offline:
882 self.update_node_offline_on_device()
883 return True
884
885 def should_update(self):
886 result = self._update_changed_options()
887 if result:
888 return True
889 return False
890
891 def update(self):
892 self.have = self.read_current_from_device()
893 if not self.should_update():
894 return False
895
896 if self.want.fqdn_auto_populate is not None:
897 if self.want.fqdn_auto_populate != self.have.fqdn_auto_populate:
898 raise F5ModuleError(
899 "The 'fqdn_auto_populate' parameter cannot be changed."
900 )
901 if self.want.fqdn_address_type is not None:
902 if self.want.fqdn_address_type != self.have.fqdn_address_type:
903 raise F5ModuleError(
904 "The 'fqdn_address_type' parameter cannot be changed."
905 )
906
907 if self.module.check_mode:
908 return True
909
910 self.update_on_device()
911 if self.want.state == 'offline':
912 self.update_node_offline_on_device()
913 return True
914
915 def absent(self):
916 if self.exists():
917 return self.remove()
918 return False
919
920 def remove(self):
921 if self.module.check_mode:
922 return True
923 self.remove_from_device()
924 if self.exists():
925 raise F5ModuleError("Failed to delete the node.")
926 return True
927
928 def read_current_from_device(self):
929 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
930 self.client.provider['server'],
931 self.client.provider['server_port'],
932 transform_name(self.want.partition, self.want.name)
933 )
934 resp = self.client.api.get(uri)
935 try:
936 response = resp.json()
937 except ValueError as ex:
938 raise F5ModuleError(str(ex))
939
940 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
941 return ApiParameters(params=response)
942 raise F5ModuleError(resp.content)
943
944 def exists(self):
945 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
946 self.client.provider['server'],
947 self.client.provider['server_port'],
948 transform_name(self.want.partition, self.want.name)
949 )
950 resp = self.client.api.get(uri)
951 try:
952 response = resp.json()
953 except ValueError as ex:
954 raise F5ModuleError(str(ex))
955
956 if resp.status == 404 or 'code' in response and response['code'] == 404:
957 return False
958 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
959 return True
960
961 errors = [401, 403, 409, 500, 501, 502, 503, 504]
962
963 if resp.status in errors or 'code' in response and response['code'] in errors:
964 if 'message' in response:
965 raise F5ModuleError(response['message'])
966 else:
967 raise F5ModuleError(resp.content)
968
969 def update_node_offline_on_device(self):
970 params = dict(
971 session="user-disabled",
972 state="user-down"
973 )
974 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
975 self.client.provider['server'],
976 self.client.provider['server_port'],
977 transform_name(self.want.partition, self.want.name)
978 )
979 resp = self.client.api.patch(uri, json=params)
980 try:
981 response = resp.json()
982 except ValueError as ex:
983 raise F5ModuleError(str(ex))
984 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
985 return True
986 raise F5ModuleError(resp.content)
987
988 def update_on_device(self):
989 params = self.changes.api_params()
990 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
991 self.client.provider['server'],
992 self.client.provider['server_port'],
993 transform_name(self.want.partition, self.want.name)
994 )
995 if params:
996 resp = self.client.api.patch(uri, json=params)
997 try:
998 response = resp.json()
999 except ValueError as ex:
1000 raise F5ModuleError(str(ex))
1001 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1002 return True
1003 raise F5ModuleError(resp.content)
1004
1005 def create_on_device(self):
1006 params = self.changes.api_params()
1007 params['name'] = self.want.name
1008 params['partition'] = self.want.partition
1009 uri = "https://{0}:{1}/mgmt/tm/ltm/node/".format(
1010 self.client.provider['server'],
1011 self.client.provider['server_port']
1012 )
1013 resp = self.client.api.post(uri, json=params)
1014 try:
1015 response = resp.json()
1016 except ValueError as ex:
1017 raise F5ModuleError(str(ex))
1018
1019 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1020 self._wait_for_fqdn_checks()
1021 return True
1022 raise F5ModuleError(resp.content)
1023
1024 def _wait_for_fqdn_checks(self):
1025 while True:
1026 have = self.read_current_from_device()
1027 if have.state == 'fqdn-checking':
1028 time.sleep(1)
1029 else:
1030 break
1031
1032 def remove_from_device(self):
1033 uri = "https://{0}:{1}/mgmt/tm/ltm/node/{2}".format(
1034 self.client.provider['server'],
1035 self.client.provider['server_port'],
1036 transform_name(self.want.partition, self.want.name)
1037 )
1038 resp = self.client.api.delete(uri)
1039 if resp.status == 200:
1040 return True
1041
1042
1043 class ArgumentSpec(object):
1044 def __init__(self):
1045 self.supports_check_mode = True
1046 argument_spec = dict(
1047 name=dict(required=True),
1048 address=dict(
1049 aliases=['host', 'ip']
1050 ),
1051 fqdn=dict(
1052 aliases=['hostname']
1053 ),
1054 description=dict(),
1055 state=dict(
1056 choices=['absent', 'present', 'enabled', 'disabled', 'offline'],
1057 default='present'
1058 ),
1059 partition=dict(
1060 default='Common',
1061 fallback=(env_fallback, ['F5_PARTITION'])
1062 ),
1063 fqdn_address_type=dict(
1064 choices=['ipv4', 'ipv6', 'all']
1065 ),
1066 fqdn_auto_populate=dict(type='bool'),
1067 fqdn_up_interval=dict(),
1068 fqdn_down_interval=dict(type='int'),
1069 connection_limit=dict(type='int'),
1070 rate_limit=dict(type='int'),
1071 ratio=dict(type='int'),
1072 dynamic_ratio=dict(type='int'),
1073 availability_requirements=dict(
1074 type='dict',
1075 options=dict(
1076 type=dict(
1077 choices=['all', 'at_least'],
1078 required=True
1079 ),
1080 at_least=dict(type='int'),
1081 ),
1082 required_if=[
1083 ['type', 'at_least', ['at_least']],
1084 ]
1085 ),
1086 monitors=dict(
1087 type='list',
1088 elements='str',
1089 ),
1090 )
1091 self.argument_spec = {}
1092 self.argument_spec.update(f5_argument_spec)
1093 self.argument_spec.update(argument_spec)
1094
1095
1096 def main():
1097 spec = ArgumentSpec()
1098
1099 module = AnsibleModule(
1100 argument_spec=spec.argument_spec,
1101 supports_check_mode=spec.supports_check_mode,
1102 )
1103
1104 try:
1105 mm = ModuleManager(module=module)
1106 results = mm.exec_module()
1107 module.exit_json(**results)
1108 except F5ModuleError as ex:
1109 module.fail_json(msg=str(ex))
1110
1111
1112 if __name__ == '__main__':
1113 main()