Ansible Ad Hoc Commands: Complete Guide for Beginners with example

Ansible Ad-Hoc commands

Table of Contents

OBJECTIVES:

After completing this section, you should be able to run a single Ansible automation task using an ad hoc command and explain some use cases for ad hoc commands.

What is AD HOC Command in Ansible? 

An ad hoc command is a way of executing a single Ansible task quickly, one that you do not need to save to run again later. They are simple, online operations that can be run without writing a playbook. Ad hoc commands are useful for quick tests and changes. For example, you can use an ad hoc command to make sure that a certain line exists in the /etc/hosts file on a group of servers.

Ad hoc commands are very useful for quickly performing simple tasks with Ansible.

Running Ad Hoc Commands:

Use the ansible command to run ad hoc commands:

ansible host-pattern -m module [-a 'module arguments'] [-i inventory]

The host-pattern argument is used to specify the managed hosts on which the ad hoc command should be run. It could be a specific managed host or host group in the inventory. You have already seen this used in conjunction with the –list-hosts option, which shows you which hosts are matched by a particular host pattern. You have also already seen that you can use the -i option to specify a different inventory location to use than the default in the current Ansible configuration file.

The -m option takes as an argument the name of the module that Ansible should run on the targeted hosts. Modules are small programs that are executed to implement your task. Some modules need no additional information, but others need additional arguments to specify the details of their operation. The -a option takes a list of those arguments as a quoted string.

One of the simplest ad hoc commands uses the ping module. This module does not do an ICMP ping, but checks to see if you can run Python-based modules on managed hosts. For example, the following ad hoc command determines whether all managed hosts in the inventory can run standard modules:

vagrant@vm1:~/ansible$ ansible all -m ping

vm2 | SUCCESS => {

    “ansible_facts”: {

        “discovered_interpreter_python”: “/usr/bin/python3”

    },

    “changed”: false,

    “ping”: “pong”

}

192.168.56.12 | SUCCESS => {

    “ansible_facts”: {

        “discovered_interpreter_python”: “/usr/bin/python3”

    },

    “changed”: false,

    “ping”: “pong”

}

Performing Tasks with Modules Using Ad Hoc Commands:

Modules are the tools that ad hoc commands use to accomplish tasks. Ansible provides hundreds of modules which do different things. You can usually find a tested, special-purpose module that does what you need as part of the standard installation. The ansible-doc -l command lists all modules installed on a system. You can use ansible-doc to view the documentation of particular modules by name, and find information about what arguments the modules take as options.
The following table lists a number of useful modules as examples.

Ansible Modules

MODULE CATEGORY MODULES
Files modules • copy: Copy a local file to the managed host • file: Set permissions and other properties of files • lineinfile: Ensure a particular line is or is not in a file • synchronize: Synchronize content using rsync
Software package modules • package: Manage packages using autodetected package manager native to the operating system • yum: Manage packages using the YUM package manager • apt: Manage packages using the APT package manager • dnf: Manage packages using the DNF package manager • gem: Manage Ruby gems • pip: Manage Python packages from PyPI
System modules • firewalld: Manage arbitrary ports and services using firewalld • reboot: Reboot a machine • service: Manage services • user: Add, remove, and manage user accounts
Net Tools modules • get_url: Download files over HTTP, HTTPS, or FTP • nmcli: Manage networking • uri: Interact with web services

For example, the following ad hoc command uses the user module to ensure that the gautam user exists and has UID 1001 on vm2:

vagrant@vm1:~/ansible$ ansible webserver -m user -a ‘name=gautam uid=1001 state=present’ -u gautam

vm2 | SUCCESS => {

    “ansible_facts”: {

        “discovered_interpreter_python”: “/usr/bin/python3”

    },

    “append”: false,

    “changed”: false,

    “comment”: “GK,,,”,

    “group”: 1001,

    “home”: “/home/gautam”,

    “move_home”: false,

    “name”: “gautam”,

    “shell”: “/bin/bash”,

    “state”: “present”,

    “uid”: 1001

}

