Ansible: Run Shell Command on Remote Host

To run a command on a remote host we can use the Ansible’s shell module (or win_shell for Windows targets).

By default, the shell module uses the /bin/sh shell to execute commands, but it is possible to use other shells such as /bin/bash by passing the executable argument.

In this note i will show the examples of Ansible tasks running shell commands on remote hosts and also i will show how to execute ad hoc commands to perform quick tasks without having to write a playbook.

Cool Tip: Ansible Playbook – Print Variable & List All Variables! Read more →

Ansible Shell Command

Run a Shell Command

Create a task as follows to run a shell command on a remote host, e.g. to ping something from a remote host:

- name: "Run a shell command on a remote host"
  shell: ping -c1

Sample output:

TASK [ansible_shell_command : Run a shell command on a remote host] ******************
changed: [] => changed=true 
  cmd: ping -c1
  delta: '0:00:00.097941'
  end: '2021-12-19 19:01:59.890245'
  msg: ''
  rc: 0
  start: '2021-12-19 19:01:59.792304'
  stderr: ''
  stderr_lines: <omitted>
  stdout: |-
    PING ( 56(84) bytes of data.
    64 bytes from ( icmp_seq=1 ttl=48 time=89.7 ms
    --- ping statistics ---
    1 packets transmitted, 1 received, 0% packet loss, time 0ms
    rtt min/avg/max/mdev = 89.709/89.709/89.709/0.000 ms
  stdout_lines: <omitted>

To see the output of the executed command you should run the ansible-playbook with ANSIBLE_VERBOSITY=1 and higher, for example as follows:


Cool Tip: Enable DEBUG mode and increase VERBOSITY in Ansible! Read more →

Run Multiple Commands

To run multiple shell commands in Ansible:

- name: "Execute multiple commands"
  shell: |
    uptime & uname -a
    echo "Test" > /dev/null

Ad-Hoc Command in Ansible

Use the ping Ansible module to check the availability of all hosts listed in inventory.ini:

$ ansible -i inventory.ini all -m ping

To run an ad hoc shell command:

$ ansible -i inventory.ini <remote_host> -m shell -a "ping -c1"

To execute multiple ad hoc shell commands:

$ ansible -i inventory.ini <remote_host> -m shell -a "uptime & whoami"

Cool Tip: How to fix the Ansible’s “sudo: a password is required” error! Read more →

Leave a Reply