I'm starting with Ansible, and I found that there is a module called command
which lets me execute any command in a remote node.
I saw a couple of example where initial setups are solved by using command
instead of specific modules. For example, as far as I know, both of these do the same task:
- name: Install git using apt module
apt:
name: git
state: present
- name: Install git using command
command: apt-get install git
So, my question is: is there any difference or any reason to use a module instead of command?
Both modules execute commands on target nodes but in a sensible different way. The command modules execute commands on the target machine without using the target shell, it simply executes the command. The target shell is for example the popular bash , zsh , or sh .
Ansible command module is used to run any commands or run any scripts in the remote target machine. Or used to execute commands on a remote node. The command module is used to run simple Linux commands on a remote node or server, which is a part of the host group or standalone server mentioned in the host group.
The command module takes the command name followed by a list of space-delimited arguments. The given command will be executed on all selected nodes. The command(s) will not be processed through the shell, so variables like $HOSTNAME and operations like "*" , "<" , ">" , "|" , ";" and "&" will not work. Use the ansible.
The difference in short is that using a specific module will give you playbook's idempotence and provide better portability and readability.
What I mean by idempotence? When you run:
- name: Install git using apt module
apt:
name: git
state: present
It will install git package only if it is not yet installed on the target system and after playbook run this task will be reported in green colour (OK
) if git had been already installed.
2nd approach with the command
module:
- name: Install git using command
command: apt-get install git
Above command will always report status as changed
(yellow colour) when in fact nothing changed (assuming git package had been already installed). There are ways to make tasks that use the command
module idempotent as well but it costs you some more work.
Best practice is to always use a specific module before command
in playbooks.
Ansible is all about describing and managing system state. When you run a playbook on a certain target system it can be very misleading to see a task reporting a changed
state while in fact nothing has been changed.
Think declaratively about describing desired state, not about low level commands needed to get a system to this state.
Below article will also provide some explanation around differences and consequences of using command
vs specific module:
Ansible Best Practices: The Essentials
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With