Level 1
0 / 100 XP

Running Ad-hoc Commands

In this lesson, we'll focus on executing ad-hoc commands in Ansible. Ad-hoc commands are a quick and easy way to perform tasks without writing a full playbook. Specifically, we'll learn how to use an ad-hoc command to delete the file we created in our previous lesson. By the end of this lesson, you'll understand how to use Ansible for simple, direct task execution across your managed nodes.

What are Ad-hoc Commands?

Ad-hoc commands in Ansible allow you to execute simple tasks at the command line without needing to write a playbook. They are great for tasks you need to perform quickly, but they are not idempotent like a playbook, so they should be used judiciously.

Using ansible-doc for Module Information

Before we run our ad-hoc command, let's first understand how to use the ansible-doc command to get information about the file module. The file module is versatile and can be used for various file operations, including creating, deleting, or modifying files and directories.

To view the documentation for the file module, run:

ansible-doc file

__

Pro tip: You can search the file by pressing '/' and then typing in a search query. Pressing 'n' will show the next occurrence of your search pattern.

This command will display detailed information about the file module, including how to specify the path to a file and set its state. Look for the state option and notice how setting it to absent will remove a file.

Deleting the File with an Ad-hoc Command

Now, let's use an ad-hoc command to delete the file /tmp/ansible_created_this_file.txt that we created earlier. The command is as follows:

ansible all -m file -a "path=/tmp/ansible_created_this_file.txt state=absent"

Here's what this command does:

  • all specifies that the command should run on all hosts in your inventory.
  • -m file tells Ansible to use the file module.
  • -a allows you to pass arguments to the module. Her…