1 common modules to run commands
Even though every module can be used directly as ad hoc with "ansible" command,
$ ansible all -m module_name -a module_parameters
the ad-hoc mode is mainly used for running commands just like doing it within a login console. Ansible provides some modules that take commands themselves as a parameter.
1.1 command
This is the default module for ad-hoc mode. If no "-m" option is specified, "ansible" uses the "command" module.
- It does NOT execute commands through the shell, so variables like "$HOME" and operations like "<", ">", "|" , "&" will not work.
- "command" module requires python installed on managed nodes.
e.g.
$ ansible all -a 'uname -r'
1.2 raw
"raw" module executes a low-down and dirty SSH command, not going through the module subsystem. As a result, it doesn't require python installed on managed nodes. And it's obvious usage is to install python so other modules can work later.
It returns the stdout, stderr just as is. Ansible doesn't do any error checking.
$ ansible localhost -m raw -a 'uname -r'
localhost | CHANGED | rc=0 >>
4.18.0-80.11.2.el8_0.x86_64
1.3 shell
"shell" module lets you run any commands just like within the login shell.
$ ansible localhost -m shell -a 'cat /etc/passwd | grep ^root'
localhost | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
1.4 script
Just like the shell module, the "script" module runs commands within a shell env. The main difference is the "script" module accepts a local script file on the control node, which is useful when the commands become complex, even necessary when handling shell special characters.
e.g. find users whose UID is greater than 1000.
$ cat test.sh
#!/bin/bash
cat /etc/passwd | awk -F: '$3>1000 { print $1,$3 }'
$ ansible localhost -m script -a ./test.sh
localhost | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "",
"stderr_lines": [],
"stdout": "nobody 65534\n",
"stdout_lines": [
"nobody 65534"
]
}
2 Ad-hoc commands VS playbooks
For simple and temporary tasks, ad-hoc commands are very convenient. Some Ansible users even don't bother to write playbooks at all.
But the real power of Ansible lies in its playbooks. You may be able to write a script that runs ad hoc Ansible commands functioning just like a playbook. But a playbook is much easier to write, understand, maintain, scale, extend.
No comments:
Post a Comment