How to execute Ad-Hoc Commands in ansible

Ad-Hoc Commands

Ad-Hoc commands are quick commands which are used to perform actions, that won’t be saved for later.

Ad-Hoc in Latin means something done for a very precise and particular purpose.  As the word suggests, ansible ad hoc commands are written for a very particular task

Parallelism & Shell Commands

#To set up SSH agent
$ ssh-agent bash $ ssh-add ~/.ssh/id_rsa
#To use SSH with a password instead of keys, you can use --ask-pass (-K)
$ ansible europe -a "/sbin/reboot" -f 20
#To run /usr/bin/ansible from a user account, not the root
$ ansible europe -a "/usr/bin/foo" -u username
#To run commands through privilege escalation and not through user account
$ ansible europe -a "/usr/bin/foo" -u username --become [--ask-become-pass]
#If you are using password less method then use --ask-become-pass (-K) to interactively get the password to be use
#You can become a user, other than root by using --become-user
$ ansible europe -a "/usr/bin/foo" -u username --become --become-user otheruser [--ask-become-pass]

File Transfer

#Transfer a file directly to many servers
$ ansible europe -m copy -a "src=/etc/hosts dest=/tmp/hosts"
#To change the ownership and permissions on files
$ ansible webservers -m file -a "dest=/srv/foo/a.txt mode=600" $ ansible webservers -m file -a "dest=/srv/foo/b.txt
mode=600 owner=example group=example"
#To create directories
$ ansible webservers -m file -a "dest=/path/to/c mode=755 owner=example group=example state=directory“
#To delete directories (recursively) and delete files
$ ansible webservers -m file -a "dest=/path/to/c state=absent

Manage Packages

#To ensure that a package is installed, but doesn’t get updated
$ ansible webservers -m apt -a "name=acme state=present"
#To ensure that a package is installed to a specific version
$ ansible webservers -m apt -a "name=acme-1.5 state=present"
#To ensure that a package at the latest version
$ ansible webservers -m apt -a "name=acme state=latest"
#To ensure that a package is not installed
$ ansible webservers -m apt -a "name=acme state=absent

Manage Services

#To ensure a service is started on all web servers
$ ansible webservers -m service -a "name=httpd
#To restart a service on all web servers
$ ansible webservers -m service -a "name=httpd
#To ensure a service is stopped
$ ansible webservers -m service -a "name=httpd

Deploying From Source Control

#GitRep: #Destination:/src/myapp
$ ansible webservers -m git -a "repo= dest=/src/myapp version=HEAD"

Leave a Reply

Your email address will not be published.