AD‑HOC COMMANDS

Introduction

An Ansible ad‑hoc command is a one‑line command used to perform quick tasks on one or more remote servers without writing a playbook.

It is mainly used for:

Why Use Ad‑hoc Commands?

Ad‑hoc Command Examples

  1. Ping all servers
    ansible -m ping all
    • -m = module
    • all = all servers
  2. Ping a specific group
    ansible -m ping node
    • node = group name
    • Hosts are added under this group
  3. Check disk space
    ansible -m command -a "df -h" all
    • -a = pass the command
    • command = command module
    • df = check disk space
  4. Use shell with pipeline
    ansible -m shell -a "df -h | ls" all
    • shell = command module
    • Pipelines can be used
  5. Install Apache using apt
    ansible node -m apt -a "name=apache2 state=present update_cache=yes" -b
    • apt = module to install Apache
    • name = package name
    • state = package state
    • update_cache = updates apt cache
    • -b = run with elevated privileges
  6. Restart a service
    ansible -m service -a "name=apache2 state=restarted" all
    • service module = restart Apache
  7. Copy a file
    ansible -m copy -a "src=config dest=/tmp" all
    • copy module = copy files
    • src = source file
    • dest = destination path
  8. Create a directory
    ansible -m file -a "dest=/tmp/ak mode=644 state=directory" all
    • file module = create directories
    • dest = directory path
    • mode = permissions
    • state = directory state
  9. Create a template
    ansible -m template -a "src=template dest=/tmp/ak" all
    • template module = create template file
    • src = source template
    • dest = destination path
  10. List all hosts
    ansible --list-hosts all
    • Shows all hosts in the hosts file
  11. Create a user
    ansible -m user -a "name=devops state=present groups=sudo append=yes" all
    • user module = create a user
    • name = username
    • state = user state
    • groups=sudo = add to sudo group
    • append=yes = keep existing groups
  12. Install multiple packages
    ansible -m apt -a "name='vim,git,curl' state=present update_cache=yes" -b all
    • Installs multiple packages
    • -b = root privileges
  13. Delete a file or directory
    ansible -m file -a "path=/tmp/oldfile state=absent" all
    • state=absent = delete file or directory
    • path = file or directory path
  14. Fetch files from remote hosts
    ansible -m fetch -a "src=/etc/hosts dest=~/hosts_backup/ flat=yes" all
    • fetch module = copy remote files to local
    • flat=yes = avoids creating directories
  15. Synchronize directories
    ansible -m synchronize -a "src=/local/dir dest=/remote/dir" all
    • synchronize module = sync directories
    • src = source directory
    • dest = destination directory
    • Uses rsync