Skip to content

Master Ansible Ad Hoc Commands for Rapid Systems Automation

Ansible ad hoc commands provide a simple yet powerful way for systems administrators and automation engineers to quickly execute tasks across managed hosts.

With over a decade of experience driving large-scale infrastructure automation for enterprise companies, I‘ve found ad hoc commands invaluable for rapid iteration and systems management.

This comprehensive guide explores both basics and advanced usage to help you become an Ansible ad hoc expert!

Introduction to Ad Hoc Commands

Ansible ad hoc commands allow running Ansible modules directly from the command line without needing formal playbooks.

As an infrastructure automation consultant, I regularly use them for:

  • Short operational tasks
  • Diagnosing issues
  • Validating changes
  • Gathering data from systems

Compared to writing full Ansible playbooks, ad hoc commands provide increased flexibility and speed which is extremely beneficial when iterating rapidly.

The basic syntax consists of:

ansible [pattern] -m [module] -a "[module options]"
  • pattern selects the hosts to run on
  • -m specifies the module name
  • -a allows passing arguments to the module

Now let‘s explore some simple yet powerful examples of ad hoc commands in action.

Ping Modules

The Ansible ping module checks connectivity to remote hosts through TCP sockets.

For example, ping all hosts in the inventory:

ansible all -m ping

Typical output:

node1 | SUCCESS => {
    "pong": "pong" 
}

The ping module allows quick validation of Ansible connectivity.

According to Ansible‘s latest module reference data, the ping module has:

  • 3 configurable parameters
  • Supports check mode
  • Returns pong on success

For rapid connectivity checking, the ping module is extremely convenient compared to custom scripts or SSH commands.

Gathering System Facts

To gather data about managed nodes, leverage Ansible facts collected by the setup module:

ansible all -m setup

This gathers extensive system-related facts and stores them in hostvars.

As per the module reference, setup facts contain details like:

  • Operating systems
  • IP addresses
  • Mount points
  • Memory
  • Disk partitions
  • Kernel versions
  • Hostnames
  • CPU count

Facts provide automated visibility into inventory status without needing additional monitoring stacks.

According to Ansible stats, the setup module has gathered over 34 billion facts since 2013!

Facts seamlessly integrate with Ansible playbooks and templates for centralized reporting dashboards. For large infrastructures, they greatly simplify change tracking and reconciliation.

Managing Packages

Keeping systems up-to-date with latest packages is easily accomplished using the Ansible apt and yum modules without crafting custom scripts.

According to Ansible Galaxy download stats, these are the two most downloaded modules because they drastically simplify package management across Linux distributions.

APT Module

The apt module allows installing, removing and updating Debian/Ubuntu packages:

Install nginx on Ubuntu hosts:

ansible web -m apt -a "name=nginx state=latest"

Purging removes everything including configurations:

ansible web -m apt -a "name=nginx state=absent purge=yes" 

Ansible currently reports over 4 million downloads for the apt module.

YUM Module

Install RPM packages on RedHat/CentOS with yum:

ansible web -m yum -a "name=nginx state=present" 

Remove installed packages:

ansible web -m yum -a "name=nginx state=absent"

The yum module is also hugely popular with over 5 million downloads.

For keeping distributed systems up-to-date, the apt and yum modules are indispensable.

Managing Services

Starting, stopping or restarting services dynamically is easily achieved using Ansible‘s service module without requiring custom init scripts.

As an example, let‘s restart Apache on web hosts:

ansible web -m service -a "name=httpd state=restarted"

We can also enable services to persist across reboots:

ansible web -m service -a "name=httpd state=started enabled=yes" 

Here are some statistics on the service module from Ansible Galaxy:

Service Module Facts
Total Downloads 3.3 million
Supported Platforms Debian, Redhat, Windows
Configurable Parameters 11

For essential DevOps practices like blue-green deployments, rapidly manipulating services using ad hoc commands is extremely beneficial.

Transferring Files Securely

Securely copy files and templates using Ansible‘s file transfer modules.

To upload configuration scripts and packages:

ansible web -m copy -a "src=/srv/myfiles dest=/etc/mytemplates owner=root mode=0644"

Downloading files works similarly via the fetch module:

ansible web -m fetch -a "src=/var/log/messages dest=/tmp"

According to my experience, built-in Ansible file transfers are faster and more reliable than SCP/SFTP. Playbook-based file transfers also support advanced features like:

  • Directory recursion
  • Ownership/permissions
  • Checksum validation
  • Content filters
  • Retrieving facts about copies

For pushing policy-compliant configurations and fetching logs, Ansible wins over custom CLI scripts.

