In the Ansible Core, there are different ansible modules included for almost all types of use cases. Modules are also known as ‘library or task plugins’, discrete units of code used on the playbook task, or the command line. Each Ansible module usually executes on the remote target node and collects the return output. The two most commonly used Ansible modules are shell and command.
The shell module in Ansible is used to execute all Shell commands against the target Unix-based hosts. The shell module executes commands in nodes or Shell scripts. Another dedicated Ansible module is Script that transfers the Shell script from the control machine to the remote server and executes it. In the command module, the given command executes on all selected nodes. The executed command will not be processed through the shell.
Ansible modules are almost similar and perform the same tasks on the first view, but there are some crucial differences between these modules. Here, we will mention in this article some main differences between the shell and command modules in Ansible.
Different Between Shell vs. Command Module in Ansible
In most of the use cases, both shell and command modules perform the same job. However, there are few main differences between these two modules.
Variable and Operations support
While using the Command module, the commands will not be executed through a shell. Consequently, variables like $HOME are not available, and operations like <, >, | and & will not work in this case. If you want to use these variables and operations, you need to use a shell module.
In the Shell module, commands are executed through a shell or by default in the remote node ‘/bin/sh’. As we have mentioned above, in the command module, commands execution is not processed through the shell. The location can be changed with an executable option. Piping and redirection features are therefore available in the shell module.
If you want to run a command predictably and securely then, it is recommended to use the command module instead of the shell. The command module will not be affected by the user’s environment, so; it is more secure than the shell module.
Although both modules are useful, you should first check whether a more specific Ansible module is available for the given task. It is best practice to use modules instead of executing the raw command because modules fulfill all standards, including exception handling. If you find there is no module available, it is more secure to use the command modules because tasks will not be affected through the user environment setup. Use the shell modules if you need some specific variable features and operations.