Debakar Roy

Day 18: Ansible - Ad-hoc commands and playbooks

1 min read

Ansible simplifies routine IT work. This post covers its two execution styles: ad-hoc commands for quick one-off tasks on remote hosts, and playbooks for reusable, more complex automation.

Setup

My lab: one Ubuntu Ansible controller and three Debian managed hosts.

Ansible ad-hoc commands

Ad-hoc commands run directly from the command line — ideal for quick checks like service status or uptime, with no playbook file needed.

Here are some examples against the linux-host inventory group:

Check if Linux hosts are reachable

ansible linux-host -m ping


Check uptime of all Linux hosts

ansible linux-host -m command -a "uptime"


Use the ansible.builtin.shell module

ansible linux-host -m ansible.builtin.shell -a 'echo $TERM'


Use the ansible.builtin.copy module

ansible linux-host -m ansible.builtin.copy -a "src=/etc/hosts dest=/tmp/hosts"


Ad-hoc commands suit simple, one-off tasks only — anything complex belongs in a playbook.

Ansible playbooks

Playbooks are the core of Ansible automation. Written in YAML, they define an ordered set of tasks for remote hosts, and can be shared, reused, and versioned.

Here is a playbook that installs and configures Apache on all Debian hosts in the linux-host group:

---
- name: Install and configure Apache on Debian hosts
  hosts: linux-host
  become: true

  tasks:
    - name: Update package index
      apt:
        update_cache: true

    - name: Install Apache
      apt:
        name: apache2
        state: present

    - name: Start and enable Apache service
      service:
        name: apache2
        state: started
        enabled: true

  handlers:
    - name: Restart Apache
      service:
        name: apache2
        state: restarted

It updates the package index, installs Apache via the apt module, then starts and enables the service, with a handler ready to restart Apache when notified of config changes.

To run it, save the file as apache_setup.yml and execute:

ansible-playbook apache_setup.yml

Conclusion

Ad-hoc commands cover quick one-off tasks; playbooks handle everything repeatable and complex. Together they simplify most day-to-day automation and keep the workflow consistent.


Further reading: