| 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_command |
| 13 |
short_description: Run TMSH and BASH commands on F5 devices |
| 14 |
description: |
| 15 |
- Sends a TMSH or BASH command to a BIG-IP node and returns the results |
| 16 |
read from the device. This module includes an argument that will cause |
| 17 |
the module to wait for a specific condition before returning or timing |
| 18 |
out if the condition is not met. |
| 19 |
- This module is B(not) idempotent, nor will it ever be. It is intended as |
| 20 |
a stop-gap measure to satisfy automation requirements until such a time as |
| 21 |
a real module has been developed to configure in the way you need. |
| 22 |
- If you are using this module, we recommend also filing an issue |
| 23 |
to have a B(real) module created for your needs. |
| 24 |
version_added: "1.0.0" |
| 25 |
options: |
| 26 |
commands: |
| 27 |
description: |
| 28 |
- The commands to send to the remote BIG-IP device over the |
| 29 |
configured provider. The resulting output from the command |
| 30 |
is returned. If the I(wait_for) argument is provided, the |
| 31 |
module is not returned until the condition is satisfied or |
| 32 |
the number of retries has expired. |
| 33 |
- Only C(tmsh) commands are supported. If you are piping or adding additional |
| 34 |
logic that is outside of C(tmsh) (such as grep'ing, awk'ing or other shell |
| 35 |
related logic that are not C(tmsh)), this behavior is not supported. |
| 36 |
required: True |
| 37 |
type: raw |
| 38 |
wait_for: |
| 39 |
description: |
| 40 |
- Specifies what to evaluate from the output of the command |
| 41 |
and what conditionals to apply. This argument will cause |
| 42 |
the task to wait for a particular conditional to be true |
| 43 |
before moving forward. If the conditional is not true |
| 44 |
by the configured retries, the task fails. See the examples. |
| 45 |
type: list |
| 46 |
elements: str |
| 47 |
aliases: ['waitfor'] |
| 48 |
match: |
| 49 |
description: |
| 50 |
- The I(match) argument is used in conjunction with the |
| 51 |
I(wait_for) argument to specify the match policy. Valid |
| 52 |
values are C(all) or C(any). If the value is set to C(all), |
| 53 |
then all conditionals in the I(wait_for) must be satisfied. If |
| 54 |
the value is set to C(any) then only one of the values must be |
| 55 |
satisfied. |
| 56 |
type: str |
| 57 |
choices: |
| 58 |
- any |
| 59 |
- all |
| 60 |
default: all |
| 61 |
retries: |
| 62 |
description: |
| 63 |
- Specifies the number of retries a command should be tried |
| 64 |
before it is considered failed. The command is run on the |
| 65 |
target device every retry and evaluated against the I(wait_for) |
| 66 |
conditionals. |
| 67 |
type: int |
| 68 |
default: 10 |
| 69 |
interval: |
| 70 |
description: |
| 71 |
- Configures the interval in seconds to wait between retries |
| 72 |
of the command. If the command does not pass the specified |
| 73 |
conditional, the interval indicates how to long to wait before |
| 74 |
trying the command again. |
| 75 |
type: int |
| 76 |
default: 1 |
| 77 |
warn: |
| 78 |
description: |
| 79 |
- Whether the module should raise warnings related to command idempotency |
| 80 |
or not. |
| 81 |
- Note that the F5 Ansible developers specifically leave this on to make you |
| 82 |
aware that your usage of this module may be better served by official F5 |
| 83 |
Ansible modules. This module should always be used as a last resort. |
| 84 |
default: true |
| 85 |
type: bool |
| 86 |
chdir: |
| 87 |
description: |
| 88 |
- Change into this directory before running the command. |
| 89 |
type: str |
| 90 |
notes: |
| 91 |
- When running this module in an HA environment via SSH connection and using a role other than C(admin) |
| 92 |
or C(root), you may see a C(Change Pending) status, even if you did not make any changes. |
| 93 |
This is being tracked with ID429869. |
| 94 |
- When using the bigip_command module with the REST API, there are a number of places regex is used |
| 95 |
internally to escape characters such as quotation marks. If your TMSH command contains regex characters itself, |
| 96 |
such as datagroup wildcards C(*), then a large amount of escape characters may be needed. |
| 97 |
- When issuing a long running command, you must provide a large enough value for the timeout option in the |
| 98 |
provider block. |
| 99 |
extends_documentation_fragment: f5networks.f5_modules.f5_rest_cli |
| 100 |
author: |
| 101 |
- Tim Rupp (@caphrim007) |
| 102 |
- Wojciech Wypior (@wojtek0806) |
| 103 |
''' |
| 104 |
|
| 105 |
EXAMPLES = r''' |
| 106 |
- name: run show version on remote devices |
| 107 |
bigip_command: |
| 108 |
commands: show sys version |
| 109 |
provider: |
| 110 |
server: lb.mydomain.com |
| 111 |
password: secret |
| 112 |
user: admin |
| 113 |
delegate_to: localhost |
| 114 |
|
| 115 |
- name: sleep for 200 seconds |
| 116 |
bigip_command: |
| 117 |
commands: 'run /util bash -c "sleep 200"' |
| 118 |
provider: |
| 119 |
server: lb.mydomain.com |
| 120 |
password: secret |
| 121 |
user: admin |
| 122 |
timeout: 210 |
| 123 |
delegate_to: localhost |
| 124 |
|
| 125 |
- name: run show version and check to see if output contains BIG-IP |
| 126 |
bigip_command: |
| 127 |
commands: show sys version |
| 128 |
wait_for: result[0] contains BIG-IP |
| 129 |
provider: |
| 130 |
server: lb.mydomain.com |
| 131 |
password: secret |
| 132 |
user: admin |
| 133 |
register: result |
| 134 |
delegate_to: localhost |
| 135 |
|
| 136 |
- name: run multiple commands on remote nodes |
| 137 |
bigip_command: |
| 138 |
commands: |
| 139 |
- show sys version |
| 140 |
- list ltm virtual |
| 141 |
provider: |
| 142 |
server: lb.mydomain.com |
| 143 |
password: secret |
| 144 |
user: admin |
| 145 |
delegate_to: localhost |
| 146 |
|
| 147 |
- name: run multiple commands and evaluate the output |
| 148 |
bigip_command: |
| 149 |
commands: |
| 150 |
- show sys version |
| 151 |
- list ltm virtual |
| 152 |
wait_for: |
| 153 |
- result[0] contains BIG-IP |
| 154 |
- result[1] contains my-vs |
| 155 |
provider: |
| 156 |
server: lb.mydomain.com |
| 157 |
password: secret |
| 158 |
user: admin |
| 159 |
register: result |
| 160 |
delegate_to: localhost |
| 161 |
|
| 162 |
- name: tmsh prefixes will automatically be handled |
| 163 |
bigip_command: |
| 164 |
commands: |
| 165 |
- show sys version |
| 166 |
- tmsh list ltm virtual |
| 167 |
provider: |
| 168 |
server: lb.mydomain.com |
| 169 |
password: secret |
| 170 |
user: admin |
| 171 |
delegate_to: localhost |
| 172 |
|
| 173 |
- name: Delete all LTM nodes in Partition1, assuming no dependencies exist |
| 174 |
bigip_command: |
| 175 |
commands: |
| 176 |
- delete ltm node all |
| 177 |
chdir: Partition1 |
| 178 |
provider: |
| 179 |
server: lb.mydomain.com |
| 180 |
password: secret |
| 181 |
user: admin |
| 182 |
delegate_to: localhost |
| 183 |
|
| 184 |
- name: Command that contains wildcard character to be passed to tmsh |
| 185 |
bigip_command: |
| 186 |
commands: |
| 187 |
- modify ltm data-group internal dg_string records add { "my test\\\\\\\*string" { data "value" }} |
| 188 |
provider: |
| 189 |
server: lb.mydomain.com |
| 190 |
password: secret |
| 191 |
user: admin |
| 192 |
delegate_to: localhost |
| 193 |
''' |
| 194 |
|
| 195 |
RETURN = r''' |
| 196 |
stdout: |
| 197 |
description: The set of responses from the commands. |
| 198 |
returned: always |
| 199 |
type: list |
| 200 |
sample: ['...', '...'] |
| 201 |
stdout_lines: |
| 202 |
description: The value of stdout split into a list. |
| 203 |
returned: always |
| 204 |
type: list |
| 205 |
sample: [['...', '...'], ['...'], ['...']] |
| 206 |
failed_conditions: |
| 207 |
description: The list of conditionals that have failed. |
| 208 |
returned: failed |
| 209 |
type: list |
| 210 |
sample: ['...', '...'] |
| 211 |
warn: |
| 212 |
description: Whether or not to raise warnings about modification commands. |
| 213 |
returned: changed |
| 214 |
type: bool |
| 215 |
sample: true |
| 216 |
''' |
| 217 |
|
| 218 |
import copy |
| 219 |
import re |
| 220 |
import shlex |
| 221 |
import time |
| 222 |
from datetime import datetime |
| 223 |
|
| 224 |
from ansible.module_utils.basic import AnsibleModule |
| 225 |
from ansible.module_utils.six import string_types |
| 226 |
|
| 227 |
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.parsing import Conditional |
| 228 |
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( |
| 229 |
ComplexList, to_list |
| 230 |
) |
| 231 |
|
| 232 |
from collections import deque |
| 233 |
|
| 234 |
from ..module_utils.bigip import F5RestClient |
| 235 |
from ..module_utils.common import ( |
| 236 |
F5ModuleError, AnsibleF5Parameters, f5_argument_spec, is_cli |
| 237 |
) |
| 238 |
from ..module_utils.icontrol import tmos_version |
| 239 |
from ..module_utils.teem import send_teem |
| 240 |
|
| 241 |
try: |
| 242 |
from ..module_utils.common import run_commands |
| 243 |
HAS_CLI_TRANSPORT = True |
| 244 |
except ImportError: |
| 245 |
HAS_CLI_TRANSPORT = False |
| 246 |
|
| 247 |
|
| 248 |
class NoChangeReporter(object): |
| 249 |
stdout_re = [ |
| 250 |
|
| 251 |
re.compile(r"The requested.*already exists"), |
| 252 |
|
| 253 |
|
| 254 |
re.compile(r"Data Input Error: shared.*already exists"), |
| 255 |
] |
| 256 |
|
| 257 |
def find_no_change(self, responses): |
| 258 |
"""Searches the response for something that looks like a change |
| 259 |
|
| 260 |
This method borrows heavily from Ansible's ``_find_prompt`` method |
| 261 |
defined in the ``lib/ansible/plugins/connection/network_cli.py::Connection`` |
| 262 |
class. |
| 263 |
|
| 264 |
Arguments: |
| 265 |
response (string): The output from the command. |
| 266 |
|
| 267 |
Returns: |
| 268 |
bool: True when change is detected. False otherwise. |
| 269 |
""" |
| 270 |
for response in responses: |
| 271 |
for regex in self.stdout_re: |
| 272 |
if regex.search(response): |
| 273 |
return True |
| 274 |
return False |
| 275 |
|
| 276 |
|
| 277 |
class Parameters(AnsibleF5Parameters): |
| 278 |
returnables = ['stdout', 'stdout_lines', 'warnings', 'executed_commands'] |
| 279 |
|
| 280 |
def to_return(self): |
| 281 |
result = {} |
| 282 |
try: |
| 283 |
for returnable in self.returnables: |
| 284 |
result[returnable] = getattr(self, returnable) |
| 285 |
result = self._filter_params(result) |
| 286 |
return result |
| 287 |
except Exception: |
| 288 |
return result |
| 289 |
|
| 290 |
@property |
| 291 |
def raw_commands(self): |
| 292 |
if self._values['commands'] is None: |
| 293 |
return [] |
| 294 |
if isinstance(self._values['commands'], string_types): |
| 295 |
result = [self._values['commands']] |
| 296 |
else: |
| 297 |
result = self._values['commands'] |
| 298 |
return result |
| 299 |
|
| 300 |
def cmd_has_pipe(self, cmd): |
| 301 |
lex = shlex.shlex(cmd, posix=True) |
| 302 |
lex.whitespace = '|' |
| 303 |
lex.whitespace_split = True |
| 304 |
return len(list(lex)) > 1 |
| 305 |
|
| 306 |
def convert_commands(self, commands): |
| 307 |
result = [] |
| 308 |
for command in commands: |
| 309 |
tmp = dict( |
| 310 |
command='', |
| 311 |
pipeline='' |
| 312 |
) |
| 313 |
|
| 314 |
command = command.replace("'", "\\'") |
| 315 |
pipeline = command.split('|', 1) if self.cmd_has_pipe(command) else [command] |
| 316 |
tmp['command'] = pipeline[0] |
| 317 |
try: |
| 318 |
tmp['pipeline'] = pipeline[1] |
| 319 |
except IndexError: |
| 320 |
pass |
| 321 |
result.append(tmp) |
| 322 |
return result |
| 323 |
|
| 324 |
def convert_commands_cli(self, commands): |
| 325 |
result = [] |
| 326 |
for command in commands: |
| 327 |
tmp = dict( |
| 328 |
command='', |
| 329 |
pipeline='' |
| 330 |
) |
| 331 |
|
| 332 |
pipeline = command.split('|', 1) if self.cmd_has_pipe(command) else [command] |
| 333 |
tmp['command'] = pipeline[0] |
| 334 |
try: |
| 335 |
tmp['pipeline'] = pipeline[1] |
| 336 |
except IndexError: |
| 337 |
pass |
| 338 |
result.append(tmp) |
| 339 |
return result |
| 340 |
|
| 341 |
def merge_command_dict(self, command): |
| 342 |
if command['pipeline'] != '': |
| 343 |
escape_patterns = r'([$"])' |
| 344 |
command['pipeline'] = re.sub(escape_patterns, r'\\\1', command['pipeline']) |
| 345 |
command['command'] = '{0} | {1}'.format(command['command'], command['pipeline']).strip() |
| 346 |
|
| 347 |
def merge_command_dict_cli(self, command): |
| 348 |
if command['pipeline'] != '': |
| 349 |
command['command'] = '{0} | {1}'.format(command['command'], command['pipeline']).strip() |
| 350 |
|
| 351 |
@property |
| 352 |
def rest_commands(self): |
| 353 |
|
| 354 |
commands = self.normalized_commands |
| 355 |
commands = self.convert_commands(commands) |
| 356 |
if self.chdir: |
| 357 |
|
| 358 |
for command in commands: |
| 359 |
self.addon_chdir(command) |
| 360 |
|
| 361 |
for command in commands: |
| 362 |
self.addon_tmsh(command) |
| 363 |
for command in commands: |
| 364 |
self.merge_command_dict(command) |
| 365 |
result = [x['command'] for x in commands] |
| 366 |
return result |
| 367 |
|
| 368 |
@property |
| 369 |
def cli_commands(self): |
| 370 |
|
| 371 |
commands = self.normalized_commands |
| 372 |
commands = self.convert_commands_cli(commands) |
| 373 |
if self.chdir: |
| 374 |
|
| 375 |
for command in commands: |
| 376 |
self.addon_chdir(command) |
| 377 |
if not self.is_tmsh: |
| 378 |
|
| 379 |
for command in commands: |
| 380 |
self.addon_tmsh_cli(command) |
| 381 |
for command in commands: |
| 382 |
self.merge_command_dict_cli(command) |
| 383 |
result = [x['command'] for x in commands] |
| 384 |
return result |
| 385 |
|
| 386 |
@property |
| 387 |
def normalized_commands(self): |
| 388 |
if self._values['normalized_commands'] is None: |
| 389 |
return None |
| 390 |
return deque(self._values['normalized_commands']) |
| 391 |
|
| 392 |
@property |
| 393 |
def chdir(self): |
| 394 |
if self._values['chdir'] is None: |
| 395 |
return None |
| 396 |
if self._values['chdir'].startswith('/'): |
| 397 |
return self._values['chdir'] |
| 398 |
return '/{0}'.format(self._values['chdir']) |
| 399 |
|
| 400 |
@property |
| 401 |
def user_commands(self): |
| 402 |
commands = self.raw_commands |
| 403 |
return map(self._ensure_tmsh_prefix, commands) |
| 404 |
|
| 405 |
@property |
| 406 |
def wait_for(self): |
| 407 |
return self._values['wait_for'] or list() |
| 408 |
|
| 409 |
def addon_tmsh(self, command): |
| 410 |
escape_patterns = r'([$"])' |
| 411 |
if command['command'].count('"') % 2 != 0: |
| 412 |
raise Exception('Double quotes are unbalanced') |
| 413 |
command['command'] = re.sub(escape_patterns, r'\\\\\\\1', command['command']) |
| 414 |
command['command'] = 'tmsh -c \\\"{0}\\\"'.format(command['command']) |
| 415 |
|
| 416 |
def addon_tmsh_cli(self, command): |
| 417 |
if command['command'].count('"') % 2 != 0: |
| 418 |
raise Exception('Double quotes are unbalanced') |
| 419 |
command['command'] = 'tmsh -c "{0}"'.format(command['command']) |
| 420 |
|
| 421 |
def addon_chdir(self, command): |
| 422 |
command['command'] = "cd {0}; {1}".format(self.chdir, command['command']) |
| 423 |
|
| 424 |
|
| 425 |
class BaseManager(object): |
| 426 |
def __init__(self, *args, **kwargs): |
| 427 |
self.module = kwargs.get('module', None) |
| 428 |
self.client = F5RestClient(**self.module.params) |
| 429 |
self.want = Parameters(params=self.module.params) |
| 430 |
self.want.update({'module': self.module}) |
| 431 |
self.changes = Parameters(module=self.module) |
| 432 |
self.valid_configs = [ |
| 433 |
'list', 'show', 'modify cli preference pager disabled' |
| 434 |
] |
| 435 |
self.changed_command_prefixes = ('modify', 'create', 'delete') |
| 436 |
self.warnings = list() |
| 437 |
|
| 438 |
def _to_lines(self, stdout): |
| 439 |
lines = list() |
| 440 |
for item in stdout: |
| 441 |
if isinstance(item, string_types): |
| 442 |
item = item.split('\n') |
| 443 |
lines.append(item) |
| 444 |
return lines |
| 445 |
|
| 446 |
def _announce_warnings(self, result): |
| 447 |
warnings = result.pop('warnings', []) |
| 448 |
for warning in warnings: |
| 449 |
self.module.warn(warning) |
| 450 |
|
| 451 |
def notify_non_idempotent_commands(self, commands): |
| 452 |
for index, item in enumerate(commands): |
| 453 |
if any(item.startswith(x) for x in self.valid_configs): |
| 454 |
return |
| 455 |
else: |
| 456 |
self.warnings.append( |
| 457 |
'Using "write" commands is not idempotent. You should use ' |
| 458 |
'a module that is specifically made for that. If such a ' |
| 459 |
'module does not exist, then please file a bug. The command ' |
| 460 |
'in question is "{0}..."'.format(item[0:40]) |
| 461 |
) |
| 462 |
|
| 463 |
@staticmethod |
| 464 |
def normalize_commands(raw_commands): |
| 465 |
if not raw_commands: |
| 466 |
return None |
| 467 |
result = [] |
| 468 |
for command in raw_commands: |
| 469 |
command = command.strip() |
| 470 |
if command[0:5] == 'tmsh ': |
| 471 |
command = command[4:].strip() |
| 472 |
result.append(command) |
| 473 |
return result |
| 474 |
|
| 475 |
def parse_commands(self): |
| 476 |
results = [] |
| 477 |
commands = self._transform_to_complex_commands(self.commands) |
| 478 |
|
| 479 |
for index, item in enumerate(commands): |
| 480 |
|
| 481 |
|
| 482 |
output = item.pop('output', None) |
| 483 |
|
| 484 |
if output == 'one-line' and 'one-line' not in item['command']: |
| 485 |
item['command'] += ' one-line' |
| 486 |
elif output == 'text' and 'one-line' in item['command']: |
| 487 |
item['command'] = item['command'].replace('one-line', '') |
| 488 |
|
| 489 |
results.append(item) |
| 490 |
return results |
| 491 |
|
| 492 |
def execute(self): |
| 493 |
if self.want.normalized_commands: |
| 494 |
result = self.want.normalized_commands |
| 495 |
else: |
| 496 |
result = self.normalize_commands(self.want.raw_commands) |
| 497 |
self.want.update({'normalized_commands': result}) |
| 498 |
if not result: |
| 499 |
return False |
| 500 |
self.notify_non_idempotent_commands(self.want.normalized_commands) |
| 501 |
|
| 502 |
commands = self.parse_commands() |
| 503 |
retries = self.want.retries |
| 504 |
conditionals = [Conditional(c) for c in self.want.wait_for] |
| 505 |
|
| 506 |
if self.module.check_mode: |
| 507 |
return |
| 508 |
|
| 509 |
while retries > 0: |
| 510 |
responses = self._execute(commands) |
| 511 |
self._check_known_errors(responses) |
| 512 |
for item in list(conditionals): |
| 513 |
if item(responses): |
| 514 |
if self.want.match == 'any': |
| 515 |
conditionals = list() |
| 516 |
break |
| 517 |
conditionals.remove(item) |
| 518 |
if not conditionals: |
| 519 |
break |
| 520 |
|
| 521 |
time.sleep(self.want.interval) |
| 522 |
retries -= 1 |
| 523 |
else: |
| 524 |
failed_conditions = [item.raw for item in conditionals] |
| 525 |
errmsg = 'The following wait_for conditional statements have not been satisfied.' |
| 526 |
raise F5ModuleError(errmsg, failed_conditions) |
| 527 |
stdout_lines = self._to_lines(responses) |
| 528 |
changes = { |
| 529 |
'stdout': responses, |
| 530 |
'stdout_lines': stdout_lines, |
| 531 |
'executed_commands': self.commands |
| 532 |
} |
| 533 |
if self.want.warn: |
| 534 |
changes['warnings'] = self.warnings |
| 535 |
self.changes = Parameters(params=changes, module=self.module) |
| 536 |
return self.determine_change(responses) |
| 537 |
|
| 538 |
def determine_change(self, responses): |
| 539 |
changer = NoChangeReporter() |
| 540 |
if changer.find_no_change(responses): |
| 541 |
return False |
| 542 |
if any(x for x in self.want.normalized_commands if x.startswith(self.changed_command_prefixes)): |
| 543 |
return True |
| 544 |
return False |
| 545 |
|
| 546 |
def _check_known_errors(self, responses): |
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
for resp in responses: |
| 551 |
if 'usage: tmsh' in resp: |
| 552 |
raise F5ModuleError( |
| 553 |
"tmsh command printed its 'help' message instead of running your command. " |
| 554 |
"This usually indicates unbalanced quotes." |
| 555 |
) |
| 556 |
|
| 557 |
def _transform_to_complex_commands(self, commands): |
| 558 |
spec = dict( |
| 559 |
command=dict(key=True), |
| 560 |
output=dict( |
| 561 |
default='text', |
| 562 |
choices=['text', 'one-line'] |
| 563 |
), |
| 564 |
) |
| 565 |
transform = ComplexList(spec, self.module) |
| 566 |
result = transform(commands) |
| 567 |
return result |
| 568 |
|
| 569 |
|
| 570 |
class V1Manager(BaseManager): |
| 571 |
"""Supports CLI (SSH) communication with the remote device |
| 572 |
|
| 573 |
""" |
| 574 |
def _execute(self, commands): |
| 575 |
if self.want.is_tmsh: |
| 576 |
command = dict( |
| 577 |
command="modify cli preference pager disabled" |
| 578 |
) |
| 579 |
else: |
| 580 |
command = dict( |
| 581 |
command="tmsh modify cli preference pager disabled" |
| 582 |
) |
| 583 |
self.execute_on_device(command) |
| 584 |
return self.execute_on_device(commands) |
| 585 |
|
| 586 |
@property |
| 587 |
def commands(self): |
| 588 |
return self.want.cli_commands |
| 589 |
|
| 590 |
def is_tmsh(self): |
| 591 |
try: |
| 592 |
self.execute_on_device('tmsh -v') |
| 593 |
except Exception as ex: |
| 594 |
if 'Syntax Error:' in str(ex): |
| 595 |
return True |
| 596 |
raise |
| 597 |
return False |
| 598 |
|
| 599 |
def exec_module(self): |
| 600 |
result = dict() |
| 601 |
|
| 602 |
changed = self.execute() |
| 603 |
|
| 604 |
result.update(**self.changes.to_return()) |
| 605 |
result.update(dict(changed=changed)) |
| 606 |
self._announce_warnings(result) |
| 607 |
return result |
| 608 |
|
| 609 |
def execute(self): |
| 610 |
self.want.update({'is_tmsh': self.is_tmsh()}) |
| 611 |
return super(V1Manager, self).execute() |
| 612 |
|
| 613 |
def execute_on_device(self, commands): |
| 614 |
result = run_commands(self.module, commands) |
| 615 |
return result |
| 616 |
|
| 617 |
|
| 618 |
class V2Manager(BaseManager): |
| 619 |
"""Supports REST communication with the remote device |
| 620 |
|
| 621 |
""" |
| 622 |
def _execute(self, commands): |
| 623 |
return self.execute_on_device(commands) |
| 624 |
|
| 625 |
@property |
| 626 |
def commands(self): |
| 627 |
return self.want.rest_commands |
| 628 |
|
| 629 |
def exec_module(self): |
| 630 |
start = datetime.now().isoformat() |
| 631 |
version = tmos_version(self.client) |
| 632 |
result = dict() |
| 633 |
|
| 634 |
changed = self.execute() |
| 635 |
|
| 636 |
result.update(**self.changes.to_return()) |
| 637 |
result.update(dict(changed=changed)) |
| 638 |
self._announce_warnings(result) |
| 639 |
send_teem(start, self.client, self.module, version) |
| 640 |
return result |
| 641 |
|
| 642 |
def execute_on_device(self, commands): |
| 643 |
responses = [] |
| 644 |
uri = "https://{0}:{1}/mgmt/tm/util/bash".format( |
| 645 |
self.client.provider['server'], |
| 646 |
self.client.provider['server_port'], |
| 647 |
) |
| 648 |
for item in to_list(commands): |
| 649 |
try: |
| 650 |
args = dict( |
| 651 |
command='run', |
| 652 |
utilCmdArgs='-c "{0}"'.format(item['command']) |
| 653 |
) |
| 654 |
resp = self.client.api.post(uri, json=args) |
| 655 |
response = resp.json() |
| 656 |
if 'commandResult' in response: |
| 657 |
output = u'{0}'.format(response['commandResult']) |
| 658 |
responses.append(output.strip()) |
| 659 |
except ValueError as ex: |
| 660 |
raise F5ModuleError(str(ex)) |
| 661 |
|
| 662 |
if 'code' in response and response['code'] == 400: |
| 663 |
if 'message' in response: |
| 664 |
raise F5ModuleError(response['message']) |
| 665 |
else: |
| 666 |
raise F5ModuleError(resp.content) |
| 667 |
return responses |
| 668 |
|
| 669 |
|
| 670 |
class ModuleManager(object): |
| 671 |
def __init__(self, *args, **kwargs): |
| 672 |
self.kwargs = kwargs |
| 673 |
self.module = kwargs.get('module', None) |
| 674 |
|
| 675 |
def exec_module(self): |
| 676 |
if is_cli(self.module) and HAS_CLI_TRANSPORT: |
| 677 |
manager = self.get_manager('v1') |
| 678 |
else: |
| 679 |
manager = self.get_manager('v2') |
| 680 |
result = manager.exec_module() |
| 681 |
return result |
| 682 |
|
| 683 |
def get_manager(self, type): |
| 684 |
if type == 'v1': |
| 685 |
return V1Manager(**self.kwargs) |
| 686 |
elif type == 'v2': |
| 687 |
return V2Manager(**self.kwargs) |
| 688 |
|
| 689 |
|
| 690 |
class ArgumentSpec(object): |
| 691 |
def __init__(self): |
| 692 |
self.supports_check_mode = True |
| 693 |
argument_spec = dict( |
| 694 |
commands=dict( |
| 695 |
type='raw', |
| 696 |
required=True |
| 697 |
), |
| 698 |
wait_for=dict( |
| 699 |
type='list', |
| 700 |
elements='str', |
| 701 |
aliases=['waitfor'] |
| 702 |
), |
| 703 |
match=dict( |
| 704 |
default='all', |
| 705 |
choices=['any', 'all'] |
| 706 |
), |
| 707 |
retries=dict( |
| 708 |
default=10, |
| 709 |
type='int' |
| 710 |
), |
| 711 |
interval=dict( |
| 712 |
default=1, |
| 713 |
type='int' |
| 714 |
), |
| 715 |
warn=dict( |
| 716 |
type='bool', |
| 717 |
default='yes' |
| 718 |
), |
| 719 |
chdir=dict() |
| 720 |
) |
| 721 |
|
| 722 |
provider_update = dict( |
| 723 |
transport=dict( |
| 724 |
type='str', |
| 725 |
default='rest', |
| 726 |
choices=['cli', 'rest'] |
| 727 |
), |
| 728 |
ssh_keyfile=dict( |
| 729 |
type='path' |
| 730 |
), |
| 731 |
|
| 732 |
) |
| 733 |
new_spec = copy.deepcopy(f5_argument_spec) |
| 734 |
self.argument_spec = {} |
| 735 |
self.argument_spec.update(new_spec) |
| 736 |
self.argument_spec['provider']['options'].update(provider_update) |
| 737 |
self.argument_spec.update(argument_spec) |
| 738 |
|
| 739 |
|
| 740 |
def main(): |
| 741 |
spec = ArgumentSpec() |
| 742 |
|
| 743 |
module = AnsibleModule( |
| 744 |
argument_spec=spec.argument_spec, |
| 745 |
supports_check_mode=spec.supports_check_mode |
| 746 |
) |
| 747 |
|
| 748 |
try: |
| 749 |
mm = ModuleManager(module=module) |
| 750 |
results = mm.exec_module() |
| 751 |
module.exit_json(**results) |
| 752 |
except F5ModuleError as ex: |
| 753 |
module.fail_json(msg=str(ex)) |
| 754 |
|
| 755 |
|
| 756 |
if __name__ == '__main__': |
| 757 |
main() |