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:
- Quick checks
- Small changes
- Troubleshooting
- Immediate actions
Why Use Ad‑hoc Commands?
- You don’t want to create a YAML playbook
- The task is temporary or one‑time
- You need fast execution
- You want to test connectivity or configuration
Ad‑hoc Command Examples
- Ping all servers
ansible -m ping all
-m= moduleall= all servers
- Ping a specific group
ansible -m ping node
- node = group name
- Hosts are added under this group
- Check disk space
ansible -m command -a "df -h" all
-a= pass the command- command = command module
- df = check disk space
- Use shell with pipeline
ansible -m shell -a "df -h | ls" all
- shell = command module
- Pipelines can be used
- 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
- Restart a service
ansible -m service -a "name=apache2 state=restarted" all
- service module = restart Apache
- Copy a file
ansible -m copy -a "src=config dest=/tmp" all
- copy module = copy files
- src = source file
- dest = destination path
- 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
- Create a template
ansible -m template -a "src=template dest=/tmp/ak" all
- template module = create template file
- src = source template
- dest = destination path
- List all hosts
ansible --list-hosts all
- Shows all hosts in the hosts file
- 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
- Install multiple packages
ansible -m apt -a "name='vim,git,curl' state=present update_cache=yes" -b all
- Installs multiple packages
- -b = root privileges
- 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
- 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
- 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