Skip to main content

Running Ad-Hoc Commands

1. Executing Ad-Hoc Commands

Command Description Example
ansible <host-pattern> -m <module> Execute a module on remote hosts ansible all -m ping
ansible <host-pattern> -a "<module-args>" Execute a module with arguments ansible webserver -a "ls -l /tmp"
ansible <host-pattern> -m <module> -a "<args>" Execute a module with arguments on remote hosts ansible all -m command -a "uptime"

Example: Ping all hosts

ansible all -m ping

Example: List files in /tmp

ansible webserver -a "ls -l /tmp"
Note: The -m flag specifies the module to use, and -a provides arguments for that module. The <host-pattern> defines which hosts to target.

2. Using Module Arguments

Argument Description Example
host_pattern Target hosts or groups to run the command on all, webservers, web[0:1]
module_name Name of the Ansible module to execute ping, copy, shell
module_args Arguments passed to the module as key=value pairs src=/tmp/file.txt dest=/etc/file.txt

Example: Running a shell command with arguments

ansible all -m shell -a "ls -l /home"

Example: Using copy module with arguments

ansible webservers -m copy -a "src=/local/file.txt dest=/remote/file.txt"
Note: Module arguments are passed as key=value pairs and must be quoted if they contain spaces or special characters.

3. Specifying Module

Module Description Usage Notes
command Execute a command on the remote host ansible all -m command -a "ls -l" Does not support shell operators like pipes or redirections
shell Execute a command using the shell on the remote host ansible all -m shell -a "ls -l | grep txt" Supports shell operators and pipes
copy Copy files from the controller to the remote host ansible all -m copy -a "src=/local/file dest=/remote/path" Can also copy from local to remote
file Manage files and directories on the remote host ansible all -m file -a "path=/remote/file state=absent" Can set ownership, permissions, and other file attributes
yum Manage packages using YUM (RedHat/CentOS) ansible all -m yum -a "name=nginx state=present" Supports installing, updating, and removing packages
apt Manage packages using APT (Debian/Ubuntu) ansible all -m apt -a "name=nginx state=present" Supports installing, updating, and removing packages

Example: Running a command with shell module

ansible all -m shell -a "df -h | grep /dev/sda"</code>
</pre>
</div>
</div>
<div class="example">
<h2 id="example-copying-a-file-using-copy-module">Example: Copying a file using copy module<a href="#example-copying-a-file-using-copy-module" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<div class="codeBlock" data-language="yaml">
<pre><code>- name: Copy a file to remote hosts
  copy:
    src: /local/config.ini
    dest: /etc/config.ini</code>
</pre>
</div>
</div>
<h2 id="4-targeting-hosts">4. Targeting Hosts<a href="#4-targeting-hosts" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<table>
<tbody>
<tr>
<th>Target</th>
<th>Description</th>
<th>Examples</th>
</tr>
<tr>
<td class="property">all</td>
<td>Selects all hosts defined in the inventory</td>
<td><code>ansible all -m ping</code></td>
</tr>
<tr>
<td class="property">group_name</td>
<td>Selects all hosts in a specific group</td>
<td><code>ansible webservers -m ping</code></td>
</tr>
<tr>
<td class="property">host_name</td>
<td>Selects a specific host by name</td>
<td><code>ansible web1 -m ping</code></td>
</tr>
<tr>
<td class="property">pattern</td>
<td>Uses glob patterns to match host names</td>
<td><code>ansible 'web*' -m ping</code></td>
</tr>
<tr>
<td class="property">host_list</td>
<td>Lists specific hosts separated by commas</td>
<td><code>ansible 'web1,web2' -m ping</code></td>
</tr>
</tbody>
</table>
<div class="example">
<h2 id="example-using-host-patterns">Example: Using Host Patterns<a href="#example-using-host-patterns" class="toc__headingLink" aria-label="Link to this section"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<div class="codeBlock" data-language="bash">
<pre><code>ansible 'web*' -m ping

Example: Targeting Multiple Groups

ansible 'webservers:dbservers' -m ping

Example: Excluding Hosts

ansible 'all:!localhost' -m ping

5. Setting Parallelism

Option Values Description
forks 5 Number of parallel processes to use for executing tasks
serial 10 Number of hosts to process in serial (default: all)
max_fail_percentage 30 Maximum percentage of hosts that can fail before stopping execution

Example: Running tasks with limited parallelism

ansible all -m ping -f 3
Note: The -f flag sets the number of forks (parallel processes). Adjust based on system resources and desired concurrency.

