In the Ansible Core are a lot of Ansible modules included for almost all use cases. On this page
are all modules listed and described with the available options and some examples. Some Ansible modules are on the first view quite similar and can be used for the same purpose, but often are there some crucial differences.
Shell vs. Command
A typical example are the Ansible modules Shell and Command. In the most use cases both modules lead to the same goal. Here are the main differences between these modules.
- With the Command module the command will be executed without being proceeded through a shell. As a consequence some variables like $HOME are not available. And also stream operations like <, >, | and & will not work.
- The Shell module runs a command through a shell, by default /bin/sh. This can be changed with the option executable. Piping and redirection are here therefor available.
- The command module is more secure, because it will not be affected by the user’s environment.
Conclusion
Before the usage of both modules, you should check, if there isn’t a more specific Ansible module for that task. It’s always better to use a module instead of running a raw command, because the modules are designed to be idempotent and fulfill other standards like exception handling.
If there isn’t a module available, it’s safer to use the command module, because the task will not be affected through the user environment.
If you need the user environment or streaming operations there’s only the shell module, but you should be careful. Keep in mind the following hint from Ansible, if you use the shell module in combination with variables:
To sanitize any variables passed to the shell module, you should use “{{ var | quote }}” instead of just “{{ var }}” to make sure they don’t include evil things like semicolons.)
28 Comments