knowledge/technology/tools/Ansible/modules/ansible.builtin.shell.md
2023-12-04 11:02:23 +01:00

3.8 KiB

ansible.builtin.shell

Execute shell commands on targets.

Parameter

Parameter Type Default Description
chdir path - Change into this directory before running the command.
cmd string - The command to run followed by optional arguments.
creates path - A filename, when it already exists, this step will not be run.
executable path - Change the shell used to execute the command.
removes path - A filename, when it does not exist, this step will not be run.
stdin string - Set the stdin of the command directly to the specified value.
stdin_add_newline boolean true Whether to append a newline to stdin data.

Return Values

Value Type When Description
cmd string always The command executed by the task.
delta string always The command execution delta time.
end string always The command execution end time.
rc integer always The command return code (0 means success).
start string always The command execution start time.
stderr string always The command standard error.
stderr_lines list / elements=string always The command standard error split in lines.
stdout string always The command standard output.
stdout_lines list / elements=string always The command standard output split in lines.

Examples

- name: Execute the command in remote shell; stdout goes to the specified file on the remote
  ansible.builtin.shell: somescript.sh >> somelog.txt

- name: Change the working directory to somedir/ before executing the command
  ansible.builtin.shell: somescript.sh >> somelog.txt
  args:
    chdir: somedir/

# You can also use the 'args' form to provide the options.
- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist
  ansible.builtin.shell: somescript.sh >> somelog.txt
  args:
    chdir: somedir/
    creates: somelog.txt

# You can also use the 'cmd' parameter instead of free form format.
- name: This command will change the working directory to somedir/
  ansible.builtin.shell:
    cmd: ls -l | grep log
    chdir: somedir/

- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
  ansible.builtin.shell: cat < /tmp/*txt
  args:
    executable: /bin/bash

- name: Run a command using a templated variable (always use quote filter to avoid injection)
  ansible.builtin.shell: cat {{ myfile|quote }}

# You can use shell to run other executables to perform actions inline
- name: Run expect to wait for a successful PXE boot via out-of-band CIMC
  ansible.builtin.shell: |
    set timeout 300
    spawn ssh admin@{{ cimc_host }}

    expect "password:"
    send "{{ cimc_password }}\n"

    expect "\n{{ cimc_name }}"
    send "connect host\n"

    expect "pxeboot.n12"
    send "\n"

    exit 0    
  args:
    executable: /usr/bin/expect
  delegate_to: localhost