| 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_iapp_template |
| 13 |
short_description: Manages TCL iApp templates on a BIG-IP. |
| 14 |
description: |
| 15 |
- Manages TCL iApp templates on a BIG-IP. This module allows you to |
| 16 |
deploy iApp templates to the BIG-IP and manage their lifecycle. The |
| 17 |
conventional way to use this module is to import new iApps as needed, |
| 18 |
or by extracting the contents of the iApp archive that is provided at |
| 19 |
downloads.f5.com, and then importing all the iApps with this module. |
| 20 |
This module can also update existing iApps provided the source |
| 21 |
of the iApp changed while the name stayed the same. Note that |
| 22 |
this module does not reconfigure any services that may have been |
| 23 |
created using the C(bigip_iapp_service) module. iApps are normally |
| 24 |
not updated in production. Instead, new versions are deployed and then |
| 25 |
existing services are changed to consume that new template. As such, |
| 26 |
the ability to update templates in-place requires using the C(force) option. |
| 27 |
version_added: "1.0.0" |
| 28 |
options: |
| 29 |
force: |
| 30 |
description: |
| 31 |
- Specifies whether or not to force the uploading of an iApp. When |
| 32 |
C(true), the system force updates the iApp even if there are iApp services |
| 33 |
using it. This will not update the running service, use |
| 34 |
C(bigip_iapp_service) to do that. When C(false), the system updates the iApp |
| 35 |
only if there are no iApp services using the template. |
| 36 |
type: bool |
| 37 |
name: |
| 38 |
description: |
| 39 |
- The name of the iApp template you want to delete. This option |
| 40 |
is only available when specifying a C(state) of C(absent) and is |
| 41 |
provided as a way to delete templates that you may no longer have |
| 42 |
the source of. |
| 43 |
type: str |
| 44 |
content: |
| 45 |
description: |
| 46 |
- Sets the contents of an iApp template directly to the specified |
| 47 |
value. This is for simple values, but can be used with lookup |
| 48 |
plugins for anything complex or with formatting. C(content) must |
| 49 |
be provided when creating new templates. |
| 50 |
type: str |
| 51 |
state: |
| 52 |
description: |
| 53 |
- Whether the iApp template should exist or not. |
| 54 |
type: str |
| 55 |
choices: |
| 56 |
- present |
| 57 |
- absent |
| 58 |
default: present |
| 59 |
partition: |
| 60 |
description: |
| 61 |
- Device partition to manage resources on. |
| 62 |
type: str |
| 63 |
default: Common |
| 64 |
extends_documentation_fragment: f5networks.f5_modules.f5 |
| 65 |
author: |
| 66 |
- Tim Rupp (@caphrim007) |
| 67 |
- Wojciech Wypior (@wojtek0806) |
| 68 |
''' |
| 69 |
|
| 70 |
EXAMPLES = r''' |
| 71 |
- name: Add the iApp contained in template iapp.tmpl |
| 72 |
bigip_iapp_template: |
| 73 |
content: "{{ lookup('template', 'iapp.tmpl') }}" |
| 74 |
state: present |
| 75 |
provider: |
| 76 |
user: admin |
| 77 |
password: secret |
| 78 |
server: lb.mydomain.com |
| 79 |
delegate_to: localhost |
| 80 |
|
| 81 |
- name: Update a template in place |
| 82 |
bigip_iapp_template: |
| 83 |
content: "{{ lookup('template', 'iapp-new.tmpl') }}" |
| 84 |
state: present |
| 85 |
provider: |
| 86 |
user: admin |
| 87 |
password: secret |
| 88 |
server: lb.mydomain.com |
| 89 |
delegate_to: localhost |
| 90 |
|
| 91 |
- name: Update a template in place that has existing services created from it. |
| 92 |
bigip_iapp_template: |
| 93 |
content: "{{ lookup('template', 'iapp-new.tmpl') }}" |
| 94 |
force: true |
| 95 |
state: present |
| 96 |
provider: |
| 97 |
user: admin |
| 98 |
password: secret |
| 99 |
server: lb.mydomain.com |
| 100 |
delegate_to: localhost |
| 101 |
''' |
| 102 |
|
| 103 |
RETURN = r''' |
| 104 |
# only common fields returned |
| 105 |
''' |
| 106 |
|
| 107 |
import re |
| 108 |
import uuid |
| 109 |
from datetime import datetime |
| 110 |
|
| 111 |
from ansible.module_utils.basic import AnsibleModule |
| 112 |
from ansible.module_utils.basic import env_fallback |
| 113 |
|
| 114 |
from ..module_utils.bigip import F5RestClient |
| 115 |
from ..module_utils.common import ( |
| 116 |
F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name |
| 117 |
) |
| 118 |
from ..module_utils.icontrol import ( |
| 119 |
upload_file, tmos_version |
| 120 |
) |
| 121 |
from ..module_utils.teem import send_teem |
| 122 |
|
| 123 |
try: |
| 124 |
from StringIO import StringIO |
| 125 |
except ImportError: |
| 126 |
from io import StringIO |
| 127 |
|
| 128 |
|
| 129 |
class Parameters(AnsibleF5Parameters): |
| 130 |
api_attributes = [] |
| 131 |
|
| 132 |
returnables = [] |
| 133 |
|
| 134 |
@property |
| 135 |
def name(self): |
| 136 |
if self._values['name']: |
| 137 |
return self._values['name'] |
| 138 |
if self._values['content']: |
| 139 |
name = self._get_template_name() |
| 140 |
return name |
| 141 |
return None |
| 142 |
|
| 143 |
@property |
| 144 |
def content(self): |
| 145 |
if self._values['content'] is None: |
| 146 |
return None |
| 147 |
result = self._squash_template_name_prefix() |
| 148 |
result = self._replace_template_name(result) |
| 149 |
return result |
| 150 |
|
| 151 |
@property |
| 152 |
def checksum(self): |
| 153 |
return self._values['tmplChecksum'] |
| 154 |
|
| 155 |
def _squash_template_name_prefix(self): |
| 156 |
"""Removes the template name prefix |
| 157 |
|
| 158 |
This method removes that partition from the name |
| 159 |
in the iApp so that comparisons can be done properly and entries |
| 160 |
can be created properly when using REST. |
| 161 |
|
| 162 |
:return string |
| 163 |
""" |
| 164 |
pattern = r'sys\s+application\s+template\s+/Common/' |
| 165 |
replace = 'sys application template ' |
| 166 |
return re.sub(pattern, replace, self._values['content']) |
| 167 |
|
| 168 |
def _replace_template_name(self, template): |
| 169 |
"""Replaces template name at runtime |
| 170 |
|
| 171 |
To allow us to do the switch-a-roo with temporary templates and |
| 172 |
checksum comparisons, we need to take the template provided to us |
| 173 |
and change its name to a temporary value so that BIG-IP will create |
| 174 |
a clone for us. |
| 175 |
|
| 176 |
:return string |
| 177 |
""" |
| 178 |
pattern = r'sys\s+application\s+template\s+[^ ]+' |
| 179 |
|
| 180 |
if self._values['name']: |
| 181 |
name = self._values['name'] |
| 182 |
else: |
| 183 |
name = self._get_template_name() |
| 184 |
|
| 185 |
replace = 'sys application template {0}'.format(fq_name(self.partition, name)) |
| 186 |
return re.sub(pattern, replace, template) |
| 187 |
|
| 188 |
def _get_template_name(self): |
| 189 |
pattern = r'sys\s+application\s+template\s+(?P<path>\/[^\{}"\'*?|#]+\/)?(?P<name>[^\{}"\'*?|#]+)' |
| 190 |
matches = re.search(pattern, self._values['content']) |
| 191 |
try: |
| 192 |
result = matches.group('name').strip() |
| 193 |
except IndexError: |
| 194 |
result = None |
| 195 |
if result: |
| 196 |
return result |
| 197 |
raise F5ModuleError( |
| 198 |
"No template name was found in the template" |
| 199 |
) |
| 200 |
|
| 201 |
|
| 202 |
class ApiParameters(Parameters): |
| 203 |
pass |
| 204 |
|
| 205 |
|
| 206 |
class ModuleParameters(Parameters): |
| 207 |
pass |
| 208 |
|
| 209 |
|
| 210 |
class Changes(Parameters): |
| 211 |
def to_return(self): |
| 212 |
result = {} |
| 213 |
try: |
| 214 |
for returnable in self.returnables: |
| 215 |
result[returnable] = getattr(self, returnable) |
| 216 |
result = self._filter_params(result) |
| 217 |
except Exception: |
| 218 |
raise |
| 219 |
return result |
| 220 |
|
| 221 |
|
| 222 |
class UsableChanges(Changes): |
| 223 |
pass |
| 224 |
|
| 225 |
|
| 226 |
class ReportableChanges(Changes): |
| 227 |
pass |
| 228 |
|
| 229 |
|
| 230 |
class ModuleManager(object): |
| 231 |
def __init__(self, *args, **kwargs): |
| 232 |
self.module = kwargs.get('module', None) |
| 233 |
self.client = F5RestClient(**self.module.params) |
| 234 |
self.want = ModuleParameters(params=self.module.params) |
| 235 |
self.have = ApiParameters() |
| 236 |
self.changes = UsableChanges() |
| 237 |
|
| 238 |
def _announce_deprecations(self, result): |
| 239 |
warnings = result.pop('__warnings', []) |
| 240 |
for warning in warnings: |
| 241 |
self.client.module.deprecate( |
| 242 |
msg=warning['msg'], |
| 243 |
version=warning['version'] |
| 244 |
) |
| 245 |
|
| 246 |
def exec_module(self): |
| 247 |
start = datetime.now().isoformat() |
| 248 |
version = tmos_version(self.client) |
| 249 |
changed = False |
| 250 |
result = dict() |
| 251 |
state = self.want.state |
| 252 |
|
| 253 |
if state == "present": |
| 254 |
changed = self.present() |
| 255 |
elif state == "absent": |
| 256 |
changed = self.absent() |
| 257 |
|
| 258 |
reportable = ReportableChanges(params=self.changes.to_return()) |
| 259 |
changes = reportable.to_return() |
| 260 |
result.update(**changes) |
| 261 |
result.update(dict(changed=changed)) |
| 262 |
self._announce_deprecations(result) |
| 263 |
send_teem(start, self.client, self.module, version) |
| 264 |
return result |
| 265 |
|
| 266 |
def present(self): |
| 267 |
if self.exists(): |
| 268 |
return self.update() |
| 269 |
else: |
| 270 |
return self.create() |
| 271 |
|
| 272 |
def absent(self): |
| 273 |
changed = False |
| 274 |
if self.exists(): |
| 275 |
changed = self.remove() |
| 276 |
return changed |
| 277 |
|
| 278 |
def create(self): |
| 279 |
if self.module.check_mode: |
| 280 |
return True |
| 281 |
self.create_on_device() |
| 282 |
if self.exists(): |
| 283 |
return True |
| 284 |
else: |
| 285 |
raise F5ModuleError("Failed to create the iApp template") |
| 286 |
|
| 287 |
def remove(self): |
| 288 |
if self.module.check_mode: |
| 289 |
return True |
| 290 |
self.remove_from_device() |
| 291 |
if self.exists(): |
| 292 |
raise F5ModuleError("Failed to delete the iApp template") |
| 293 |
return True |
| 294 |
|
| 295 |
def update(self): |
| 296 |
self.have = self.read_current_from_device() |
| 297 |
|
| 298 |
if not self.templates_differ(): |
| 299 |
return False |
| 300 |
|
| 301 |
if not self.want.force and self.template_in_use(): |
| 302 |
return False |
| 303 |
|
| 304 |
if self.module.check_mode: |
| 305 |
return True |
| 306 |
|
| 307 |
self._remove_iapp_checksum() |
| 308 |
|
| 309 |
self.create_on_device() |
| 310 |
self._generate_template_checksum_on_device() |
| 311 |
return True |
| 312 |
|
| 313 |
def exists(self): |
| 314 |
uri = "https://{0}:{1}/mgmt/tm/sys/application/template/{2}".format( |
| 315 |
self.client.provider['server'], |
| 316 |
self.client.provider['server_port'], |
| 317 |
transform_name(self.want.partition, self.want.name) |
| 318 |
) |
| 319 |
resp = self.client.api.get(uri) |
| 320 |
try: |
| 321 |
response = resp.json() |
| 322 |
except ValueError as ex: |
| 323 |
raise F5ModuleError(str(ex)) |
| 324 |
|
| 325 |
if resp.status == 404 or 'code' in response and response['code'] == 404: |
| 326 |
return False |
| 327 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 328 |
return True |
| 329 |
|
| 330 |
errors = [401, 403, 409, 500, 501, 502, 503, 504] |
| 331 |
|
| 332 |
if resp.status in errors or 'code' in response and response['code'] in errors: |
| 333 |
if 'message' in response: |
| 334 |
raise F5ModuleError(response['message']) |
| 335 |
else: |
| 336 |
raise F5ModuleError(resp.content) |
| 337 |
|
| 338 |
def template_in_use(self): |
| 339 |
uri = "https://{0}:{1}/mgmt/tm/sys/application/service/".format( |
| 340 |
self.client.provider['server'], |
| 341 |
self.client.provider['server_port'], |
| 342 |
) |
| 343 |
|
| 344 |
name = fq_name(self.want.partition, self.want.name) |
| 345 |
resp = self.client.api.get(uri) |
| 346 |
|
| 347 |
try: |
| 348 |
response = resp.json() |
| 349 |
except ValueError: |
| 350 |
return False |
| 351 |
|
| 352 |
if resp.status == 404 or 'code' in response and response['code'] == 404: |
| 353 |
return False |
| 354 |
|
| 355 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 356 |
for item in response['items']: |
| 357 |
if item['template'] == name: |
| 358 |
return True |
| 359 |
return False |
| 360 |
raise F5ModuleError(resp.content) |
| 361 |
|
| 362 |
def read_current_from_device(self): |
| 363 |
self._generate_template_checksum_on_device() |
| 364 |
uri = "https://{0}:{1}/mgmt/tm/sys/application/template/{2}".format( |
| 365 |
self.client.provider['server'], |
| 366 |
self.client.provider['server_port'], |
| 367 |
transform_name(self.want.partition, self.want.name) |
| 368 |
) |
| 369 |
|
| 370 |
resp = self.client.api.get(uri) |
| 371 |
|
| 372 |
try: |
| 373 |
response = resp.json() |
| 374 |
except ValueError as ex: |
| 375 |
raise F5ModuleError(str(ex)) |
| 376 |
|
| 377 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 378 |
return ApiParameters(params=response) |
| 379 |
raise F5ModuleError(resp.content) |
| 380 |
|
| 381 |
def _remove_iapp_checksum(self): |
| 382 |
"""Removes the iApp tmplChecksum |
| 383 |
|
| 384 |
This is required for updating in place or else the load command will |
| 385 |
fail with a "AppTemplate ... content does not match the checksum" |
| 386 |
error. |
| 387 |
|
| 388 |
:return: |
| 389 |
""" |
| 390 |
uri = "https://{0}:{1}/mgmt/tm/sys/application/template/{2}".format( |
| 391 |
self.client.provider['server'], |
| 392 |
self.client.provider['server_port'], |
| 393 |
transform_name(self.want.partition, self.want.name) |
| 394 |
) |
| 395 |
params = dict(tmplChecksum=None) |
| 396 |
|
| 397 |
resp = self.client.api.patch(uri, json=params) |
| 398 |
|
| 399 |
try: |
| 400 |
response = resp.json() |
| 401 |
except ValueError as ex: |
| 402 |
raise F5ModuleError(str(ex)) |
| 403 |
|
| 404 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 405 |
return True |
| 406 |
raise F5ModuleError(resp.content) |
| 407 |
|
| 408 |
def templates_differ(self): |
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
backup = self.want.name |
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
self.want.update({ |
| 425 |
'name': 'ansible-{0}'.format(str(uuid.uuid4())) |
| 426 |
}) |
| 427 |
|
| 428 |
|
| 429 |
temp = self._get_temporary_template() |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
self.want.update({ |
| 434 |
'name': backup |
| 435 |
}) |
| 436 |
if temp.checksum != self.have.checksum: |
| 437 |
return True |
| 438 |
return False |
| 439 |
|
| 440 |
def _get_temporary_template(self): |
| 441 |
self.create_on_device() |
| 442 |
temp = self.read_current_from_device() |
| 443 |
self.remove_from_device() |
| 444 |
return temp |
| 445 |
|
| 446 |
def _generate_template_checksum_on_device(self): |
| 447 |
command = 'tmsh generate sys application template {0} checksum'.format( |
| 448 |
self.want.name |
| 449 |
) |
| 450 |
params = dict( |
| 451 |
command="run", |
| 452 |
utilCmdArgs='-c "{0}"'.format(command) |
| 453 |
) |
| 454 |
uri = "https://{0}:{1}/mgmt/tm/util/bash".format( |
| 455 |
self.client.provider['server'], |
| 456 |
self.client.provider['server_port'] |
| 457 |
) |
| 458 |
|
| 459 |
resp = self.client.api.post(uri, json=params) |
| 460 |
|
| 461 |
try: |
| 462 |
response = resp.json() |
| 463 |
except ValueError as ex: |
| 464 |
raise F5ModuleError(str(ex)) |
| 465 |
|
| 466 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 467 |
return True |
| 468 |
raise F5ModuleError(resp.content) |
| 469 |
|
| 470 |
def upload_file_to_device(self, content, name): |
| 471 |
url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format( |
| 472 |
self.client.provider['server'], |
| 473 |
self.client.provider['server_port'] |
| 474 |
) |
| 475 |
try: |
| 476 |
upload_file(self.client, url, content, name) |
| 477 |
except F5ModuleError: |
| 478 |
raise F5ModuleError( |
| 479 |
"Failed to upload the file." |
| 480 |
) |
| 481 |
|
| 482 |
def create_on_device(self): |
| 483 |
remote_path = "/var/config/rest/downloads/{0}".format(self.want.name) |
| 484 |
load_command = 'tmsh load sys application template {0}'.format(remote_path) |
| 485 |
|
| 486 |
template = StringIO(self.want.content) |
| 487 |
self.upload_file_to_device(template, self.want.name) |
| 488 |
|
| 489 |
uri = "https://{0}:{1}/mgmt/tm/util/bash".format( |
| 490 |
self.client.provider['server'], |
| 491 |
self.client.provider['server_port'] |
| 492 |
) |
| 493 |
params = dict( |
| 494 |
command="run", |
| 495 |
utilCmdArgs='-c "{0}"'.format(load_command) |
| 496 |
) |
| 497 |
|
| 498 |
resp = self.client.api.post(uri, json=params) |
| 499 |
|
| 500 |
try: |
| 501 |
response = resp.json() |
| 502 |
except ValueError as ex: |
| 503 |
raise F5ModuleError(str(ex)) |
| 504 |
|
| 505 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 506 |
if 'commandResult' in response: |
| 507 |
if 'Syntax Error' in response['commandResult']: |
| 508 |
raise F5ModuleError(response['commandResult']) |
| 509 |
if 'ERROR' in response['commandResult']: |
| 510 |
raise F5ModuleError(response['commandResult']) |
| 511 |
return True |
| 512 |
raise F5ModuleError(resp.content) |
| 513 |
|
| 514 |
def remove_from_device(self): |
| 515 |
uri = "https://{0}:{1}/mgmt/tm/sys/application/template/{2}".format( |
| 516 |
self.client.provider['server'], |
| 517 |
self.client.provider['server_port'], |
| 518 |
transform_name(self.want.partition, self.want.name) |
| 519 |
) |
| 520 |
response = self.client.api.delete(uri) |
| 521 |
if response.status == 200: |
| 522 |
return True |
| 523 |
raise F5ModuleError(response.content) |
| 524 |
|
| 525 |
|
| 526 |
class ArgumentSpec(object): |
| 527 |
def __init__(self): |
| 528 |
self.supports_check_mode = True |
| 529 |
argument_spec = dict( |
| 530 |
name=dict(), |
| 531 |
state=dict( |
| 532 |
default='present', |
| 533 |
choices=['present', 'absent'] |
| 534 |
), |
| 535 |
force=dict( |
| 536 |
type='bool' |
| 537 |
), |
| 538 |
content=dict(), |
| 539 |
partition=dict( |
| 540 |
default='Common', |
| 541 |
fallback=(env_fallback, ['F5_PARTITION']) |
| 542 |
) |
| 543 |
) |
| 544 |
self.argument_spec = {} |
| 545 |
self.argument_spec.update(f5_argument_spec) |
| 546 |
self.argument_spec.update(argument_spec) |
| 547 |
|
| 548 |
|
| 549 |
def main(): |
| 550 |
spec = ArgumentSpec() |
| 551 |
|
| 552 |
module = AnsibleModule( |
| 553 |
argument_spec=spec.argument_spec, |
| 554 |
supports_check_mode=spec.supports_check_mode |
| 555 |
) |
| 556 |
|
| 557 |
try: |
| 558 |
mm = ModuleManager(module=module) |
| 559 |
results = mm.exec_module() |
| 560 |
module.exit_json(**results) |
| 561 |
except F5ModuleError as ex: |
| 562 |
module.fail_json(msg=str(ex)) |
| 563 |
|
| 564 |
|
| 565 |
if __name__ == '__main__': |
| 566 |
main() |