If you are not familiar with modules, check out Ansible - Getting Started with Modules.
Typically, the shell, command, or script modules are used to invoke a command on a managed node (e.g. target systems). /usr/bin/python needs to exist on the managed node to use these modules. If Python does not exist, the raw module can be used instead.
In this example, the ps command will be invoked on the managed nodes.
---
- hosts: localhost
tasks:
- name: ps command
shell: ps
...
The following should be produced.
TASK [ps command]
changed: [server1.example.com]
Register
By default, no stdout is printed. The register parameter can be used to print output to the console.
---
- hosts: localhost
tasks:
- name: ps command
shell: ps
register: out
- name: print out
debug:
var: out
...
Which should return something like this.
TASK [print out]
ok: [localhost] => {
"out": {
"changed": true,
"cmd": "ps",
"delta": "0:00:02.674260",
"end": "2021-08-03 23:34:44.388683",
"failed": false,
"failed_when_result": false,
"msg": "non-zero return code",
"rc": 1,
"start": "2021-08-03 23:34:41.714423",
"stderr": "",
"stderr_lines": [],
"stdout": "root 122418 122378 0 23:41 ? 00:00:00 bash",
"stdout_lines": [
"root 122418 122378 0 23:41 ? 00:00:00 bash"
]
}
}
non-zero return code
Typically, a return code of 0 or 1 is ok when using the shell module. The failed_when parameter can be used to fail when the rc (return code) is not 0 or 1. Refer to our article on resolving non-zero return code.
---
- hosts: localhost
tasks:
- name: ps command
shell: ps
register: out
failed_when: out.rc not in [ 0, 1 ]
...
Become (root, sudo)
If you do not have permission to issue a certain shell command, permission denied will be returned. To resolve this, the become module can be used to become root.
Arguments
The chdir argument can be used to change into a certain directory on the managed node before running the command.
- name: invoke example.sh
shell: example.sh
args:
chdir: /tmp
Let's say the creates parameter contains /tmp/foo.txt. If /tmp/foo.txt exists, the task will not be run. If /tmp/foo.txt does not exist, the task will be run.
- name: invoke example.sh
shell: example.sh
args:
creates: /tmp/foo.txt
Let's say the removes parameter contains /tmp/foo.txt. If /tmp/foo.txt exists, the task will be run. If /tmp/foo.txt does not exist, the task will not be run.
- name: invoke example.sh
shell: example.sh
args:
removes: /tmp/foo.txt
Let's say you have a script that prompts for input, like this.
What is your name?
The stdin parameter can be used to pass standard input to the script.
- name: invoke example.sh
shell: example.sh
args:
stdin: "John Doe"