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:
Ad‑hoc commands are used when:
ansible -m ping all
ansible -m ping all-m = modulesall denotes all serversansible -m ping node
ansible -m ping nodenode means it is a groupansible -m command -a "df -h" all
ansible -m command -a "df -h" all-a is used to pass the commandcommand is a command moduledf is used to check disk spaceansible -m shell -a "df -h | ls" all
ansible -m shell -a "df -h | ls" allshell is a command moduleansible node -m apt -a "name=apache2 state=present update_cache=yes" -b
ansible node -m apt -a "name=apache2 state=present update_cache=yes" -bapt is a module to install apache2name is the package namestate defines package stateupdate_cache updates apt cache-b is used to run with elevated privilegesansible -m service -a "name=apache2 state=restarted" all
ansible -m service -a "name=apache2 state=restarted" allservice module is used to restart apache2ansible -m copy -a "src=config dest=/tmp" all
ansible -m copy -a "src=config dest=/tmp" allcopy module copies filessrc is the source filedest is the destinationansible -m file -a "dest=/tmp/ak mode=644 state=directory" all
ansible -m file -a "dest=/tmp/ak mode=644 state=directory" allfile module creates directoriesdest is the directory pathmode sets permissionsstate defines directory stateansible -m template -a "src=template dest=/tmp/ak" all
ansible -m template -a "src=template dest=/tmp/ak" alltemplate module creates a template filesrc is the source templatedest is the destination pathansible --list-host all
ansible --list-host allansible -m user -a "name=devops state=present groups=sudo append=yes" all
ansible -m user -a "name=devops state=present groups=sudo append=yes" alluser module creates a username is the usernamestate defines user stategroups=sudo adds user to sudo groupappend=yes keeps existing groupsansible -m apt -a "name='vim,git,curl' state=present update_cache=yes" -b all
ansible -m apt -a "name='vim,git,curl' state=present update_cache=yes" -b all-b ensures root privilegesansible -m file -a "path=/tmp/oldfile state=absent" all
ansible -m file -a "path=/tmp/oldfile state=absent" allstate=absent deletes the file or directorypath specifies the file pathansible -m fetch -a "src=/etc/hosts dest=~/hosts_backup/ flat=yes" all
ansible -m fetch -a "src=/etc/hosts dest=~/hosts_backup/ flat=yes" allfetch copies files from remote to localflat=yes avoids directory structure creationansible -m synchronize -a "src=/local/dir dest=/remote/dir" all
ansible -m synchronize -a "src=/local/dir dest=/remote/dir" allsynchronize syncs directoriessrc is the source directorydest is the destination directoryrsync