Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Executing Commands on Remote Hosts with Ansible's Shell Module

Tech 1

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'

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.