Ansible: Ad Hoc Commands Deep Dive

Ansible ad hoc commands are one-liners designed to achieve very specific tasks they are like quick snippets and your compact Swiss army knife when you want to do a quick task across multiple machines.

To put it simply, Ansible ad hoc commands are one-liner Linux shell commands, and playbooks are like a shell script, a collective of many commands with logic.

An Ansible ad hoc command uses the /usr/bin/ansible command-line tool to automate a single task on one or more managed nodes. ad hoc commands are quick and easy, but they are not reusable. So why learn about ad hoc commands? ad hoc commands demonstrate the simplicity and power of Ansible.

Ansible ad hoc commands come in handy when you want to perform a quick task.

Understanding Ansible Ad Hoc

ad hoc commands are great for tasks you repeat rarely. For example, if you want to power off all the machines in your lab for Christmas vacation, you could execute a quick one-liner in Ansible without writing a playbook. An ad hoc command looks like this:

Configure Ansible and Run ad-hoc Commands

The -a option accepts options either through the key=value syntax or a JSON string starting with { and ending with } for a more complex option structure.

demo

Let me show you how to execute some Ansible ad-hoc commands via Ansible command.

I will show you how to use the ping module, run a command, and retrieve the Ansible facts from a target node via the Ansible command line.

1. Write an ansible ad hoc ping command to ping 3 servers from the inventory file.

ansible -i /path/to/inventory/file server1:server2:server3 -m ping

2. Write an Ansible ad hoc command to check uptime.

ansible -i /path/to/inventory/file all -m command -a uptime

3. Write an Ansible ad hoc command to check the free memory or memory usage of hosts.

ansible -i /path/to/inventory/file all -a "free -m"

4. Write a Ad-hoc command to get physical memory allocated to the host.

ansible all -m shell -a "cat /proc/meminfo|head -2"

5. Write a Ad-hoc command to check the disk space on all hosts in an inventory file.

ansible -i inventory_file all -m shell -a 'df -h'

This command uses the df command to show the disk space usage on each host in the inventory file.

6. Write a Ad-hoc command to list all the running processes on a specific host in an inventory file

ansible -i inventory_file specific_host -m command -a 'ps aux'

This command uses the ps command to list all the running processes on the specific host in the inventory file.

7. Write a Ad-hoc command to run a shell command with sudo on all hosts in an inventory file.

ansible -i inventory_file all -b -m shell -a 'sudo-command'

8. Write a Ad-hoc command to check the status of a specific service on all hosts in an inventory file.

ansible -i inventory_file all -m service -a 'name=docker state=started'

You can check the status of a specific service on single hosts or server1

ansible -i inventory_file server1 -m service -a 'name=docker state=started'

9. To create a Directory with 777 permission using the ansible ad hoc command.

 ansible all -m file -a "path=/home/ubuntu/ansible state=directory mode=0777" -b

11. To create a file with 777 permission using Ansible ad hoc commands

ansible all -m file -a "path=/path/to/file state=touch mode=0777"

12. To run a command

You can execute any Linux commands ( behind the scene, the ansible.builtin.command module) using the following Ansible ad-hoc command:

ansible host1.example.com -a "/bin/echo hi"

The output is like this:

As you can see, the connection was successful, with amber color text, a changed status, and a “hi” message printed onscreen.

Delete files or directories with Ansible.

Let’s jump into a real-life playbook on how to delete files or directories with Ansible.

---
- name: file module demo
  hosts: all
  vars:
    mypath: "/home/devops/deleteme"
  become: false
  tasks:
    - name: "{{ mypath }}" not present
      ansible.builtin.file:
        path: "{{ mypath }}"
        state: "absent"

Restart services on remote hosts with Ansible.

---
- name: service module demo
  hosts: all
  become: true
  tasks:
    - name: sshd restart
      ansible.builtin.service:
        name: sshd
        state: restarted
        enabled: true

Ansible copy files to remote hosts.

---
- name: copy module demo
  hosts: all
  become: false
  tasks:
    - name: copy report.txt
      ansible.builtin.copy:
        src: report.txt
        dest: /home/devops/report.txt
        owner: devops
        mode: '0644'

Print a text or a variable during execution with Ansible.

---
- name: debug module demo
  hosts: all
  vars:
    fruit: "apple"
  tasks:
    - name: debug message
      ansible.builtin.debug:
        msg: "our fruit is {{ fruit }}"
        verbosity: 2

Ansible check directory exists

---
- name: check if the directory exists
  hosts: all
  become: false
  vars:
    directory: "/tmp"
  tasks:
    - name: Check if the directory exists
      ansible.builtin.stat:
        path: "{{ directory }}"
      register: dir_to_check

    - name: Directory found
      ansible.builtin.debug:
        msg: "Directory {{ directory }} present"
      when: dir_to_check.stat.isdir is defined

Configuring System Users and Groups with Ansible Ad-hoc

User modules may interest users in many ways like Creating users, Removing users and changing user properties.

# Add User
ansible -i inv host1 -b -m user -a "name=super"
ansible -i inv vsathyak2 -b -m user -a "name=super state=present"
# User named "super is created"
# 'b' flag is used since user creation needs root privileges
# default 'state' is 'present'.

# Remove User
ansible -i inv host1 -b -m user -a "name=super state=absent"
#This will remove the user but won't remove the home folder of the user
ansible -i inv host1 -b -m user -a "name=super state=absent remove=yes"
# This will remove the user all info related to the user

# Add Group and Add User to Group
ansible -i inv host1 -b -m group -a "name=Group_Devops"
 #will create the group 'Group_Devops'

ansible -i -inv host1 -b -m user -a "name=super group=Group_Devops"
  #will add the user 'super' to already created group 'Group_Devops'

#Remove Group
ansible -i inv host1 -b -m user -a "name=super group=wheel"
    #Moving user 'super' from group 'Group_Devops' to group 'wheel'
ansible -i inv host1 -b -m group -a "name=Group_Devops state=absent"
    #Deleting group Group_Devops then.

Installing Software and Daemon Management

Package, yum, and apt are used to install and manage software packages, and yum and apt are used for distribution-specific software management. The package module will detect the target host distribution and use the appropriate method of installing software. In a mixed distribution environment, a package module is the best practice.

#yum
ansible -i inv centos -b -m yum -a "name=httpd state=latest"

#apt
ansible -i inv ubuntu -b -m apt -a "name=apache2 state=latest"
# Controlling Daemons with the Service Module

#To start a service
ansible -i inv host1 -b -m service -a "name=httpd state=started enabled=yes"

#To find status a service
ansible -i inv host1 -b -m service -a "name=httpd"

#To Stop a Service
ansible -i inv host1 -b -m service -a "name=httpd state=stopped

Thank you for reading!! I hope you find this article helpful.

Happy Learning!!

0
Subscribe to my newsletter

Read articles from Hemanth Narayanaswamy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hemanth Narayanaswamy
Hemanth Narayanaswamy

I'm a DevOps Engineer with a passion for automating and streamlining operational processes. I'm constantly learning and adapting to new technologies, and always looking for ways to improve and expand upon existing solutions.