6. Checking Connectivity

Command Description Example
ansible <pattern> -m ping Check if hosts are reachable and Ansible can communicate with them ansible all -m ping
ansible <pattern> -m ping -o Optimize output for scripting by using one line per host ansible webservers -m ping -o
Note: The ping module does not actually ping the host, but rather tests connectivity and Ansible's ability to execute tasks.

7. Running Shell Commands

Option Values Notes
shell command Execute a shell command on the target host
args chdir, creates, removes, executable Additional arguments to pass to the shell command

Example: Running a shell command

---
- hosts: all
  tasks:
    - name: Run a shell command
      shell: whoami

Example: Running a shell command with arguments

---
- hosts: all
  tasks:
    - name: Run a shell command with chdir
      shell: ls -la
      args:
        chdir: /home/user
Note: The shell module executes commands in a shell environment and should be used carefully to avoid security issues.

8. Copying Files

Option Values Notes
src string Path to local file or directory to copy
dest string Remote path where file or directory will be copied
mode string Permissions for the remote file (e.g., 0644)
owner string User owner of the remote file
group string Group owner of the remote file

Example: Copying a File

- name: Copy a file to remote hosts
  copy:
    src: /local/path/to/file.txt
    dest: /remote/path/to/file.txt
    mode: '0644'

Example: Copying a Directory

- name: Copy a directory to remote hosts
  copy:
    src: /local/path/to/dir/
    dest: /remote/path/to/dir/
    mode: '0755'
Note: The copy module does not support recursive copying of directories. Use the archive and unarchive modules for such operations.

9. Gathering Facts

Fact Description Example Value
ansible_fqdn Fully qualified domain name web01.example.com
ansible_hostname Hostname web01
ansible_os_family Operating system family RedHat
ansible_distribution OS distribution name Ubuntu
ansible_distribution_version OS version 20.04
ansible_kernel Kernel version 5.4.0-104-generic
ansible_memory_mb Total memory in MB {"real": {"total": 4096}}
ansible_processor_count Number of CPU cores 4
ansible_interfaces List of network interfaces ["lo", "eth0"]
ansible_default_ipv4 Default IPv4 address {"address": "192.168.1.100", "interface": "eth0"}

Example: Gathering Facts with Ad-Hoc Command

ansible web_servers -m setup

Example: Limiting Facts Collection

ansible web_servers -m setup -a "filter=ansible_hostname"
Note: Facts are collected automatically when using ansible or ansible-playbook commands. You can also force fact gathering with the setup module.

10. Managing Packages

Package Manager Module Notes
apt ansible.builtin.apt Used on Debian/Ubuntu systems
yum ansible.builtin.yum Used on RHEL/CentOS systems
dnf ansible.builtin.dnf Used on Fedora systems
pacman ansible.builtin.pacman Used on Arch Linux systems

Example: Install a package with apt

- name: Install nginx with apt
  ansible.builtin.apt:
    name: nginx
    state: present

Example: Install a package with yum

- name: Install httpd with yum
  ansible.builtin.yum:
    name: httpd
    state: present

Example: Install a package with dnf

- name: Install httpd with dnf
  ansible.builtin.dnf:
    name: httpd
    state: present

Example: Install a package with pacman

- name: Install nginx with pacman
  ansible.builtin.pacman:
    name: nginx
    state: present

11. Managing Services

Service Module Parameters Description
name string Name of the service to manage
state started | stopped | restarted | reloaded Desired state of the service
enabled yes | no Whether the service should be enabled to start at boot
daemon_reload yes | no Reload the systemd daemon to pick up changes (systemd only)

Example: Start and Enable a Service

- name: Start and enable nginx service
  ansible.builtin.systemd:
    name: nginx
    state: started
    enabled: yes

Example: Stop and Disable a Service

- name: Stop and disable mysql service
  ansible.builtin.systemd:
    name: mysql
    state: stopped
    enabled: no
Note: For systems using SysV init, use ansible.builtin.service instead of systemd.

12. Using Privilege Escalation

Option Values Description
become true Enable privilege escalation for the task
become_method sudo Method used to escalate privileges (e.g., sudo, su, doas)
become_user root User to escalate privileges to (default is root)
become_flags -H Flags passed to the privilege escalation tool (e.g., -H for sudo)

Example: Running a command with privilege escalation

- name: Run command as root
  command: whoami
  become: true
  become_method: sudo
  become_user: root
Note: Privilege escalation requires proper configuration in ansible.cfg or via sudo on the target host.

Was this article helpful?