1-Day1-2-AnsibleAd-hocCommands

Introduction to Ansible Ad-hoc Commands

  • What are Ad-hoc Commands?

    • Ansible ad hoc commands use the /usr/bin/ansible command-line tool to automate a single task on one or more managed nodes.

    • They are quick and easy but not reusable.

    • Ad hoc commands demonstrate the simplicity and power of Ansible.

    • Concepts learned here directly apply to playbook development.

If you are familiar with Linux, we can compare the Ansible ad hoc commands with one-liner Linux shell commands; and the playbooks to shell script.

Refer the official Ansible documentationarrow-up-right for more information.

  • Use Cases for Ad-hoc Tasks:

    • Rebooting servers

    • Managing files

    • Installing packages

    • Managing users and groups

    • Managing services

    • Gathering facts

    • Check mode (dry run)

    • And more!

Practical Examples of Ansible Ad-hoc Commands

  1. Ping All Hosts:

    • Verify connectivity to all hosts.

    • Command: $ ansible all -m ping

    • Sample Output:

(This is not the OS ping command,it is an Ansible module named ping)*arrow-up-right

  1. Check Uptime:

    • Get uptime information from hosts.

    • Command: $ ansible all -a "uptime"

    • Sample Output:

  2. Memory Usage:

    • Check free memory on hosts.

    • Command: $ ansible all -a "free -m"

    • Sample Output:

  3. Create a Unix User:

    • Create a user named "myuser."

    • Command: $ ansible all -a "useradd myuser"

    • Sample Output:

(The user creation require root privillage in the managed nodes, if not the command will fail)

  1. Check User ID (UID):

    • Verify the user ID for "myuser."

    • Command: $ ansible all -a "id myuser"

    • Sample Output:

  2. Create a Directory Using the File Module:

    • Create a directory named "/etc/some_directory."

    • Command: $ ansible all -m file -a "path=/etc/some_directory state=directory mode=0755"

    • Note: The Ansible file module is used to manage files and directories. It allows you to create, delete, modify permissions, copy, touch, or manipulate file ownership.

Note: (We used an Ansible module named file. We will discuss modules later in the session. If you want to know more about the file module,)please refer to the official documentation.arrow-up-right

Last updated