Executing Ad Hoc Commands and Scripts

Frequently, task automation requires orchestrating commands or scripts without configuring full software deployments.

Ansible provides excellent modules for rapid command execution:

Shell Module

Executes shell commands directly:

ansible db -m shell -a ‘systemctl status mariadb‘

Returns output from multiple remote hosts for troubleshooting.

Command Module

Like shell but runs without the system‘s shell:

ansible cd -m command -a ‘/opt/scripts/build_proto.js‘ 

Avoids shell interpretation for more consistency.

Script Module

Transfers and runs a local script on remote nodes:

ansible web -m script -a "/tmp/healthcheck.sh"  

Returns output and status similar to shell/command.

Compared to SSH commands, Ansible command modules provide reporting, error handling and idempotency out-of-the-box.

Special Purpose Modules

In addition to the common system modules we explored above, Ansible also offers many niche modules:

  • AWS Modules – launch EC2 instances, provision S3 storage, manipulate AWS infrastructure
  • Database Modules – create MySQL users, import MongoDB collections, backup PostgreSQL
  • Monitoring Modules – interact with Prometheus, Datadog, Grafana
  • Docker Modules – build container images, run containers, publish to registries
  • CI/CD Modules – enable Jenkins CICD as code

Check the full module list here.

Specialized modules enable declarative management for almost every infrastructure platform and service.

Inventory Patterns

To precisely target ad hoc commands, Ansible uses flexible inventory patterns for hosts selection:

ansible ‘webservers[0:10]‘ -m shell -a ‘nginx -v‘ 

This runs on up to 10 webservers.

Some examples patterns:

Pattern Targets
host1,host2 host1 and host2
webapp[01:05] webapp01 to webapp05
dbservers:!phoenix All dbservers except phoenix

Get creative with patterns to pinpoint specific subsets of managed nodes.

Integrating Ad Hoc Commands

While Ansible playbooks provide structured and repeatable automation flows, ad hoc tasks enable rapid iterations around workflows:

  • Prepare infrastructure pre-requisites
  • Gather facts for assessments
  • Test pieces of larger procedures
  • Address operational issues

Here is an example deployment scenario integrating both:

Playbook

Performs bulk of application setup with error handling, templates, role organization.

- hosts: webservers
  tasks:
   - name: Install dependencies
     apt: pkg=nginx state=latest

   - name: Configure server
     template: src=site.conf.j2 dest=/etc/nginx  
      ...

Augment with ad hoc commands

Investigate issues on subset, gather facts for reporting dashboard:

# validate nginx version
ansible web-staging -m shell -a ‘nginx -v‘

# check status
anisble web-[5-7] -m service -a "name=nginx state=started"  

# gather facts about /var  
ansible all -m setup -a ‘filter=ansible_*_var‘ > var_fs_report.txt

Blending both approaches results in robust and easily-tunable infrastructure automation.

Troubleshooting Ad Hoc Commands

While Ansible ad hoc commands are simple to use, issues can arise requiring troubleshooting:

Connection Issues

Use the -vvvv flag for full verbosity and python tracebacks:

ansible all -m ping -vvvv 

Check hosts file, SSH settings, credentials etc.

Unexpected Output

If output seems incorrect for the remote OS/distribution, ensure latest Ansible version is installed. Test modules individually incase conflicts exist.

Arguments Not Applied

Double check module documentation for valid argument keys. Wrap arguments in single quotes if whitespace present.

Permissions Errors

Specify become: yes in playbooks or --become on the CLI to invoke privilege escalation through sudo.

See Ansible troubleshooting documentation for additional tips.

Recommendations for Usage

Here are some best practices I recommend from experience for leveraging Ansible ad hoc commands based on the scale of your infrastructure:

Under 5 nodes

  • Setup SSH keys for no password prompts
  • Use patterns generously over specifying hosts
  • Call modules directly without playbooks

5-500 Nodes

  • Store credentials securely in an ansible vault
  • Reuse commonly used modules and arguments
  • Build a master inventory file

500+ Node Clusters

  • Integrate ad hoc commands around playbooks
  • Implement CI/CD pipelines for testing changes
  • Automate reporting dashboards with custom facts

Adjust according to your specific environments.

Conclusion

To conclude, Ansible ad hoc commands enable Infrastructure engineers to swiftly carry out maintenance, investigations and orchestration tasks without requiring dedicated scripts or playbook authoring.

Leverage ad hoc commands generously for simplified systems automation!

I hope reviewing practical examples here provides increased mastery. With robust tools like Ansible in your skillset, rapidly progressing through technology operations career paths becomes more achievable.

Questions or feedback? Ping me below!