| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# (c) 2015, Matt Martz <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
--- |
| 11 |
module: expect |
| 12 |
version_added: '2.0' |
| 13 |
short_description: Executes a command and responds to prompts |
| 14 |
description: |
| 15 |
- The M(ansible.builtin.expect) module executes a command and responds to prompts. |
| 16 |
- The given command will be executed on all selected nodes. It will not be |
| 17 |
processed through the shell, so variables like C($HOME) and operations |
| 18 |
like C("<"), C(">"), C("|"), and C("&") will not work. |
| 19 |
options: |
| 20 |
command: |
| 21 |
description: |
| 22 |
- The command module takes command to run. |
| 23 |
required: true |
| 24 |
type: str |
| 25 |
creates: |
| 26 |
type: path |
| 27 |
description: |
| 28 |
- A filename, when it already exists, this step will B(not) be run. |
| 29 |
removes: |
| 30 |
type: path |
| 31 |
description: |
| 32 |
- A filename, when it does not exist, this step will B(not) be run. |
| 33 |
chdir: |
| 34 |
type: path |
| 35 |
description: |
| 36 |
- Change into this directory before running the command. |
| 37 |
responses: |
| 38 |
type: dict |
| 39 |
description: |
| 40 |
- Mapping of prompt regular expressions and corresponding answer(s). |
| 41 |
- Each key in O(responses) is a Python regex U(https://docs.python.org/3/library/re.html#regular-expression-syntax). |
| 42 |
- The value of each key is a string or list of strings. |
| 43 |
If the value is a string and the prompt is encountered multiple times, the answer will be repeated. |
| 44 |
Provide the value as a list to give different answers for successive matches. |
| 45 |
required: true |
| 46 |
timeout: |
| 47 |
type: raw |
| 48 |
description: |
| 49 |
- Amount of time in seconds to wait for the expected strings. Use |
| 50 |
V(null) to disable timeout. |
| 51 |
default: 30 |
| 52 |
echo: |
| 53 |
description: |
| 54 |
- Whether or not to echo out your response strings. |
| 55 |
default: false |
| 56 |
type: bool |
| 57 |
requirements: |
| 58 |
- python >= 2.6 |
| 59 |
- pexpect >= 3.3 |
| 60 |
extends_documentation_fragment: action_common_attributes |
| 61 |
attributes: |
| 62 |
check_mode: |
| 63 |
support: none |
| 64 |
diff_mode: |
| 65 |
support: none |
| 66 |
platform: |
| 67 |
support: full |
| 68 |
platforms: posix |
| 69 |
notes: |
| 70 |
- If you want to run a command through the shell (say you are using C(<), |
| 71 |
C(>), C(|), and so on), you must specify a shell in the command such as |
| 72 |
C(/bin/bash -c "/path/to/something | grep else"). |
| 73 |
- Case insensitive searches are indicated with a prefix of C((?i)). |
| 74 |
- The C(pexpect) library used by this module operates with a search window |
| 75 |
of 2000 bytes, and does not use a multiline regex match. To perform a |
| 76 |
start of line bound match, use a pattern like C((?m)^pattern). |
| 77 |
- The M(ansible.builtin.expect) module is designed for simple scenarios. |
| 78 |
For more complex needs, consider the use of expect code with the M(ansible.builtin.shell) |
| 79 |
or M(ansible.builtin.script) modules. (An example is part of the M(ansible.builtin.shell) module documentation). |
| 80 |
- If the command returns non UTF-8 data, it must be encoded to avoid issues. One option is to pipe |
| 81 |
the output through C(base64). |
| 82 |
seealso: |
| 83 |
- module: ansible.builtin.script |
| 84 |
- module: ansible.builtin.shell |
| 85 |
author: "Matt Martz (@sivel)" |
| 86 |
""" |
| 87 |
|
| 88 |
EXAMPLES = r""" |
| 89 |
- name: Case insensitive password string match |
| 90 |
ansible.builtin.expect: |
| 91 |
command: passwd username |
| 92 |
responses: |
| 93 |
(?i)password: "MySekretPa$$word" |
| 94 |
# you don't want to show passwords in your logs |
| 95 |
no_log: true |
| 96 |
|
| 97 |
- name: Match multiple regular expressions and demonstrate individual and repeated responses |
| 98 |
ansible.builtin.expect: |
| 99 |
command: /path/to/custom/command |
| 100 |
responses: |
| 101 |
Question: |
| 102 |
# give a unique response for each of the 3 hypothetical prompts matched |
| 103 |
- response1 |
| 104 |
- response2 |
| 105 |
- response3 |
| 106 |
# give the same response for every matching prompt |
| 107 |
"^Match another prompt$": "response" |
| 108 |
|
| 109 |
- name: Multiple questions with responses |
| 110 |
ansible.builtin.expect: |
| 111 |
command: /path/to/custom/command |
| 112 |
responses: |
| 113 |
"Please provide your name": |
| 114 |
- "Anna" |
| 115 |
"Database user": |
| 116 |
- "{{ db_username }}" |
| 117 |
"Database password": |
| 118 |
- "{{ db_password }}" |
| 119 |
""" |
| 120 |
|
| 121 |
import datetime |
| 122 |
import os |
| 123 |
|
| 124 |
PEXPECT_IMP_ERR = None |
| 125 |
try: |
| 126 |
import pexpect |
| 127 |
HAS_PEXPECT = True |
| 128 |
except ImportError as ex: |
| 129 |
PEXPECT_IMP_ERR = ex |
| 130 |
HAS_PEXPECT = False |
| 131 |
|
| 132 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 133 |
from ansible.module_utils.common.text.converters import to_bytes, to_native |
| 134 |
from ansible.module_utils.common.validation import check_type_int |
| 135 |
|
| 136 |
|
| 137 |
def response_closure(module, question, responses): |
| 138 |
resp_gen = (b'%s\n' % to_bytes(r).rstrip(b'\n') for r in responses) |
| 139 |
|
| 140 |
def wrapped(info): |
| 141 |
try: |
| 142 |
return next(resp_gen) |
| 143 |
except StopIteration: |
| 144 |
module.fail_json(msg="No remaining responses for '%s', " |
| 145 |
"output was '%s'" % |
| 146 |
(question, |
| 147 |
info['child_result_list'][-1])) |
| 148 |
|
| 149 |
return wrapped |
| 150 |
|
| 151 |
|
| 152 |
def main(): |
| 153 |
module = AnsibleModule( |
| 154 |
argument_spec=dict( |
| 155 |
command=dict(required=True), |
| 156 |
chdir=dict(type='path'), |
| 157 |
creates=dict(type='path'), |
| 158 |
removes=dict(type='path'), |
| 159 |
responses=dict(type='dict', required=True), |
| 160 |
timeout=dict(type='raw', default=30), |
| 161 |
echo=dict(type='bool', default=False), |
| 162 |
) |
| 163 |
) |
| 164 |
|
| 165 |
if not HAS_PEXPECT: |
| 166 |
module.fail_json(msg=missing_required_lib("pexpect"), exception=PEXPECT_IMP_ERR) |
| 167 |
|
| 168 |
chdir = module.params['chdir'] |
| 169 |
args = module.params['command'] |
| 170 |
creates = module.params['creates'] |
| 171 |
removes = module.params['removes'] |
| 172 |
responses = module.params['responses'] |
| 173 |
timeout = module.params['timeout'] |
| 174 |
if timeout is not None: |
| 175 |
try: |
| 176 |
timeout = check_type_int(timeout) |
| 177 |
except TypeError as te: |
| 178 |
module.fail_json(msg=f"argument 'timeout' is of type {type(timeout)} and we were unable to convert to int: {te}") |
| 179 |
echo = module.params['echo'] |
| 180 |
|
| 181 |
events = dict() |
| 182 |
for key, value in responses.items(): |
| 183 |
if isinstance(value, list): |
| 184 |
response = response_closure(module, key, value) |
| 185 |
else: |
| 186 |
response = b'%s\n' % to_bytes(value).rstrip(b'\n') |
| 187 |
|
| 188 |
events[to_bytes(key)] = response |
| 189 |
|
| 190 |
if args.strip() == '': |
| 191 |
module.fail_json(rc=256, msg="no command given") |
| 192 |
|
| 193 |
if chdir: |
| 194 |
chdir = os.path.abspath(chdir) |
| 195 |
os.chdir(chdir) |
| 196 |
|
| 197 |
if creates: |
| 198 |
# do not run the command if the line contains creates=filename |
| 199 |
# and the filename already exists. This allows idempotence |
| 200 |
# of command executions. |
| 201 |
if os.path.exists(creates): |
| 202 |
module.exit_json( |
| 203 |
cmd=args, |
| 204 |
stdout="skipped, since %s exists" % creates, |
| 205 |
changed=False, |
| 206 |
rc=0 |
| 207 |
) |
| 208 |
|
| 209 |
if removes: |
| 210 |
# do not run the command if the line contains removes=filename |
| 211 |
# and the filename does not exist. This allows idempotence |
| 212 |
# of command executions. |
| 213 |
if not os.path.exists(removes): |
| 214 |
module.exit_json( |
| 215 |
cmd=args, |
| 216 |
stdout="skipped, since %s does not exist" % removes, |
| 217 |
changed=False, |
| 218 |
rc=0 |
| 219 |
) |
| 220 |
|
| 221 |
start_date = datetime.datetime.now() |
| 222 |
|
| 223 |
try: |
| 224 |
try: |
| 225 |
# Prefer pexpect.run from pexpect>=4 |
| 226 |
b_out, rc = pexpect.run(args, timeout=timeout, withexitstatus=True, |
| 227 |
events=events, cwd=chdir, echo=echo, |
| 228 |
encoding=None) |
| 229 |
except TypeError: |
| 230 |
# Use pexpect._run in pexpect>=3.3,<4 |
| 231 |
# pexpect.run doesn't support `echo` |
| 232 |
# pexpect.runu doesn't support encoding=None |
| 233 |
b_out, rc = pexpect._run(args, timeout=timeout, withexitstatus=True, |
| 234 |
events=events, extra_args=None, logfile=None, |
| 235 |
cwd=chdir, env=None, _spawn=pexpect.spawn, |
| 236 |
echo=echo) |
| 237 |
|
| 238 |
except (TypeError, AttributeError) as e: |
| 239 |
# This should catch all insufficient versions of pexpect |
| 240 |
# We deem them insufficient for their lack of ability to specify |
| 241 |
# to not echo responses via the run/runu functions, which would |
| 242 |
# potentially leak sensitive information |
| 243 |
module.fail_json(msg='Insufficient version of pexpect installed ' |
| 244 |
'(%s), this module requires pexpect>=3.3. ' |
| 245 |
'Error was %s' % (pexpect.__version__, to_native(e))) |
| 246 |
except pexpect.ExceptionPexpect as e: |
| 247 |
module.fail_json(msg='%s' % to_native(e)) |
| 248 |
|
| 249 |
end_date = datetime.datetime.now() |
| 250 |
delta = end_date - start_date |
| 251 |
|
| 252 |
result = dict( |
| 253 |
cmd=args, |
| 254 |
stdout=to_native(b_out).rstrip('\r\n'), |
| 255 |
rc=rc, |
| 256 |
start=str(start_date), |
| 257 |
end=str(end_date), |
| 258 |
delta=str(delta), |
| 259 |
changed=True, |
| 260 |
) |
| 261 |
|
| 262 |
if rc is None: |
| 263 |
module.fail_json(msg='command exceeded timeout', **result) |
| 264 |
elif rc != 0: |
| 265 |
module.fail_json(msg='non-zero return code', **result) |
| 266 |
|
| 267 |
module.exit_json(**result) |
| 268 |
|
| 269 |
|
| 270 |
if __name__ == '__main__': |
| 271 |
main() |