Running Arbitrary Commands on Managed Hosts:

The command module allows administrators to run arbitrary commands on the command line of managed hosts. The command to be run is specified as an argument to the module using the -a option. For example, the following command runs the hostname command on the managed hosts referenced by the webserver  host pattern.

vagrant@vm1:~/ansible$ ansible webserver -m command -a /usr/bin/hostname -u gautam

vm2 | CHANGED | rc=0 >>

vm2

The previous ad hoc command example returned two lines of output for each managed host. The first line is a status report, showing the name of the managed host that the ad hoc operation ran on, as well as the outcome of the operation. The second line is the output of the command executed remotely using the Ansible command module.

For better readability and parsing of ad hoc command output, administrators might find it useful to have a single line of output for each operation performed on a managed host. Use the -o option to display the output of Ansible ad hoc commands in a single line format.

vagrant@vm1:~/ansible$ ansible webserver -m command -a /usr/bin/hostname -u gautam -o

vm2 | CHANGED | rc=0 | (stdout) vm2

The command module allows administrators to quickly execute remote commands on managed hosts. These commands are not processed by the shell on the managed hosts. As such, they cannot access shell environment variables or perform shell operations, such as redirection and piping.

For situations where commands require shell processing, administrators can use the shell module. Like the command module, you pass the commands to be executed as arguments to the module in an ad hoc command. Ansible then executes the command remotely on the managed hosts. Unlike the command module, the commands are processed through a shell on the managed hosts. Therefore, shell environment variables are accessible and shell operations such as redirection and piping are also available for use.
The following example illustrates the difference between the command and shell modules. If you try to execute the built-in Bash command set with these two modules, it only succeeds with the shell module.

vagrant@vm1:~/ansible$ ansible webserver -m command -a set

vm2 | FAILED | rc=2 >>

[Errno 2] No such file or directory: b’set’

vagrant@vm1:~/ansible$ ansible webserver -m shell -a set

vm2 | CHANGED | rc=0 >>

HOME=’/root’

IFS=’ 

LANG=’en_US.UTF-8′

LOGNAME=’root’

MAIL=’/var/mail/root’

OPTIND=’1′

PATH=’/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin’

PPID=’3137′

PS1=’# ‘

PS2=’> ‘

PS4=’+ ‘

PWD=’/home/gautam’

SHELL=’/bin/bash’

SUDO_COMMAND=’/bin/sh -c echo BECOME-SUCCESS-cvjvoevliquvtsslclumkixqldnfqbpm ; /usr/bin/python3 /home/gautam/.ansible/tmp/ansible-tmp-1761056869.9317095-2374-111964898152141/AnsiballZ_command.py’

SUDO_GID=’1001′

SUDO_UID=’1001′

SUDO_USER=’gautam’

TERM=’xterm-256color’

USER=’root’

Both command and shell modules require a working Python installation on the managed host. A third module, raw, can run commands directly using the remote shell, bypassing the module subsystem. This is useful when managing systems that cannot have Python installed (for example, a network router). It can also be used to install Python on a host.

CONFIGURING CONNECTIONS FOR AD HOC COMMANDS:

The directives for managed host connections and privilege escalation can be configured in the Ansible configuration file, and they can also be defined using options in ad hoc commands. When defined using options in ad hoc commands, they take precedence over the directive configured in the Ansible configuration file. The following table shows the analogous command-line options for each configuration file directive.

Ansible Command-line Options

CONFIGURATION FILE DIRECTIVES COMMAND-LINE OPTION
inventory -i
remote_user -u
become --become,-b
become_method --become-method
become_user --become-user
become_ask_pass --ask-become-pass,-k

You can refer also Ansible public documentation https://docs.ansible.com/projects/ansible/latest/command_guide/intro_adhoc.html to know more about it.

Please visit our official website https://linuxgktech.com/ansible/ to know more about Ansible. 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top