You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Ad-hoc commands are one-line Ansible commands that let you perform quick tasks without writing a playbook. They are ideal for testing, troubleshooting, and one-off operations. Every ad-hoc command uses a module --- the building block of all Ansible automation.
ansible <host-pattern> -i <inventory> -m <module> -a "<arguments>"
| Flag | Description |
|---|---|
-i | Path to the inventory file |
-m | The module to use |
-a | Arguments to pass to the module |
-b | Enable become (privilege escalation / sudo) |
-u | Remote user |
-k | Prompt for SSH password |
-K | Prompt for become (sudo) password |
-f | Number of parallel forks (default: 5) |
-v | Verbose output (-vv, -vvv, -vvvv for more detail) |
The ping module is the simplest way to verify connectivity --- it is not an ICMP ping, but an Ansible-level connectivity test:
# Test all hosts
ansible all -m ping
# Test a specific group
ansible webservers -m ping
Runs a command on the managed node. This is the default module if -m is not specified:
ansible webservers -a "uptime"
ansible webservers -a "df -h"
ansible webservers -a "free -m"
Note: The
commandmodule does not support shell features like pipes, redirects, or environment variables. Use theshellmodule for those.
Like command, but runs through /bin/sh, supporting pipes and redirects:
ansible webservers -m shell -a "cat /var/log/syslog | tail -20"
ansible webservers -m shell -a "echo $HOSTNAME"
Copy files from the control node to managed nodes:
# Copy a file
ansible webservers -m copy -a "src=/local/path/app.conf dest=/etc/app/app.conf owner=root mode=0644"
# Create a file with inline content
ansible webservers -m copy -a "content='Hello World' dest=/tmp/hello.txt"
Manage files, directories, and symlinks:
# Create a directory
ansible webservers -m file -a "path=/opt/app state=directory owner=deploy mode=0755"
# Create a symlink
ansible webservers -m file -a "src=/opt/app/current dest=/opt/app/latest state=link"
# Delete a file
ansible webservers -m file -a "path=/tmp/old-file.txt state=absent"
Manage packages on Debian-based systems:
# Install a package
ansible webservers -b -m apt -a "name=nginx state=present"
# Install latest version
ansible webservers -b -m apt -a "name=nginx state=latest"
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.