| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
DOCUMENTATION = r''' |
| 11 |
--- |
| 12 |
module: bigip_policy |
| 13 |
short_description: Manage general policy configuration on a BIG-IP |
| 14 |
description: |
| 15 |
- Manages general policy configuration on a BIG-IP. This module is best |
| 16 |
used in conjunction with the C(bigip_policy_rule) module. This module |
| 17 |
can handle general configuration, like setting the draft state of the policy, |
| 18 |
the description, and items unrelated to the policy rules themselves. |
| 19 |
It is also the first module that should be used when creating rules, as |
| 20 |
the C(bigip_policy_rule) module requires a policy parameter. |
| 21 |
version_added: "1.0.0" |
| 22 |
options: |
| 23 |
description: |
| 24 |
description: |
| 25 |
- The description to attach to the policy. |
| 26 |
- This parameter is only supported on versions of BIG-IP >= 12.1.0. On earlier |
| 27 |
versions it is simply ignored. |
| 28 |
type: str |
| 29 |
name: |
| 30 |
description: |
| 31 |
- The name of the policy to create. |
| 32 |
type: str |
| 33 |
required: True |
| 34 |
state: |
| 35 |
description: |
| 36 |
- When C(state) is C(present), ensures the policy exists and is |
| 37 |
published. When C(state) is C(absent), ensures the policy is removed, |
| 38 |
even if it is currently drafted. |
| 39 |
- When C(state) is C(draft), ensures the policy exists and is drafted. |
| 40 |
When modifying rules, it is required that policies first be in a draft. |
| 41 |
- Drafting is only supported on versions of BIG-IP >= 12.1.0. On versions |
| 42 |
prior to that, specifying a C(state) of C(draft) will raise an error. |
| 43 |
type: str |
| 44 |
choices: |
| 45 |
- present |
| 46 |
- absent |
| 47 |
- draft |
| 48 |
default: present |
| 49 |
strategy: |
| 50 |
description: |
| 51 |
- Specifies the method to determine which actions get executed when |
| 52 |
there are multiple rules that match. When creating new |
| 53 |
policies, the default is C(first). |
| 54 |
- This module does not allow you to specify the C(best) strategy to use. |
| 55 |
It will choose the system default (C(/Common/best-match)) instead. |
| 56 |
type: str |
| 57 |
choices: |
| 58 |
- first |
| 59 |
- all |
| 60 |
- best |
| 61 |
rules: |
| 62 |
description: |
| 63 |
- Specifies a list of rules you want associated with this policy. |
| 64 |
The order of this list is the order they will be evaluated by BIG-IP. |
| 65 |
If the specified rules do not exist (for example when creating a new |
| 66 |
policy) they will be created. |
| 67 |
- The C(conditions) for a default rule are C(all). |
| 68 |
- The C(actions) for a default rule are C(ignore). |
| 69 |
- The C(bigip_policy_rule) module can be used to create and edit existing |
| 70 |
and new rules. |
| 71 |
type: list |
| 72 |
elements: str |
| 73 |
partition: |
| 74 |
description: |
| 75 |
- Device partition to manage resources on. |
| 76 |
type: str |
| 77 |
default: Common |
| 78 |
extends_documentation_fragment: f5networks.f5_modules.f5 |
| 79 |
author: |
| 80 |
- Tim Rupp (@caphrim007) |
| 81 |
- Wojciech Wypior (@wojtek0806) |
| 82 |
''' |
| 83 |
|
| 84 |
EXAMPLES = r''' |
| 85 |
- name: Create policy which is immediately published |
| 86 |
bigip_policy: |
| 87 |
name: Policy-Foo |
| 88 |
state: present |
| 89 |
provider: |
| 90 |
server: lb.mydomain.com |
| 91 |
user: admin |
| 92 |
password: secret |
| 93 |
delegate_to: localhost |
| 94 |
|
| 95 |
- name: Add a rule to the new policy - Immediately published |
| 96 |
bigip_policy_rule: |
| 97 |
policy: Policy-Foo |
| 98 |
name: ABC |
| 99 |
conditions: |
| 100 |
- type: http_uri |
| 101 |
path_starts_with: |
| 102 |
- /ABC |
| 103 |
- foo |
| 104 |
- bar |
| 105 |
path_ends_with: |
| 106 |
- baz |
| 107 |
actions: |
| 108 |
- forward: true |
| 109 |
select: true |
| 110 |
pool: pool-svrs |
| 111 |
provider: |
| 112 |
server: lb.mydomain.com |
| 113 |
user: admin |
| 114 |
password: secret |
| 115 |
delegate_to: localhost |
| 116 |
|
| 117 |
- name: Add multiple rules to the new policy - Added in the order they are specified |
| 118 |
bigip_policy_rule: |
| 119 |
policy: Policy-Foo |
| 120 |
name: "{{ item.name }}" |
| 121 |
conditions: "{{ item.conditions }}" |
| 122 |
actions: "{{ item.actions }}" |
| 123 |
provider: |
| 124 |
server: lb.mydomain.com |
| 125 |
user: admin |
| 126 |
password: secret |
| 127 |
delegate_to: localhost |
| 128 |
loop: |
| 129 |
- name: rule1 |
| 130 |
actions: |
| 131 |
- type: forward |
| 132 |
pool: pool-svrs |
| 133 |
conditions: |
| 134 |
- type: http_uri |
| 135 |
path_starts_with: /euro |
| 136 |
- name: HomePage |
| 137 |
actions: |
| 138 |
- type: forward |
| 139 |
pool: pool-svrs |
| 140 |
conditions: |
| 141 |
- type: http_uri |
| 142 |
path_starts_with: /HomePage/ |
| 143 |
|
| 144 |
- name: Create policy specify default rules - Immediately published |
| 145 |
bigip_policy: |
| 146 |
name: Policy-Bar |
| 147 |
state: present |
| 148 |
rules: |
| 149 |
- rule1 |
| 150 |
- rule2 |
| 151 |
- rule3 |
| 152 |
provider: |
| 153 |
server: lb.mydomain.com |
| 154 |
user: admin |
| 155 |
password: secret |
| 156 |
delegate_to: localhost |
| 157 |
|
| 158 |
- name: Create policy specify default rules - Left in a draft |
| 159 |
bigip_policy: |
| 160 |
name: Policy-Baz |
| 161 |
state: draft |
| 162 |
rules: |
| 163 |
- rule1 |
| 164 |
- rule2 |
| 165 |
- rule3 |
| 166 |
provider: |
| 167 |
server: lb.mydomain.com |
| 168 |
user: admin |
| 169 |
password: secret |
| 170 |
delegate_to: localhost |
| 171 |
''' |
| 172 |
|
| 173 |
RETURN = r''' |
| 174 |
strategy: |
| 175 |
description: The new strategy set on the policy. |
| 176 |
returned: changed and success |
| 177 |
type: int |
| 178 |
sample: first-match |
| 179 |
description: |
| 180 |
description: |
| 181 |
- The new description of the policy. |
| 182 |
- This value is only returned for BIG-IP devices >= 12.1.0. |
| 183 |
returned: changed and success |
| 184 |
type: str |
| 185 |
sample: This is my description |
| 186 |
rules: |
| 187 |
description: List of the rules, and their order, applied to the policy. |
| 188 |
returned: changed and success |
| 189 |
type: list |
| 190 |
sample: ['/Common/rule1', '/Common/rule2'] |
| 191 |
''' |
| 192 |
import re |
| 193 |
import traceback |
| 194 |
from datetime import datetime |
| 195 |
|
| 196 |
try: |
| 197 |
from packaging.version import Version |
| 198 |
except ImportError: |
| 199 |
HAS_PACKAGING = False |
| 200 |
Version = None |
| 201 |
PACKAGING_IMPORT_ERROR = traceback.format_exc() |
| 202 |
else: |
| 203 |
HAS_PACKAGING = True |
| 204 |
PACKAGING_IMPORT_ERROR = None |
| 205 |
|
| 206 |
try: |
| 207 |
from urllib import quote_plus |
| 208 |
except ImportError: |
| 209 |
from urllib.parse import quote_plus |
| 210 |
|
| 211 |
from ansible.module_utils.basic import ( |
| 212 |
AnsibleModule, missing_required_lib, env_fallback |
| 213 |
) |
| 214 |
from ..module_utils.bigip import F5RestClient |
| 215 |
from ..module_utils.common import ( |
| 216 |
F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name |
| 217 |
) |
| 218 |
from ..module_utils.icontrol import tmos_version |
| 219 |
from ..module_utils.teem import send_teem |
| 220 |
|
| 221 |
|
| 222 |
class Parameters(AnsibleF5Parameters): |
| 223 |
def to_return(self): |
| 224 |
result = {} |
| 225 |
for returnable in self.returnables: |
| 226 |
result[returnable] = getattr(self, returnable) |
| 227 |
result = self._filter_params(result) |
| 228 |
return result |
| 229 |
|
| 230 |
@property |
| 231 |
def strategy(self): |
| 232 |
if self._values['strategy'] is None: |
| 233 |
return None |
| 234 |
|
| 235 |
|
| 236 |
elif self._values['strategy'] == 'first': |
| 237 |
return self._get_builtin_strategy('first') |
| 238 |
elif 'first-match' in self._values['strategy']: |
| 239 |
return str(self._values['strategy']) |
| 240 |
|
| 241 |
|
| 242 |
elif self._values['strategy'] == 'all': |
| 243 |
return self._get_builtin_strategy('all') |
| 244 |
elif 'all-match' in self._values['strategy']: |
| 245 |
return str(self._values['strategy']) |
| 246 |
|
| 247 |
else: |
| 248 |
|
| 249 |
if self._values['strategy'] == 'best': |
| 250 |
return self._get_builtin_strategy('best') |
| 251 |
elif 'best-match' in self._values['strategy']: |
| 252 |
return str(self._values['strategy']) |
| 253 |
else: |
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
return self._get_custom_strategy_name() |
| 258 |
|
| 259 |
def _get_builtin_strategy(self, strategy): |
| 260 |
return '/Common/{0}-match'.format(strategy) |
| 261 |
|
| 262 |
def _get_custom_strategy_name(self): |
| 263 |
strategy = self._values['strategy'] |
| 264 |
if re.match(r'(\/[a-zA-Z_0-9.-]+){2}', strategy): |
| 265 |
return strategy |
| 266 |
elif re.match(r'[a-zA-Z_0-9.-]+', strategy): |
| 267 |
return '/{0}/{1}'.format(self.partition, strategy) |
| 268 |
else: |
| 269 |
raise F5ModuleError( |
| 270 |
"The provided strategy name is invalid!" |
| 271 |
) |
| 272 |
|
| 273 |
@property |
| 274 |
def rules(self): |
| 275 |
if self._values['rules'] is None: |
| 276 |
return None |
| 277 |
|
| 278 |
result = [str(x) for x in self._values['rules']] |
| 279 |
return result |
| 280 |
|
| 281 |
|
| 282 |
class SimpleParameters(Parameters): |
| 283 |
api_attributes = [ |
| 284 |
'strategy', |
| 285 |
] |
| 286 |
|
| 287 |
updatables = [ |
| 288 |
'strategy', |
| 289 |
'rules', |
| 290 |
] |
| 291 |
|
| 292 |
returnables = [ |
| 293 |
'strategy', |
| 294 |
'rules', |
| 295 |
] |
| 296 |
|
| 297 |
|
| 298 |
class ComplexParameters(Parameters): |
| 299 |
api_attributes = [ |
| 300 |
'strategy', |
| 301 |
'description', |
| 302 |
] |
| 303 |
|
| 304 |
updatables = [ |
| 305 |
'strategy', |
| 306 |
'description', |
| 307 |
'rules', |
| 308 |
] |
| 309 |
|
| 310 |
returnables = [ |
| 311 |
'strategy', |
| 312 |
'description', |
| 313 |
'rules', |
| 314 |
] |
| 315 |
|
| 316 |
|
| 317 |
class SimpleChanges(SimpleParameters): |
| 318 |
api_attributes = [ |
| 319 |
'strategy' |
| 320 |
] |
| 321 |
|
| 322 |
updatables = [ |
| 323 |
'strategy', 'rules' |
| 324 |
] |
| 325 |
|
| 326 |
returnables = [ |
| 327 |
'strategy', 'rules' |
| 328 |
] |
| 329 |
|
| 330 |
|
| 331 |
class ComplexChanges(ComplexParameters): |
| 332 |
api_attributes = [ |
| 333 |
'strategy', 'description' |
| 334 |
] |
| 335 |
|
| 336 |
updatables = [ |
| 337 |
'strategy', 'description', 'rules' |
| 338 |
] |
| 339 |
|
| 340 |
returnables = [ |
| 341 |
'strategy', 'description', 'rules' |
| 342 |
] |
| 343 |
|
| 344 |
|
| 345 |
class BaseManager(object): |
| 346 |
def __init__(self, *args, **kwargs): |
| 347 |
self.module = kwargs.get('module', None) |
| 348 |
self.client = F5RestClient(**self.module.params) |
| 349 |
self.have = None |
| 350 |
self.want = Parameters(params=self.module.params) |
| 351 |
|
| 352 |
def _announce_deprecations(self): |
| 353 |
warnings = [] |
| 354 |
if self.want: |
| 355 |
warnings += self.want._values.get('__deprecated', []) |
| 356 |
if self.have: |
| 357 |
warnings += self.have._values.get('__deprecated', []) |
| 358 |
for warning in warnings: |
| 359 |
self.module.deprecate( |
| 360 |
msg=warning['msg'], |
| 361 |
version=warning['version'] |
| 362 |
) |
| 363 |
|
| 364 |
def _announce_warnings(self): |
| 365 |
warnings = [] |
| 366 |
if self.want: |
| 367 |
warnings += self.want._values.get('__warning', []) |
| 368 |
if self.have: |
| 369 |
warnings += self.have._values.get('__warning', []) |
| 370 |
for warning in warnings: |
| 371 |
self.module.warn(warning['msg']) |
| 372 |
|
| 373 |
def present(self): |
| 374 |
if self.exists(): |
| 375 |
return self.update() |
| 376 |
else: |
| 377 |
return self.create() |
| 378 |
|
| 379 |
def should_update(self): |
| 380 |
result = self._update_changed_options() |
| 381 |
if result: |
| 382 |
return True |
| 383 |
return False |
| 384 |
|
| 385 |
def _validate_creation_parameters(self): |
| 386 |
if self.want.strategy is None: |
| 387 |
self.want.update(dict(strategy='first')) |
| 388 |
|
| 389 |
def _get_rule_names(self, rules): |
| 390 |
if 'items' in rules: |
| 391 |
rules['items'].sort(key=lambda x: x['ordinal']) |
| 392 |
result = [x['name'] for x in rules['items']] |
| 393 |
return result |
| 394 |
else: |
| 395 |
return [] |
| 396 |
|
| 397 |
def _read_rule_from_device(self, rule_name, draft=False): |
| 398 |
if draft: |
| 399 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 400 |
self.client.provider['server'], |
| 401 |
self.client.provider['server_port'], |
| 402 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 403 |
quote_plus(rule_name) |
| 404 |
) |
| 405 |
else: |
| 406 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 407 |
self.client.provider['server'], |
| 408 |
self.client.provider['server_port'], |
| 409 |
transform_name(self.want.partition, self.want.name), |
| 410 |
self.want.name |
| 411 |
) |
| 412 |
|
| 413 |
resp = self.client.api.get(uri) |
| 414 |
try: |
| 415 |
response = resp.json() |
| 416 |
except ValueError as ex: |
| 417 |
raise F5ModuleError(str(ex)) |
| 418 |
|
| 419 |
if 'code' in response and response['code'] == 400: |
| 420 |
if 'message' in response: |
| 421 |
raise F5ModuleError(response['message']) |
| 422 |
else: |
| 423 |
raise F5ModuleError(resp.content) |
| 424 |
return response['ordinal'] |
| 425 |
|
| 426 |
def _create_rule_on_device(self, rule_name, idx, draft=False): |
| 427 |
params = dict(name=rule_name, ordinal=idx) |
| 428 |
if draft: |
| 429 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/".format( |
| 430 |
self.client.provider['server'], |
| 431 |
self.client.provider['server_port'], |
| 432 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 433 |
) |
| 434 |
else: |
| 435 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/".format( |
| 436 |
self.client.provider['server'], |
| 437 |
self.client.provider['server_port'], |
| 438 |
transform_name(self.want.partition, self.want.name), |
| 439 |
) |
| 440 |
resp = self.client.api.post(uri, json=params) |
| 441 |
try: |
| 442 |
response = resp.json() |
| 443 |
except ValueError as ex: |
| 444 |
raise F5ModuleError(str(ex)) |
| 445 |
|
| 446 |
if 'code' in response and response['code'] in [400, 403, 409]: |
| 447 |
if 'message' in response: |
| 448 |
raise F5ModuleError(response['message']) |
| 449 |
else: |
| 450 |
raise F5ModuleError(resp.content) |
| 451 |
|
| 452 |
def _modify_rule_on_device(self, rule_name, idx, draft=False): |
| 453 |
params = dict(ordinal=idx) |
| 454 |
if draft: |
| 455 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 456 |
self.client.provider['server'], |
| 457 |
self.client.provider['server_port'], |
| 458 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 459 |
quote_plus(rule_name) |
| 460 |
) |
| 461 |
else: |
| 462 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 463 |
self.client.provider['server'], |
| 464 |
self.client.provider['server_port'], |
| 465 |
transform_name(self.want.partition, self.want.name), |
| 466 |
self.want.name |
| 467 |
) |
| 468 |
resp = self.client.api.patch(uri, json=params) |
| 469 |
try: |
| 470 |
response = resp.json() |
| 471 |
except ValueError as ex: |
| 472 |
raise F5ModuleError(str(ex)) |
| 473 |
|
| 474 |
if 'code' in response and response['code'] == [400, 409]: |
| 475 |
if 'message' in response: |
| 476 |
raise F5ModuleError(response['message']) |
| 477 |
else: |
| 478 |
raise F5ModuleError(resp.content) |
| 479 |
|
| 480 |
def _rule_exists_on_device(self, rule_name, draft=False): |
| 481 |
if draft: |
| 482 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 483 |
self.client.provider['server'], |
| 484 |
self.client.provider['server_port'], |
| 485 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 486 |
quote_plus(rule_name) |
| 487 |
) |
| 488 |
else: |
| 489 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 490 |
self.client.provider['server'], |
| 491 |
self.client.provider['server_port'], |
| 492 |
transform_name(self.want.partition, self.want.name), |
| 493 |
self.want.name |
| 494 |
) |
| 495 |
resp = self.client.api.get(uri) |
| 496 |
try: |
| 497 |
response = resp.json() |
| 498 |
except ValueError: |
| 499 |
return False |
| 500 |
if resp.status == 404 or 'code' in response and response['code'] == 404: |
| 501 |
return False |
| 502 |
return True |
| 503 |
|
| 504 |
def _remove_rule_on_device(self, rule_name, draft=False): |
| 505 |
if draft: |
| 506 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 507 |
self.client.provider['server'], |
| 508 |
self.client.provider['server_port'], |
| 509 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 510 |
quote_plus(rule_name) |
| 511 |
) |
| 512 |
else: |
| 513 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format( |
| 514 |
self.client.provider['server'], |
| 515 |
self.client.provider['server_port'], |
| 516 |
transform_name(self.want.partition, self.want.name), |
| 517 |
self.want.name |
| 518 |
) |
| 519 |
response = self.client.api.delete(uri) |
| 520 |
if response.status == 200: |
| 521 |
return True |
| 522 |
raise F5ModuleError(response.content) |
| 523 |
|
| 524 |
def _upsert_policy_rules_on_device(self, draft=False): |
| 525 |
rules = self.changes.rules |
| 526 |
if rules is None: |
| 527 |
rules = [] |
| 528 |
for idx, rule in enumerate(rules): |
| 529 |
if self._rule_exists_on_device(rule, draft): |
| 530 |
ordinal = self._read_rule_from_device(rule, draft) |
| 531 |
if int(ordinal) != idx: |
| 532 |
self._modify_rule_on_device(rule, idx, draft) |
| 533 |
else: |
| 534 |
self._create_rule_on_device(rule, idx, draft) |
| 535 |
self._remove_rule_difference(rules, draft) |
| 536 |
|
| 537 |
def _remove_rule_difference(self, rules, draft=False): |
| 538 |
if not rules or not self.have.rules: |
| 539 |
return |
| 540 |
have_rules = set(self.have.rules) |
| 541 |
want_rules = set(rules) |
| 542 |
removable = have_rules.difference(want_rules) |
| 543 |
for remove in removable: |
| 544 |
self._remove_rule_on_device(remove, draft) |
| 545 |
|
| 546 |
|
| 547 |
class SimpleManager(BaseManager): |
| 548 |
def __init__(self, *args, **kwargs): |
| 549 |
super(SimpleManager, self).__init__(**kwargs) |
| 550 |
self.want = SimpleParameters(params=self.module.params) |
| 551 |
self.have = SimpleParameters() |
| 552 |
self.changes = SimpleChanges() |
| 553 |
|
| 554 |
def _set_changed_options(self): |
| 555 |
changed = {} |
| 556 |
for key in SimpleParameters.returnables: |
| 557 |
if getattr(self.want, key) is not None: |
| 558 |
changed[key] = getattr(self.want, key) |
| 559 |
if changed: |
| 560 |
self.changes = SimpleChanges(params=changed) |
| 561 |
|
| 562 |
def _update_changed_options(self): |
| 563 |
diff = Difference(self.want, self.have) |
| 564 |
updatables = SimpleParameters.updatables |
| 565 |
changed = dict() |
| 566 |
for k in updatables: |
| 567 |
change = diff.compare(k) |
| 568 |
if change is None: |
| 569 |
continue |
| 570 |
else: |
| 571 |
changed[k] = change |
| 572 |
if changed: |
| 573 |
self.changes = SimpleChanges(params=changed) |
| 574 |
return True |
| 575 |
return False |
| 576 |
|
| 577 |
def exec_module(self): |
| 578 |
start = datetime.now().isoformat() |
| 579 |
version = tmos_version(self.client) |
| 580 |
changed = False |
| 581 |
result = dict() |
| 582 |
state = self.want.state |
| 583 |
|
| 584 |
if state == 'draft': |
| 585 |
raise F5ModuleError( |
| 586 |
"The 'draft' status is not available on BIG-IP versions < 12.1.0" |
| 587 |
) |
| 588 |
if state == 'present': |
| 589 |
changed = self.present() |
| 590 |
elif state == 'absent': |
| 591 |
changed = self.absent() |
| 592 |
|
| 593 |
changes = self.changes.to_return() |
| 594 |
result.update(**changes) |
| 595 |
result.update(dict(changed=changed)) |
| 596 |
self._announce_deprecations() |
| 597 |
self._announce_warnings() |
| 598 |
send_teem(start, self.client, self.module, version) |
| 599 |
return result |
| 600 |
|
| 601 |
def create(self): |
| 602 |
self._validate_creation_parameters() |
| 603 |
self._set_changed_options() |
| 604 |
if self.module.check_mode: |
| 605 |
return True |
| 606 |
self.create_on_device() |
| 607 |
return True |
| 608 |
|
| 609 |
def update(self): |
| 610 |
self.have = self.read_current_from_device() |
| 611 |
if not self.should_update(): |
| 612 |
return False |
| 613 |
if self.module.check_mode: |
| 614 |
return True |
| 615 |
self.update_on_device() |
| 616 |
return True |
| 617 |
|
| 618 |
def absent(self): |
| 619 |
changed = False |
| 620 |
if self.exists(): |
| 621 |
changed = self.remove() |
| 622 |
return changed |
| 623 |
|
| 624 |
def remove(self): |
| 625 |
if self.module.check_mode: |
| 626 |
return True |
| 627 |
self.remove_from_device() |
| 628 |
if self.exists(): |
| 629 |
raise F5ModuleError("Failed to delete the policy") |
| 630 |
return True |
| 631 |
|
| 632 |
def exists(self): |
| 633 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 634 |
self.client.provider['server'], |
| 635 |
self.client.provider['server_port'], |
| 636 |
transform_name(self.want.partition, self.want.name) |
| 637 |
) |
| 638 |
resp = self.client.api.get(uri) |
| 639 |
try: |
| 640 |
response = resp.json() |
| 641 |
except ValueError as ex: |
| 642 |
raise F5ModuleError(str(ex)) |
| 643 |
|
| 644 |
if resp.status == 404 or 'code' in response and response['code'] == 404: |
| 645 |
return False |
| 646 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 647 |
return True |
| 648 |
|
| 649 |
errors = [401, 403, 409, 500, 501, 502, 503, 504] |
| 650 |
|
| 651 |
if resp.status in errors or 'code' in response and response['code'] in errors: |
| 652 |
if 'message' in response: |
| 653 |
raise F5ModuleError(response['message']) |
| 654 |
else: |
| 655 |
raise F5ModuleError(resp.content) |
| 656 |
|
| 657 |
def read_current_from_device(self): |
| 658 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 659 |
self.client.provider['server'], |
| 660 |
self.client.provider['server_port'], |
| 661 |
transform_name(self.want.partition, self.want.name), |
| 662 |
) |
| 663 |
query = "?expandSubcollections=true" |
| 664 |
resp = self.client.api.get(uri + query) |
| 665 |
try: |
| 666 |
response = resp.json() |
| 667 |
except ValueError as ex: |
| 668 |
raise F5ModuleError(str(ex)) |
| 669 |
|
| 670 |
if 'code' in response and response['code'] == 400: |
| 671 |
if 'message' in response: |
| 672 |
raise F5ModuleError(response['message']) |
| 673 |
else: |
| 674 |
raise F5ModuleError(resp.content) |
| 675 |
|
| 676 |
rules = self._get_rule_names(response['rulesReference']) |
| 677 |
result = SimpleParameters(params=response) |
| 678 |
result.update(dict(rules=rules)) |
| 679 |
return result |
| 680 |
|
| 681 |
def update_on_device(self): |
| 682 |
params = self.changes.api_params() |
| 683 |
if params: |
| 684 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 685 |
self.client.provider['server'], |
| 686 |
self.client.provider['server_port'], |
| 687 |
transform_name(self.want.partition, self.want.name) |
| 688 |
) |
| 689 |
resp = self.client.api.patch(uri, json=params) |
| 690 |
try: |
| 691 |
response = resp.json() |
| 692 |
except ValueError as ex: |
| 693 |
raise F5ModuleError(str(ex)) |
| 694 |
|
| 695 |
if 'code' in response and response['code'] == 400: |
| 696 |
if 'message' in response: |
| 697 |
raise F5ModuleError(response['message']) |
| 698 |
else: |
| 699 |
raise F5ModuleError(resp.content) |
| 700 |
|
| 701 |
self._upsert_policy_rules_on_device() |
| 702 |
|
| 703 |
def create_on_device(self): |
| 704 |
params = self.want.api_params() |
| 705 |
payload = dict( |
| 706 |
name=self.want.name, |
| 707 |
partition=self.want.partition, |
| 708 |
**params |
| 709 |
) |
| 710 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/".format( |
| 711 |
self.client.provider['server'], |
| 712 |
self.client.provider['server_port'], |
| 713 |
) |
| 714 |
resp = self.client.api.post(uri, json=payload) |
| 715 |
try: |
| 716 |
response = resp.json() |
| 717 |
except ValueError as ex: |
| 718 |
raise F5ModuleError(str(ex)) |
| 719 |
|
| 720 |
if 'code' in response and response['code'] in [400, 403]: |
| 721 |
if 'message' in response: |
| 722 |
raise F5ModuleError(response['message']) |
| 723 |
else: |
| 724 |
raise F5ModuleError(resp.content) |
| 725 |
|
| 726 |
self._upsert_policy_rules_on_device() |
| 727 |
|
| 728 |
return True |
| 729 |
|
| 730 |
def remove_from_device(self): |
| 731 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 732 |
self.client.provider['server'], |
| 733 |
self.client.provider['server_port'], |
| 734 |
transform_name(self.want.partition, self.want.name) |
| 735 |
) |
| 736 |
response = self.client.api.delete(uri) |
| 737 |
if response.status == 200: |
| 738 |
return True |
| 739 |
raise F5ModuleError(response.content) |
| 740 |
|
| 741 |
|
| 742 |
class ComplexManager(BaseManager): |
| 743 |
def __init__(self, *args, **kwargs): |
| 744 |
super(ComplexManager, self).__init__(**kwargs) |
| 745 |
self.want = ComplexParameters(params=self.module.params) |
| 746 |
self.have = ComplexParameters() |
| 747 |
self.changes = ComplexChanges() |
| 748 |
|
| 749 |
def _set_changed_options(self): |
| 750 |
changed = {} |
| 751 |
for key in ComplexParameters.returnables: |
| 752 |
if getattr(self.want, key) is not None: |
| 753 |
changed[key] = getattr(self.want, key) |
| 754 |
if changed: |
| 755 |
self.changes = ComplexChanges(params=changed) |
| 756 |
|
| 757 |
def _update_changed_options(self): |
| 758 |
diff = Difference(self.want, self.have) |
| 759 |
updatables = ComplexParameters.updatables |
| 760 |
changed = dict() |
| 761 |
for k in updatables: |
| 762 |
change = diff.compare(k) |
| 763 |
if change is None: |
| 764 |
continue |
| 765 |
else: |
| 766 |
changed[k] = change |
| 767 |
if changed: |
| 768 |
self.changes = ComplexChanges(params=changed) |
| 769 |
return True |
| 770 |
return False |
| 771 |
|
| 772 |
def exec_module(self): |
| 773 |
start = datetime.now().isoformat() |
| 774 |
version = tmos_version(self.client) |
| 775 |
changed = False |
| 776 |
result = dict() |
| 777 |
state = self.want.state |
| 778 |
|
| 779 |
if state in ["present", "draft"]: |
| 780 |
changed = self.present() |
| 781 |
elif state == "absent": |
| 782 |
changed = self.absent() |
| 783 |
|
| 784 |
changes = self.changes.to_return() |
| 785 |
result.update(**changes) |
| 786 |
result.update(dict(changed=changed)) |
| 787 |
send_teem(start, self.client, self.module, version) |
| 788 |
return result |
| 789 |
|
| 790 |
def should_update(self): |
| 791 |
result = self._update_changed_options() |
| 792 |
drafted = self.draft_status_changed() |
| 793 |
if any(x is True for x in [result, drafted]): |
| 794 |
return True |
| 795 |
return False |
| 796 |
|
| 797 |
def draft_status_changed(self): |
| 798 |
if self.draft_exists() and self.want.state == 'draft': |
| 799 |
drafted = False |
| 800 |
elif not self.draft_exists() and self.want.state == 'present': |
| 801 |
drafted = False |
| 802 |
else: |
| 803 |
drafted = True |
| 804 |
return drafted |
| 805 |
|
| 806 |
def present(self): |
| 807 |
if self.draft_exists() or self.policy_exists(): |
| 808 |
return self.update() |
| 809 |
else: |
| 810 |
return self.create() |
| 811 |
|
| 812 |
def absent(self): |
| 813 |
changed = False |
| 814 |
if self.draft_exists() or self.policy_exists(): |
| 815 |
changed = self.remove() |
| 816 |
return changed |
| 817 |
|
| 818 |
def remove(self): |
| 819 |
if self.module.check_mode: |
| 820 |
return True |
| 821 |
self.remove_from_device() |
| 822 |
if self.draft_exists() or self.policy_exists(): |
| 823 |
raise F5ModuleError("Failed to delete the policy") |
| 824 |
return True |
| 825 |
|
| 826 |
def create(self): |
| 827 |
self._validate_creation_parameters() |
| 828 |
|
| 829 |
self._set_changed_options() |
| 830 |
if self.module.check_mode: |
| 831 |
return True |
| 832 |
|
| 833 |
if not self.draft_exists(): |
| 834 |
self._create_new_policy_draft() |
| 835 |
|
| 836 |
|
| 837 |
|
| 838 |
self.update_on_device() |
| 839 |
|
| 840 |
if self.want.state == 'draft': |
| 841 |
return True |
| 842 |
else: |
| 843 |
return self.publish() |
| 844 |
|
| 845 |
def update(self): |
| 846 |
self.have = self.read_current_from_device() |
| 847 |
if not self.should_update(): |
| 848 |
return False |
| 849 |
if self.module.check_mode: |
| 850 |
return True |
| 851 |
|
| 852 |
if not self.draft_exists(): |
| 853 |
self._create_existing_policy_draft() |
| 854 |
|
| 855 |
if self._update_changed_options(): |
| 856 |
self.update_on_device() |
| 857 |
|
| 858 |
if self.want.state == 'draft': |
| 859 |
return True |
| 860 |
else: |
| 861 |
return self.publish() |
| 862 |
|
| 863 |
def draft_exists(self): |
| 864 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 865 |
self.client.provider['server'], |
| 866 |
self.client.provider['server_port'], |
| 867 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts') |
| 868 |
) |
| 869 |
resp = self.client.api.get(uri) |
| 870 |
try: |
| 871 |
response = resp.json() |
| 872 |
except ValueError: |
| 873 |
return False |
| 874 |
if resp.status == 404 or 'code' in response and response['code'] == 404: |
| 875 |
return False |
| 876 |
return True |
| 877 |
|
| 878 |
def policy_exists(self): |
| 879 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 880 |
self.client.provider['server'], |
| 881 |
self.client.provider['server_port'], |
| 882 |
transform_name(self.want.partition, self.want.name) |
| 883 |
) |
| 884 |
resp = self.client.api.get(uri) |
| 885 |
try: |
| 886 |
response = resp.json() |
| 887 |
except ValueError: |
| 888 |
return False |
| 889 |
if resp.status == 404 or 'code' in response and response['code'] == 404: |
| 890 |
return False |
| 891 |
return True |
| 892 |
|
| 893 |
def _create_existing_policy_draft(self): |
| 894 |
params = dict(createDraft=True) |
| 895 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 896 |
self.client.provider['server'], |
| 897 |
self.client.provider['server_port'], |
| 898 |
transform_name(self.want.partition, self.want.name) |
| 899 |
) |
| 900 |
resp = self.client.api.patch(uri, json=params) |
| 901 |
try: |
| 902 |
response = resp.json() |
| 903 |
except ValueError as ex: |
| 904 |
raise F5ModuleError(str(ex)) |
| 905 |
|
| 906 |
if 'code' in response and response['code'] == 400: |
| 907 |
if 'message' in response: |
| 908 |
raise F5ModuleError(response['message']) |
| 909 |
else: |
| 910 |
raise F5ModuleError(resp.content) |
| 911 |
return True |
| 912 |
|
| 913 |
def _create_new_policy_draft(self): |
| 914 |
params = self.want.api_params() |
| 915 |
payload = dict( |
| 916 |
name=self.want.name, |
| 917 |
partition=self.want.partition, |
| 918 |
subPath='Drafts', |
| 919 |
**params |
| 920 |
) |
| 921 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/".format( |
| 922 |
self.client.provider['server'], |
| 923 |
self.client.provider['server_port'], |
| 924 |
) |
| 925 |
resp = self.client.api.post(uri, json=payload) |
| 926 |
try: |
| 927 |
response = resp.json() |
| 928 |
except ValueError as ex: |
| 929 |
raise F5ModuleError(str(ex)) |
| 930 |
|
| 931 |
if 'code' in response and response['code'] in [400, 403]: |
| 932 |
if 'message' in response: |
| 933 |
raise F5ModuleError(response['message']) |
| 934 |
else: |
| 935 |
raise F5ModuleError(resp.content) |
| 936 |
return True |
| 937 |
|
| 938 |
def update_on_device(self): |
| 939 |
params = self.changes.api_params() |
| 940 |
if params: |
| 941 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 942 |
self.client.provider['server'], |
| 943 |
self.client.provider['server_port'], |
| 944 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 945 |
) |
| 946 |
resp = self.client.api.patch(uri, json=params) |
| 947 |
try: |
| 948 |
response = resp.json() |
| 949 |
except ValueError as ex: |
| 950 |
raise F5ModuleError(str(ex)) |
| 951 |
|
| 952 |
if 'code' in response and response['code'] == 400: |
| 953 |
if 'message' in response: |
| 954 |
raise F5ModuleError(response['message']) |
| 955 |
else: |
| 956 |
raise F5ModuleError(resp.content) |
| 957 |
|
| 958 |
self._upsert_policy_rules_on_device(draft=True) |
| 959 |
|
| 960 |
def read_current_from_device(self): |
| 961 |
if self.draft_exists(): |
| 962 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 963 |
self.client.provider['server'], |
| 964 |
self.client.provider['server_port'], |
| 965 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 966 |
) |
| 967 |
else: |
| 968 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 969 |
self.client.provider['server'], |
| 970 |
self.client.provider['server_port'], |
| 971 |
transform_name(self.want.partition, self.want.name) |
| 972 |
) |
| 973 |
query = "?expandSubcollections=true" |
| 974 |
resp = self.client.api.get(uri + query) |
| 975 |
try: |
| 976 |
response = resp.json() |
| 977 |
except ValueError as ex: |
| 978 |
raise F5ModuleError(str(ex)) |
| 979 |
|
| 980 |
if 'code' in response and response['code'] == 400: |
| 981 |
if 'message' in response: |
| 982 |
raise F5ModuleError(response['message']) |
| 983 |
else: |
| 984 |
raise F5ModuleError(resp.content) |
| 985 |
|
| 986 |
rules = self._get_rule_names(response['rulesReference']) |
| 987 |
result = ComplexParameters(params=response) |
| 988 |
result.update(dict(rules=rules)) |
| 989 |
return result |
| 990 |
|
| 991 |
def publish(self): |
| 992 |
params = dict( |
| 993 |
name=fq_name(self.want.partition, |
| 994 |
self.want.name, |
| 995 |
sub_path='Drafts' |
| 996 |
), |
| 997 |
command="publish" |
| 998 |
|
| 999 |
) |
| 1000 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/".format( |
| 1001 |
self.client.provider['server'], |
| 1002 |
self.client.provider['server_port'], |
| 1003 |
) |
| 1004 |
resp = self.client.api.post(uri, json=params) |
| 1005 |
try: |
| 1006 |
response = resp.json() |
| 1007 |
except ValueError as ex: |
| 1008 |
raise F5ModuleError(str(ex)) |
| 1009 |
|
| 1010 |
if 'code' in response and response['code'] in [400, 403]: |
| 1011 |
if 'message' in response: |
| 1012 |
raise F5ModuleError(response['message']) |
| 1013 |
else: |
| 1014 |
raise F5ModuleError(resp.content) |
| 1015 |
return True |
| 1016 |
|
| 1017 |
def remove_policy_draft_from_device(self): |
| 1018 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 1019 |
self.client.provider['server'], |
| 1020 |
self.client.provider['server_port'], |
| 1021 |
transform_name(self.want.partition, self.want.name, sub_path='Drafts'), |
| 1022 |
) |
| 1023 |
response = self.client.api.delete(uri) |
| 1024 |
|
| 1025 |
if response.status == 200: |
| 1026 |
return True |
| 1027 |
raise F5ModuleError(response.content) |
| 1028 |
|
| 1029 |
def remove_policy_from_device(self): |
| 1030 |
uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format( |
| 1031 |
self.client.provider['server'], |
| 1032 |
self.client.provider['server_port'], |
| 1033 |
transform_name(self.want.partition, self.want.name), |
| 1034 |
) |
| 1035 |
response = self.client.api.delete(uri) |
| 1036 |
|
| 1037 |
if response.status == 200: |
| 1038 |
return True |
| 1039 |
raise F5ModuleError(response.content) |
| 1040 |
|
| 1041 |
def remove_from_device(self): |
| 1042 |
if self.draft_exists(): |
| 1043 |
self.remove_policy_draft_from_device() |
| 1044 |
if self.policy_exists(): |
| 1045 |
self.remove_policy_from_device() |
| 1046 |
return True |
| 1047 |
|
| 1048 |
|
| 1049 |
class Difference(object): |
| 1050 |
def __init__(self, want, have=None): |
| 1051 |
self.want = want |
| 1052 |
self.have = have |
| 1053 |
|
| 1054 |
def compare(self, param): |
| 1055 |
try: |
| 1056 |
result = getattr(self, param) |
| 1057 |
return result |
| 1058 |
except AttributeError: |
| 1059 |
return self.__default(param) |
| 1060 |
|
| 1061 |
def __default(self, param): |
| 1062 |
attr1 = getattr(self.want, param) |
| 1063 |
try: |
| 1064 |
attr2 = getattr(self.have, param) |
| 1065 |
if attr1 != attr2: |
| 1066 |
return attr1 |
| 1067 |
except AttributeError: |
| 1068 |
return attr1 |
| 1069 |
|
| 1070 |
@property |
| 1071 |
def rules(self): |
| 1072 |
if self.want.rules != self.have.rules: |
| 1073 |
return self.want.rules |
| 1074 |
|
| 1075 |
|
| 1076 |
class ModuleManager(object): |
| 1077 |
def __init__(self, *args, **kwargs): |
| 1078 |
self.module = kwargs.get('module', None) |
| 1079 |
self.client = F5RestClient(**self.module.params) |
| 1080 |
self.kwargs = kwargs |
| 1081 |
|
| 1082 |
def exec_module(self): |
| 1083 |
if self.version_is_less_than_12(): |
| 1084 |
manager = self.get_manager('simple') |
| 1085 |
else: |
| 1086 |
manager = self.get_manager('complex') |
| 1087 |
return manager.exec_module() |
| 1088 |
|
| 1089 |
def get_manager(self, type): |
| 1090 |
if type == 'simple': |
| 1091 |
return SimpleManager(**self.kwargs) |
| 1092 |
elif type == 'complex': |
| 1093 |
return ComplexManager(**self.kwargs) |
| 1094 |
|
| 1095 |
def version_is_less_than_12(self): |
| 1096 |
version = tmos_version(self.client) |
| 1097 |
if Version(version) < Version('12.1.0'): |
| 1098 |
return True |
| 1099 |
else: |
| 1100 |
return False |
| 1101 |
|
| 1102 |
|
| 1103 |
class ArgumentSpec(object): |
| 1104 |
def __init__(self): |
| 1105 |
self.supports_check_mode = True |
| 1106 |
argument_spec = dict( |
| 1107 |
name=dict( |
| 1108 |
required=True |
| 1109 |
), |
| 1110 |
description=dict(), |
| 1111 |
rules=dict( |
| 1112 |
type='list', |
| 1113 |
elements='str', |
| 1114 |
), |
| 1115 |
strategy=dict( |
| 1116 |
choices=['first', 'all', 'best'] |
| 1117 |
), |
| 1118 |
state=dict( |
| 1119 |
default='present', |
| 1120 |
choices=['absent', 'present', 'draft'] |
| 1121 |
), |
| 1122 |
partition=dict( |
| 1123 |
default='Common', |
| 1124 |
fallback=(env_fallback, ['F5_PARTITION']) |
| 1125 |
) |
| 1126 |
) |
| 1127 |
self.argument_spec = {} |
| 1128 |
self.argument_spec.update(f5_argument_spec) |
| 1129 |
self.argument_spec.update(argument_spec) |
| 1130 |
|
| 1131 |
|
| 1132 |
def main(): |
| 1133 |
spec = ArgumentSpec() |
| 1134 |
|
| 1135 |
module = AnsibleModule( |
| 1136 |
argument_spec=spec.argument_spec, |
| 1137 |
supports_check_mode=spec.supports_check_mode |
| 1138 |
) |
| 1139 |
|
| 1140 |
if not HAS_PACKAGING: |
| 1141 |
module.fail_json( |
| 1142 |
msg=missing_required_lib('packaging'), |
| 1143 |
exception=PACKAGING_IMPORT_ERROR |
| 1144 |
) |
| 1145 |
|
| 1146 |
try: |
| 1147 |
mm = ModuleManager(module=module) |
| 1148 |
results = mm.exec_module() |
| 1149 |
module.exit_json(**results) |
| 1150 |
except F5ModuleError as ex: |
| 1151 |
module.fail_json(msg=str(ex)) |
| 1152 |
|
| 1153 |
|
| 1154 |
if __name__ == '__main__': |
| 1155 |
main() |