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 www.shellhacks.com

Sample output:

TASK [ansible_shell_command : Run a shell command on a remote host] ******************
changed: [127.0.0.1] => changed=true 
  cmd: ping -c1 www.shellhacks.com
  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 www.shellhacks.com (51.81.56.51) 56(84) bytes of data.
    64 bytes from us12.default-host.net (51.81.56.51): icmp_seq=1 ttl=48 time=89.7 ms
  
    --- www.shellhacks.com 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:

$ ANSIBLE_STDOUT_CALLBACK=yaml ANSIBLE_VERBOSITY=1 ansible-playbook ...

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: |
    whoami
    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 www.shellhacks.com"

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