Skip to content
Jun 2 / Greg

Ansible Command vs Shell vs Raw Modules

Ansible has the ability to run remote commands in several different ways. Recently I was trying to figure out what the difference was between command, shell, and raw modules; when is the proper time to use one over the other.

Raw Module

The raw module is the most stripped down base way to run commands on a remote system and is NOT recommended. It actually executes commands natively on the system and returns standard output back. This module, unlike all others, doesn’t use python on the remote system. This means it could be used on devices like IoT kit or networking devices that don’t have any other supported method.

1
2
- name: Bootstrap a host without python2 installed
  raw: dnf install -y python2 python2-dnf libselinux-python

Shell Module

The shell module will run commands via the local shell on the remote system. This is usually discouraged also in favor of the command module. If the command you want to execute should use local environment variables, or you want to pipe the output to a file or grep(“<", ">“, “|”, “;”, “&”), then this is the droid you are looking for.

1
2
3
4
5
- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist.
  shell: somescript.sh >> somelog.txt
  args:
    chdir: somedir/
    creates: somelog.txt

Command Module

The command module runs the local binary file you supply it. It is not run through the shell, so no environment variable or piping are not an option.

1
2
3
4
5
6
7
- name: Change the working directory to somedir/ and run the command as db_owner if /path/to/database does not exist.
  command: /usr/bin/make_database.sh db_user db_name
  become: yes
  become_user: db_owner
  args:
    chdir: somedir/
    creates: /path/to/database

Thanks for reading and happy automating.

Leave a Comment

 

*