Rene B.
Rene B.

Reputation: 7414

Whats the difference between ansible 'raw', 'shell' and 'command'?

What is the difference between raw, shell and command in the ansible playbook? And when to use which?

Upvotes: 11

Views: 23522

Answers (2)

U880D
U880D

Reputation: 12121

Since I were I stumbling about the same question, I wanted to share my findings here too.

The command and shell module, as well gather_facts (annot.: setup.py) depend on a properly installed Python interpreter on the Remote Node(s). If that requirement isn't fulfilled one may experience errors were it isn't possible to execute

python <ansiblePython.py>

In a Debian 10 (Buster) minimal installation i.e., python3 was installed but the symlink to python missing.

To initialize the system correctly before applying all other roles, I've used an approach with the raw module

ansible/initSrv/main.yml

- hosts: "{{ target_hosts }}"
  gather_facts: no # is necessary because setup.py depends on Python too

  pre_tasks:
  - name: "Make sure remote system is initialized correctly"
    raw: 'ln -s /usr/bin/python3 /usr/bin/python'
    register: set_symlink
    failed_when: set_symlink.rc != 0 and set_symlink.rc != 1 

which is doing something like

/bin/sh -c 'ln -s /usr/bin/python3 /usr/bin/python'

on the remote system.

Further Documentation

... but not only restricted to that

Another Use Case

Upvotes: 8

TinaC
TinaC

Reputation: 276

command: executes a remote command on the target host, in the same shell of other playbook's tasks.
It can be used for launch scripts (.sh) or for execute simple commands. For example:

- name: Cat a file
  command: cat somefile.txt

- name: Execute a script
  command: somescript.sh param1 param2

shell: executes a remote command on the target host, opening a new shell (/bin/sh).
It can be used if you want to execute more complex commands, for example, commands concatenated with pipes. For example:

- name: Look for something in a file
  shell: cat somefile.txt | grep something

raw: executes low-level commands where the interpreter is missing on the target host, a common use case is for installing python. This module should not be used in all other cases (where command and shell are suggested)

Upvotes: 16

Related Questions