Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
the blog provides an overview of using ad-hoc commands in ansible

Going Ad-Hoc With Ansible

Ansible came to the market as a Simple IT automation tool for server/infrastructure management. Being Simple, agentless, pythonic and many more features to count on it also supports ad-hoc commands.

The Ad-Hoc command is the one-liner ansible command that performs one task on one or more managed nodes. Ad-hoc commands are quick and easy, but they are not reusable.

Why use ad-hoc commands?

Ad-hoc commands are great for a very particular task or for the tasks you repeat rarely.For example doing SCP on server/machine in aws group.

$ ansible aws -i ./hosts -m copy -a "src=data.txt dest=/home/ubuntu/" -u ubuntu

Syntax

An ad-hoc command looks like this:

$ ansible [pattern] -m [module] -a "[module options]"

A few use cases

Ad-hoc tasks can be used to reboot servers, copy files, manage packages and users, and much more. You can also use any Ansible module in an ad-hoc task. So lets see some of the use cases :

Download File from the Host

Here file '/etc/demo' from the 'aws' server to the local directory called 'backup'.

ansible aws -m fetch -a 'src=/etc/demo dest=/home/knoldus/backup/ flat=yes'

Manage Packages

  • Install Package
ansible aws -m apt -a "name=nginx state=latest" --become
  • Remove package
ansible aws -m apt -a 'name=nginx state=absent purge=yes' --become

Gathering Facts

Facts can be used for implementing conditional statements in playbook.

$ ansible aws -m setup

Manage Services

$ ansible aws -m service -a 'name=nginx state=started enabled=yes' --become
$ ansible aws -m service -a 'name=nginx state=stopped' --become

Checking uptime of each server running

$ ansible aws -a "uptime"

Using inventory with ad-hoc command

$ ansible -i ./hosts -m ping aws

Summary

Ad hoc is latin words refers to something done for a very precise and particular purpose. As the word suggests, ansible ad hoc commands are written for a very particular task.

So, that was all about Ansible Ad-hoc Commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment