Executing Commands on Remote Hosts with Ansible's Shell Module
The shell module in Ansible executes commands on remote nodes using /bin/sh. It is recommended to avoid using generic command modules like shell or command when specific modules such as yum or copy can accomplish the task, as generic modules lack built-in idempotency checks and may re-run unnecessarily.
Shell module supports shell features like variable expansion, redirection operators (<, >), pipes (|), command separators (;), and background execution (&).
1. Key Parameters
| Parameter | Default | Description |
|---|---|---|
| cmd | null | Command to execute |
| chdir | null | Change to this directory before running the command |
| creates | null | Skip the task if the specified file exists |
| removes | null | Skip the task if the specified file does not exist |
| executable | null | Absolute path to the shell executable for command execution |
| free_form | null | Accepts a command string in free form |
| stdin | null | Set the command's standard input directly to the given value |
| stdin_add_newline | true | Append a newline to stdin data |
| warn | true | Enable task warnings |
2. Practical Examples
2.1 Check for File Existence on Remote Host
ansible all -m shell -a "ls /tmp | grep sample.sh"
2.2 Display File Contents
ansible all -m shell -a "cat /tmp/sample.sh"
2.3 Retrieve Remote Host IP Address
ansible all -m shell -a "ip addr show eth0 | awk '/inet / {print \$2}' | cut -d/ -f1"
2.4 Create a File and Append Text
ansible all -m shell -a 'echo "shell module demonstration" >> /tmp/output.txt'
2.5 Run a Script on Remote Host
ansible all -m shell -a "/tmp/sample.sh"
2.6 Execute Command After Changing Directory
ansible all -m shell -a 'chdir=/tmp echo "data written here" > result.txt'