Ansible Ad-hoc commands

One of the simplest ways Ansible can be used is by using ad-hoc commands. These can be used when you want to issue some commands on a server or a bunch of servers. Ad-hoc commands are not stored for future uses but represent a fast way to interact with the desired servers.

  • You can run ansible either ad-hoc or as a playbook
  • Both methods have the same capabilities
  • Ad-hoc commands are effectively one-liners

Use cases for Ad-hoc

  • Operational commands
    • Checking log contents
    • Daemon control
    • Process management
  • Informational commands
    • Check installed software
    • Check system properties
    • Gather system performance information (CPU, disk space, memory use)
  • Research
    • Work with unfamiliar modules on test systems
    • Practice for playbook engineering

 

Ad-hoc vs Playbook

Ad-hoc mode  Playbook mode
  • Command: ansible
  • Effective for one-time commands, operational
  • Similar to a single bash command
  • Command: ansible-playbook
  • Effective for deployments, routine tasks, system activities, information gathering, and research deployment
  • Similar to bash script

Common modules

  • ping – Validate if server is up and recheable. No required parameters.
  • setup – Gather ansible facts. No required parameters.
  • yum – Use yum package manager. Parameters name and state.
  • service – Control Daemons. Parameters name and state.
  • user – Manipulate system users. Parameters name.
  • copy – Copy files. Parameters src.
  • file – Work with files. Parameters path.
  • git – Interact with git repositories. Parameters repo and dest.

 

You can check if the hosts are accessible from the ansible server by issuing a ping command on all hosts.

You can issue the same command only on a specific group:

 

You can issue the same command only on a specific host if needed.

The flag -a may be used without -m (module) to run shell command.

To reboot all managed hosts:

If you need to copy a file to multiple destinations rapidly, you can use the copy module in ansible which uses SCP. So the command and its output look like below:

 

In the next example, you will find out how to install a package via the yum module on two Centos hosts.

If you are not logged as superuser you will have problem to use yum:

So you can use -b parameter to beacome a root on remote host:

But user miro must be added to sudoers file.

Creating a file on managed host in user directory:

The same in the root home directory:

Informations about the file:

Changing properties of the file:

Changing ownership of file:

 

The ownership of file can be only changed by root. We must add -b parameter:

 

Creating a user sam in the labservers group:

Adding user sam  to the wheel group. Append parameter is needed due to we dont wan’t to wipe out group file:

Gathering facts about managed hosts: