How to distinguish Shell modules from Command modules in Ansible, and what is the main difference between them?
sobes.tech AI
Answer from AI
In Ansible, Shell modules and Command modules are used to execute commands on remote hosts, but they have key differences:
-
The Command module executes a command without using a shell. This means features like pipes (
|), redirection (>,<), environment variables, etc., are not supported. -
The Shell module runs the command through a shell (usually
/bin/sh), allowing the use of all shell features, including pipes, redirection, conditional operators, etc.
The main difference is that the Shell module offers more flexibility for complex commands but may be less secure, as the shell can interpret special characters.
Example:
- name: Run a simple command without a shell
ansible.builtin.command:
cmd: ls -l /tmp
- name: Run a command with a pipe through shell
ansible.builtin.shell:
cmd: ps aux | grep nginx
Use Command when a simple command without a shell is needed, and Shell when shell capabilities are required.