📖 Guide
Ansible Commands Cheat Sheet — Complete Reference
Every Ansible command you need, from ad-hoc commands to playbooks, roles, vault, and Galaxy. Searchable and organized.
146 commands across 12 categories
Ad-Hoc CommandsPlaybook ExecutionInventoryModules — File, Copy & TemplateModules — Service & PackageModules — User, Command & ShellVariables & FactsRolesVaultGalaxyConditionals & LoopsHandlers & Tags
Ad-Hoc Commands
| Command | Description |
|---|---|
ansible all -m ping | Ping all hosts to check connectivity |
ansible <group> -m pinge.g. ansible webservers -m ping | Ping a specific host group |
ansible all -m shell -a 'uptime' | Run a shell command on all hosts |
ansible all -m command -a 'df -h' | Run a command (no shell features like pipes) |
ansible all -a 'free -m' | Shorthand for command module (default) |
ansible all -m setup | Gather facts from all hosts |
ansible all -m setup -a 'filter=ansible_os_family' | Gather specific facts only |
ansible all -b -m apt -a 'name=nginx state=present'e.g. ansible webservers -b -m apt -a 'name=nginx state=latest' | Install a package with become (sudo) |
ansible all -m copy -a 'src=/tmp/file dest=/tmp/file' | Copy a file to remote hosts |
ansible all -m file -a 'path=/tmp/test state=directory' | Create a directory on remote hosts |
ansible all -i 'host1,host2,' -m ping | Use an inline comma-separated inventory |
ansible all --limit 'host1' | Limit execution to specific host(s) |
ansible all -m service -a 'name=nginx state=restarted' -b | Restart a service on all hosts |
Playbook Execution
| Command | Description |
|---|---|
ansible-playbook playbook.yml | Run a playbook |
ansible-playbook playbook.yml -i inventory.ini | Run with a specific inventory file |
ansible-playbook playbook.yml --check | Dry run — show changes without applying |
ansible-playbook playbook.yml --diff | Show file diffs for changes |
ansible-playbook playbook.yml --check --diff | Dry run with diffs |
ansible-playbook playbook.yml -v | Verbose output (-vv, -vvv, -vvvv for more) |
ansible-playbook playbook.yml --limit 'webservers' | Limit to specific hosts or groups |
ansible-playbook playbook.yml --tags 'deploy' | Run only tasks with specific tags |
ansible-playbook playbook.yml --skip-tags 'debug' | Skip tasks with specific tags |
ansible-playbook playbook.yml -e 'var=value'e.g. ansible-playbook deploy.yml -e 'env=production version=2.1' | Pass extra variables |
ansible-playbook playbook.yml --start-at-task 'Install nginx' | Start execution at a specific task |
ansible-playbook playbook.yml --step | Step through tasks one at a time (confirm each) |
ansible-playbook playbook.yml --list-tasks | List all tasks without executing |
ansible-playbook playbook.yml --list-hosts | List all targeted hosts without executing |
ansible-playbook playbook.yml --list-tags | List all available tags |
ansible-playbook playbook.yml --syntax-check | Check playbook syntax without running |
ansible-playbook playbook.yml --forks 20 | Set number of parallel processes (default 5) |
ansible-playbook playbook.yml --become | Run operations with become (sudo) |
ansible-playbook playbook.yml --ask-become-pass | Prompt for sudo password |
Inventory
| Command | Description |
|---|---|
ansible-inventory --list | List all hosts in inventory as JSON |
ansible-inventory --graph | Show inventory as a tree graph |
ansible-inventory --host <hostname> | Show variables for a specific host |
[webservers]\nhost1 ansible_host=192.168.1.10 | INI inventory — define a group with host vars |
[webservers:vars]\nhttp_port=80 | INI inventory — set group variables |
[all:children]\nwebservers\ndbservers | INI inventory — define parent group with children |
ansible_user=deploy | Host variable — SSH user for connection |
ansible_port=2222 | Host variable — SSH port |
ansible_ssh_private_key_file=~/.ssh/deploy | Host variable — SSH private key path |
ansible_become=yes | Host variable — enable privilege escalation |
ansible_python_interpreter=/usr/bin/python3 | Host variable — Python interpreter path |
Modules — File, Copy & Template
| Command | Description |
|---|---|
file: path=/etc/app state=directory mode='0755' | Create a directory with permissions |
file: path=/tmp/old state=absent | Delete a file or directory |
file: src=/etc/file dest=/tmp/link state=link | Create a symbolic link |
file: path=/var/log/app.log owner=app group=app mode='0644' | Set ownership and permissions |
copy: src=files/app.conf dest=/etc/app/app.conf | Copy a file from control node to remote |
copy: content='Hello World' dest=/tmp/hello.txt | Create a file with inline content |
copy: src=app.conf dest=/etc/app.conf backup=yes | Copy file and create backup of original |
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf | Render a Jinja2 template to remote host |
template: src=app.env.j2 dest=/etc/app/.env owner=app mode='0600' | Template with ownership and permissions |
fetch: src=/var/log/syslog dest=/tmp/logs/ flat=yes | Fetch a file from remote to control node |
Modules — Service & Package
| Command | Description |
|---|---|
service: name=nginx state=started | Start a service |
service: name=nginx state=stopped | Stop a service |
service: name=nginx state=restarted | Restart a service |
service: name=nginx state=reloaded | Reload a service configuration |
service: name=nginx enabled=yes | Enable a service to start on boot |
systemd: name=app daemon_reload=yes state=restarted | Reload systemd daemon and restart service |
apt: name=nginx state=present | Install a package (Debian/Ubuntu) |
apt: name=nginx state=latest | Install or upgrade to latest version |
apt: name=nginx state=absent | Remove a package |
apt: update_cache=yes cache_valid_time=3600 | Update apt cache if older than 1 hour |
yum: name=httpd state=present | Install a package (RHEL/CentOS) |
package: name=curl state=present | Generic package module (auto-detects manager) |
pip: name=flask state=present | Install a Python package with pip |
pip: requirements=/app/requirements.txt virtualenv=/app/venv | Install from requirements.txt into virtualenv |
Modules — User, Command & Shell
| Command | Description |
|---|---|
user: name=deploy state=present shell=/bin/bash | Create a user account |
user: name=deploy groups=sudo append=yes | Add user to supplementary groups |
user: name=olduser state=absent remove=yes | Remove a user and their home directory |
user: name=deploy generate_ssh_key=yes | Create user with SSH key pair |
group: name=app state=present | Create a group |
authorized_key: user=deploy key="{{ lookup('file','~/.ssh/id_rsa.pub') }}" | Add an SSH authorized key |
command: /usr/bin/app --init | Run a command (no shell processing) |
command: /usr/bin/app creates=/var/lib/app/init.done | Run only if a file does not exist |
shell: cat /var/log/app.log | grep ERROR | wc -l | Run with full shell features (pipes, redirects) |
shell: source /etc/profile && app status | Run with shell sourcing |
script: scripts/setup.sh | Transfer and execute a local script on remote |
raw: yum install -y python3 | Execute raw SSH command (no Python needed) |
Variables & Facts
| Command | Description |
|---|---|
vars:\n http_port: 80 | Define variables in a play |
vars_files:\n - vars/main.yml | Load variables from an external file |
vars_prompt:\n - name: password\n prompt: "Enter password" | Prompt user for variable input |
{{ ansible_hostname }} | Access the hostname fact |
{{ ansible_default_ipv4.address }} | Access the default IPv4 address fact |
{{ ansible_distribution }} | Access the OS distribution name |
{{ ansible_memtotal_mb }} | Access total memory in MB |
set_fact: app_path=/opt/{{ app_name }} | Set a fact dynamically during execution |
register: result | Register task output as a variable |
debug: var=result.stdout | Print a variable for debugging |
debug: msg="Port is {{ http_port }}" | Print a message with variable interpolation |
{{ lookup('env', 'HOME') }} | Look up an environment variable |
{{ lookup('file', '/etc/hostname') }} | Look up contents of a file |
{{ hostvars['db1']['ansible_host'] }} | Access another host's variables |
{{ group_names }} | List of groups the current host belongs to |
Roles
| Command | Description |
|---|---|
ansible-galaxy init myrole | Create a new role directory structure |
roles:\n - webserver | Include a role in a playbook |
roles:\n - role: webserver\n vars:\n port: 8080 | Include a role with variables |
include_role: name=common | Dynamically include a role in a task |
import_role: name=common | Statically import a role in a task |
roles/myrole/tasks/main.yml | Role tasks entry point |
roles/myrole/handlers/main.yml | Role handlers entry point |
roles/myrole/templates/ | Role templates directory |
roles/myrole/files/ | Role static files directory |
roles/myrole/vars/main.yml | Role variables (high priority) |
roles/myrole/defaults/main.yml | Role default variables (low priority, easily overridden) |
roles/myrole/meta/main.yml | Role metadata and dependencies |
Vault
| Command | Description |
|---|---|
ansible-vault create secrets.yml | Create a new encrypted file |
ansible-vault edit secrets.yml | Edit an encrypted file in place |
ansible-vault view secrets.yml | View contents of an encrypted file |
ansible-vault encrypt vars.yml | Encrypt an existing file |
ansible-vault decrypt vars.yml | Decrypt an encrypted file |
ansible-vault rekey secrets.yml | Change the vault password |
ansible-vault encrypt_string 'secret' --name 'db_pass' | Encrypt a single string for use in YAML |
ansible-playbook site.yml --ask-vault-pass | Run playbook and prompt for vault password |
ansible-playbook site.yml --vault-password-file ~/.vault_pass | Run playbook with vault password file |
Galaxy
| Command | Description |
|---|---|
ansible-galaxy install geerlingguy.docker | Install a role from Ansible Galaxy |
ansible-galaxy install -r requirements.yml | Install roles from a requirements file |
ansible-galaxy list | List installed roles |
ansible-galaxy remove geerlingguy.docker | Remove an installed role |
ansible-galaxy collection install community.general | Install a collection |
ansible-galaxy collection list | List installed collections |
ansible-galaxy role search elasticsearch | Search Galaxy for roles |
ansible-galaxy role info geerlingguy.docker | Show info about a role |
Conditionals & Loops
| Command | Description |
|---|---|
when: ansible_os_family == 'Debian' | Run task only on Debian-based systems |
when: result.rc != 0 | Run task when previous task failed |
when: my_var is defined | Run task only if variable is defined |
when: my_var | bool | Run task when variable is truthy |
when: inventory_hostname in groups['webservers'] | Run task for hosts in a specific group |
when:\n - ansible_distribution == 'Ubuntu'\n - ansible_distribution_version == '22.04' | Multiple conditions (AND logic) |
when: is_prod or is_staging | OR condition |
loop:\n - nginx\n - postgresql\n - redis | Loop over a list of items |
loop: "{{ packages }}" | Loop over a variable list |
with_items:\n - { name: 'alice', groups: 'admin' }\n - { name: 'bob', groups: 'dev' } | Loop over list of dicts (legacy syntax) |
loop: "{{ query('fileglob', 'files/*.conf') }}" | Loop over files matching a glob pattern |
until: result.stdout == 'ready'\nretries: 10\ndelay: 5 | Retry a task until condition is met |
📖 Free, searchable command reference. Bookmark this page for quick access.