| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2012, Michael DeHaan <[email protected]>, and others |
| 4 |
# Copyright: (c) 2016, Toshio Kuratomi <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
--- |
| 12 |
module: command |
| 13 |
short_description: Execute commands on targets |
| 14 |
version_added: historical |
| 15 |
description: |
| 16 |
- The M(ansible.builtin.command) module takes the command name followed by a list of space-delimited arguments. |
| 17 |
- The given command will be executed on all selected nodes. |
| 18 |
- The command(s) will not be processed through the shell, so operations like C("*"), C("<"), C(">"), C("|"), C(";") and C("&") will not work. |
| 19 |
Also, environment variables are resolved via Python, not shell, see O(expand_argument_vars) and are left unchanged if not matched. |
| 20 |
Use the M(ansible.builtin.shell) module if you need these features. |
| 21 |
- To create C(command) tasks that are easier to read than the ones using space-delimited arguments, |
| 22 |
pass parameters using the C(args) L(task keyword,https://docs.ansible.com/ansible/latest/reference_appendices/playbooks_keywords.html#task) |
| 23 |
or use O(cmd) parameter. |
| 24 |
- Either a free form command or O(cmd) parameter is required, see the examples. |
| 25 |
- For Windows targets, use the M(ansible.windows.win_command) module instead. |
| 26 |
extends_documentation_fragment: |
| 27 |
- action_common_attributes |
| 28 |
- action_common_attributes.raw |
| 29 |
attributes: |
| 30 |
check_mode: |
| 31 |
details: while the command itself is arbitrary and cannot be subject to the check mode semantics it adds O(creates)/O(removes) options as a workaround |
| 32 |
support: partial |
| 33 |
diff_mode: |
| 34 |
support: none |
| 35 |
platform: |
| 36 |
support: full |
| 37 |
platforms: posix |
| 38 |
raw: |
| 39 |
support: full |
| 40 |
options: |
| 41 |
expand_argument_vars: |
| 42 |
description: |
| 43 |
- Expands the arguments that are variables, for example C($HOME) will be expanded before being passed to the command to run. |
| 44 |
- If a variable is not matched, it is left unchanged, unlike shell substitution which would remove it. |
| 45 |
- Set to V(false) to disable expansion and treat the value as a literal argument. |
| 46 |
type: bool |
| 47 |
default: true |
| 48 |
version_added: "2.16" |
| 49 |
free_form: |
| 50 |
description: |
| 51 |
- The command module takes a free form string as a command to run. |
| 52 |
- There is no actual parameter named C(free_form). |
| 53 |
cmd: |
| 54 |
type: str |
| 55 |
description: |
| 56 |
- The command to run. |
| 57 |
argv: |
| 58 |
type: list |
| 59 |
elements: str |
| 60 |
description: |
| 61 |
- Passes the command as a list rather than a string. |
| 62 |
- Use O(argv) to avoid quoting values that would otherwise be interpreted incorrectly (for example "user name"). |
| 63 |
- Only the string (free form) or the list (argv) form can be provided, not both. One or the other must be provided. |
| 64 |
version_added: "2.6" |
| 65 |
creates: |
| 66 |
type: path |
| 67 |
description: |
| 68 |
- A filename or (since 2.0) glob pattern. If a matching file already exists, this step B(will not) be run. |
| 69 |
- This is checked before O(removes) is checked. |
| 70 |
removes: |
| 71 |
type: path |
| 72 |
description: |
| 73 |
- A filename or (since 2.0) glob pattern. If a matching file exists, this step B(will) be run. |
| 74 |
- This is checked after O(creates) is checked. |
| 75 |
version_added: "0.8" |
| 76 |
chdir: |
| 77 |
type: path |
| 78 |
description: |
| 79 |
- Change into this directory before running the command. |
| 80 |
version_added: "0.6" |
| 81 |
stdin: |
| 82 |
description: |
| 83 |
- Set the stdin of the command directly to the specified value. |
| 84 |
type: str |
| 85 |
version_added: "2.4" |
| 86 |
stdin_add_newline: |
| 87 |
type: bool |
| 88 |
default: yes |
| 89 |
description: |
| 90 |
- If set to V(true), append a newline to stdin data. |
| 91 |
version_added: "2.8" |
| 92 |
strip_empty_ends: |
| 93 |
description: |
| 94 |
- Strip empty lines from the end of stdout/stderr in result. |
| 95 |
version_added: "2.8" |
| 96 |
type: bool |
| 97 |
default: yes |
| 98 |
notes: |
| 99 |
- If you want to run a command through the shell (say you are using C(<), C(>), C(|), and so on), |
| 100 |
you actually want the M(ansible.builtin.shell) module instead. |
| 101 |
Parsing shell metacharacters can lead to unexpected commands being executed if quoting is not done correctly so it is more secure to |
| 102 |
use the M(ansible.builtin.command) module when possible. |
| 103 |
- O(creates), O(removes), and O(chdir) can be specified after the command. |
| 104 |
For instance, if you only want to run a command if a certain file does not exist, use this. |
| 105 |
- Check mode is supported when passing O(creates) or O(removes). If running in check mode and either of these are specified, the module will |
| 106 |
check for the existence of the file and report the correct changed status. If these are not supplied, the task will return RV(ignore:changed=False). |
| 107 |
- The O(ignore:executable) parameter is removed since version 2.4. If you have a need for this parameter, use the M(ansible.builtin.shell) module instead. |
| 108 |
- For Windows targets, use the M(ansible.windows.win_command) module instead. |
| 109 |
- For rebooting systems, use the M(ansible.builtin.reboot) or M(ansible.windows.win_reboot) module. |
| 110 |
- If the command returns non UTF-8 data, it must be encoded to avoid issues. This may necessitate using M(ansible.builtin.shell) so the output |
| 111 |
can be piped through C(base64). |
| 112 |
seealso: |
| 113 |
- module: ansible.builtin.raw |
| 114 |
- module: ansible.builtin.script |
| 115 |
- module: ansible.builtin.shell |
| 116 |
- module: ansible.windows.win_command |
| 117 |
author: |
| 118 |
- Ansible Core Team |
| 119 |
- Michael DeHaan |
| 120 |
""" |
| 121 |
|
| 122 |
EXAMPLES = r""" |
| 123 |
- name: Return motd to registered var |
| 124 |
ansible.builtin.command: cat /etc/motd |
| 125 |
register: mymotd |
| 126 |
|
| 127 |
# free-form (string) arguments, all arguments on one line |
| 128 |
- name: Run command if /path/to/database does not exist (without 'args') |
| 129 |
ansible.builtin.command: /usr/bin/make_database.sh db_user db_name creates=/path/to/database |
| 130 |
|
| 131 |
# free-form (string) arguments, some arguments on separate lines with the 'args' keyword |
| 132 |
# 'args' is a task keyword, passed at the same level as the module |
| 133 |
- name: Run command if /path/to/database does not exist (with 'args' keyword) |
| 134 |
ansible.builtin.command: /usr/bin/make_database.sh db_user db_name |
| 135 |
args: |
| 136 |
creates: /path/to/database |
| 137 |
|
| 138 |
# 'cmd' is module parameter |
| 139 |
- name: Run command if /path/to/database does not exist (with 'cmd' parameter) |
| 140 |
ansible.builtin.command: |
| 141 |
cmd: /usr/bin/make_database.sh db_user db_name |
| 142 |
creates: /path/to/database |
| 143 |
|
| 144 |
- name: Change the working directory to somedir/ and run the command as db_owner if /path/to/database does not exist |
| 145 |
ansible.builtin.command: /usr/bin/make_database.sh db_user db_name |
| 146 |
become: yes |
| 147 |
become_user: db_owner |
| 148 |
args: |
| 149 |
chdir: somedir/ |
| 150 |
creates: /path/to/database |
| 151 |
|
| 152 |
# argv (list) arguments, each argument on a separate line, 'args' keyword not necessary |
| 153 |
# 'argv' is a parameter, indented one level from the module |
| 154 |
- name: Use 'argv' to send a command as a list - leave 'command' empty |
| 155 |
ansible.builtin.command: |
| 156 |
argv: |
| 157 |
- /usr/bin/make_database.sh |
| 158 |
- Username with whitespace |
| 159 |
- dbname with whitespace |
| 160 |
creates: /path/to/database |
| 161 |
|
| 162 |
- name: Run command using argv with mixed argument formats |
| 163 |
ansible.builtin.command: |
| 164 |
argv: |
| 165 |
- /path/to/binary |
| 166 |
- -v |
| 167 |
- --debug |
| 168 |
- --longopt |
| 169 |
- value for longopt |
| 170 |
- --other-longopt=value for other longopt |
| 171 |
- positional |
| 172 |
|
| 173 |
- name: Safely use templated variable to run command. Always use the quote filter to avoid injection issues |
| 174 |
ansible.builtin.command: cat {{ myfile|quote }} |
| 175 |
register: myoutput |
| 176 |
""" |
| 177 |
|
| 178 |
RETURN = r""" |
| 179 |
msg: |
| 180 |
description: changed |
| 181 |
returned: always |
| 182 |
type: bool |
| 183 |
sample: True |
| 184 |
start: |
| 185 |
description: The command execution start time. |
| 186 |
returned: always |
| 187 |
type: str |
| 188 |
sample: '2017-09-29 22:03:48.083128' |
| 189 |
end: |
| 190 |
description: The command execution end time. |
| 191 |
returned: always |
| 192 |
type: str |
| 193 |
sample: '2017-09-29 22:03:48.084657' |
| 194 |
delta: |
| 195 |
description: The command execution delta time. |
| 196 |
returned: always |
| 197 |
type: str |
| 198 |
sample: '0:00:00.001529' |
| 199 |
stdout: |
| 200 |
description: The command standard output. |
| 201 |
returned: always |
| 202 |
type: str |
| 203 |
sample: 'Clustering node rabbit@slave1 with rabbit@master …' |
| 204 |
stderr: |
| 205 |
description: The command standard error. |
| 206 |
returned: always |
| 207 |
type: str |
| 208 |
sample: 'ls cannot access foo: No such file or directory' |
| 209 |
cmd: |
| 210 |
description: The command executed by the task. |
| 211 |
returned: always |
| 212 |
type: list |
| 213 |
sample: |
| 214 |
- echo |
| 215 |
- hello |
| 216 |
rc: |
| 217 |
description: The command return code (0 means success). |
| 218 |
returned: always |
| 219 |
type: int |
| 220 |
sample: 0 |
| 221 |
stdout_lines: |
| 222 |
description: The command standard output split in lines. |
| 223 |
returned: always |
| 224 |
type: list |
| 225 |
sample: [u'Clustering node rabbit@slave1 with rabbit@master …'] |
| 226 |
stderr_lines: |
| 227 |
description: The command standard error split in lines. |
| 228 |
returned: always |
| 229 |
type: list |
| 230 |
sample: [u'ls cannot access foo: No such file or directory', u'ls …'] |
| 231 |
""" |
| 232 |
|
| 233 |
import datetime |
| 234 |
import glob |
| 235 |
import os |
| 236 |
import shlex |
| 237 |
|
| 238 |
from ansible.module_utils.basic import AnsibleModule |
| 239 |
from ansible.module_utils.common.text.converters import to_native, to_bytes, to_text |
| 240 |
from ansible.module_utils.common.collections import is_iterable |
| 241 |
|
| 242 |
|
| 243 |
def main(): |
| 244 |
|
| 245 |
# the command module is the one ansible module that does not take key=value args |
| 246 |
# hence don't copy this one if you are looking to build others! |
| 247 |
# NOTE: ensure splitter.py is kept in sync for exceptions |
| 248 |
module = AnsibleModule( |
| 249 |
argument_spec=dict( |
| 250 |
_raw_params=dict(), |
| 251 |
_uses_shell=dict(type='bool', default=False), |
| 252 |
cmd=dict(), |
| 253 |
argv=dict(type='list', elements='str'), |
| 254 |
chdir=dict(type='path'), |
| 255 |
executable=dict(), |
| 256 |
expand_argument_vars=dict(type='bool', default=True), |
| 257 |
creates=dict(type='path'), |
| 258 |
removes=dict(type='path'), |
| 259 |
# The default for this really comes from the action plugin |
| 260 |
stdin=dict(required=False), |
| 261 |
stdin_add_newline=dict(type='bool', default=True), |
| 262 |
strip_empty_ends=dict(type='bool', default=True), |
| 263 |
), |
| 264 |
required_one_of=[['_raw_params', 'cmd', 'argv']], |
| 265 |
mutually_exclusive=[['_raw_params', 'cmd', 'argv']], |
| 266 |
supports_check_mode=True, |
| 267 |
) |
| 268 |
shell = module.params['_uses_shell'] |
| 269 |
chdir = module.params['chdir'] |
| 270 |
executable = module.params['executable'] |
| 271 |
args = module.params['_raw_params'] or module.params['cmd'] |
| 272 |
argv = module.params['argv'] |
| 273 |
creates = module.params['creates'] |
| 274 |
removes = module.params['removes'] |
| 275 |
stdin = module.params['stdin'] |
| 276 |
stdin_add_newline = module.params['stdin_add_newline'] |
| 277 |
strip = module.params['strip_empty_ends'] |
| 278 |
expand_argument_vars = module.params['expand_argument_vars'] |
| 279 |
|
| 280 |
# we promised these in 'always' ( _lines get auto-added on action plugin) |
| 281 |
r = {'changed': False, 'stdout': '', 'stderr': '', 'rc': None, 'cmd': None, 'start': None, 'end': None, 'delta': None, 'msg': ''} |
| 282 |
|
| 283 |
if not shell and executable: |
| 284 |
module.warn("As of Ansible 2.4, the parameter 'executable' is no longer supported with the 'command' module. Not using '%s'." % executable) |
| 285 |
executable = None |
| 286 |
|
| 287 |
if not shell and args: |
| 288 |
args = shlex.split(args) |
| 289 |
|
| 290 |
args = args or argv |
| 291 |
# All args must be strings |
| 292 |
if is_iterable(args, include_strings=False): |
| 293 |
args = [to_native(arg, errors='surrogate_or_strict', nonstring='simplerepr') for arg in args] |
| 294 |
|
| 295 |
r['cmd'] = args |
| 296 |
|
| 297 |
if chdir: |
| 298 |
chdir = to_bytes(chdir, errors='surrogate_or_strict') |
| 299 |
|
| 300 |
try: |
| 301 |
os.chdir(chdir) |
| 302 |
except OSError as ex: |
| 303 |
r['msg'] = 'Unable to change directory before execution.' |
| 304 |
module.fail_json(**r, exception=ex) |
| 305 |
|
| 306 |
# check_mode partial support, since it only really works in checking creates/removes |
| 307 |
if module.check_mode: |
| 308 |
shoulda = "Would" |
| 309 |
else: |
| 310 |
shoulda = "Did" |
| 311 |
|
| 312 |
# special skips for idempotence if file exists (assumes command creates) |
| 313 |
if creates: |
| 314 |
if glob.glob(creates): |
| 315 |
r['msg'] = "%s not run command since '%s' exists" % (shoulda, creates) |
| 316 |
r['stdout'] = "skipped, since %s exists" % creates # TODO: deprecate |
| 317 |
|
| 318 |
r['rc'] = 0 |
| 319 |
|
| 320 |
# special skips for idempotence if file does not exist (assumes command removes) |
| 321 |
if not r['msg'] and removes: |
| 322 |
if not glob.glob(removes): |
| 323 |
r['msg'] = "%s not run command since '%s' does not exist" % (shoulda, removes) |
| 324 |
r['stdout'] = "skipped, since %s does not exist" % removes # TODO: deprecate |
| 325 |
r['rc'] = 0 |
| 326 |
|
| 327 |
if r['msg']: |
| 328 |
module.exit_json(**r) |
| 329 |
|
| 330 |
r['changed'] = True |
| 331 |
|
| 332 |
# actually executes command (or not ...) |
| 333 |
if not module.check_mode: |
| 334 |
r['start'] = datetime.datetime.now() |
| 335 |
r['rc'], r['stdout'], r['stderr'] = module.run_command(args, executable=executable, use_unsafe_shell=shell, encoding=None, |
| 336 |
data=stdin, binary_data=(not stdin_add_newline), |
| 337 |
expand_user_and_vars=expand_argument_vars) |
| 338 |
r['end'] = datetime.datetime.now() |
| 339 |
else: |
| 340 |
# this is partial check_mode support, since we end up skipping if we get here |
| 341 |
r['rc'] = 0 |
| 342 |
r['msg'] = "Command would have run if not in check mode" |
| 343 |
if creates is None and removes is None: |
| 344 |
r['skipped'] = True # deprecated: description='remove this skipped value return' core_version='2.25' |
| 345 |
# skipped=True and changed=True are mutually exclusive |
| 346 |
r['changed'] = False |
| 347 |
|
| 348 |
# convert to text for jsonization and usability |
| 349 |
if r['start'] is not None and r['end'] is not None: |
| 350 |
# these are datetime objects, but need them as strings to pass back |
| 351 |
r['delta'] = to_text(r['end'] - r['start']) |
| 352 |
r['end'] = to_text(r['end']) |
| 353 |
r['start'] = to_text(r['start']) |
| 354 |
|
| 355 |
if strip: |
| 356 |
r['stdout'] = to_text(r['stdout']).rstrip("\r\n") |
| 357 |
r['stderr'] = to_text(r['stderr']).rstrip("\r\n") |
| 358 |
|
| 359 |
if r['rc'] != 0: |
| 360 |
r['msg'] = 'The command exited with a non-zero return code.' |
| 361 |
module.fail_json(**r) |
| 362 |
|
| 363 |
module.exit_json(**r) |
| 364 |
|
| 365 |
|
| 366 |
if __name__ == '__main__': |
| 367 |
main() |