Ansible ad-hoc commands run single tasks without a playbook. Mastering the core modules — apt, copy, template, service, user, file, command — covers 90% of automation needs.
| Item | Syntax / Value | Description |
|---|---|---|
| ansible -m ping | ansible all -i inventory -m ping | Test connectivity to all hosts |
| ansible -m command | ansible webservers -m command -a 'uptime' | Run a command on hosts |
| ansible -m shell | ansible webservers -m shell -a 'df -h | grep /dev' | Run shell command (supports pipes) |
| ansible -m apt | ansible webservers -m apt -a 'name=nginx state=present' -b | Install package |
| ansible -m copy | ansible webservers -m copy -a 'src=file.txt dest=/tmp/' | Copy file to hosts |
| ansible -m fetch | ansible webservers -m fetch -a 'src=/etc/hostname dest=./hosts/' | Fetch file from hosts |
| ansible -m setup | ansible web01 -m setup | Gather all facts about a host |
| ansible -m setup -a filter | ansible web01 -m setup -a 'filter=ansible_*ip*' | Filter facts |
| apt module | name: / state: present/absent/latest / update_cache: | Install/remove packages (Debian/Ubuntu) |
| yum/dnf module | name: / state: present/absent/latest | Install/remove packages (RHEL/CentOS) |
| copy module | src: / dest: / owner: / group: / mode: | Copy file from controller to hosts |
| template module | src: jinja2.j2 / dest: /path/config | Render Jinja2 template and copy |
| file module | path: / state: file/directory/absent/link / mode: | Manage files and directories |
| service module | name: / state: started/stopped/restarted / enabled: | Manage system services |
| user module | name: / state: present/absent / groups: / shell: | Manage system users |
| group module | name: / state: present/absent / gid: | Manage system groups |
| command module | cmd: / creates: / removes: / chdir: | Run command (no shell — safer) |
| shell module | cmd: / executable: /bin/bash | Run shell command (supports pipes/redirects) |
| lineinfile module | path: / line: / regexp: / state: | Ensure line present/absent in file |
| blockinfile module | path: / block: / marker: | Insert/update block of text in file |
| replace module | path: / regexp: / replace: | Regex find-and-replace in file |
| uri module | url: / method: / status_code: / body: | HTTP requests from Ansible |
| get_url module | url: / dest: / checksum: | Download file from URL |
| unarchive module | src: / dest: / remote_src: | Extract tar/zip archives |
| git module | repo: / dest: / version: | Clone or update git repository |
| cron module | name: / job: / minute: / hour: / day: | Manage cron jobs |
| debug module | msg: / var: | Print debug messages |
| set_fact module | key: value | Set variables dynamically |
| include_tasks | include_tasks: other_tasks.yml | Dynamically include task file |
| import_tasks | import_tasks: other_tasks.yml | Statically import task file |
| Jinja2 vars | {{ variable_name }} | Variable interpolation |
| Jinja2 filter | {{ var | upper | default('N/A') }} | Transform variable value |
| Jinja2 condition | {% if condition %}...{% endif %} | Conditional in template |
| Jinja2 loop | {% for item in list %}...{% endfor %} | Loop in template |
# ── Ad-hoc commands ──────────────────────────────────────────
# Test connectivity
ansible all -i inventory -m ping
# Run command on all web servers
ansible webservers -i inventory -m command -a "uptime" -u ubuntu
# Get disk usage
ansible all -i inventory -m shell -a "df -h | tail -1" -b
# Install package
ansible webservers -i inventory -m apt \
-a "name=apache2 state=present update_cache=yes" -b
# Copy file
ansible webservers -i inventory -m copy \
-a "src=index.html dest=/var/www/html/index.html owner=www-data mode=0644" -b
# Restart service
ansible webservers -i inventory -m service \
-a "name=apache2 state=restarted" -b
# Create user
ansible all -i inventory -m user \
-a "name=deploy groups=www-data shell=/bin/bash state=present" -b
# Get all facts
ansible web01 -i inventory -m setup | head -50
# ── Jinja2 Templates ──────────────────────────────────────────
# templates/apache.conf.j2
cat > /tmp/apache.conf.j2 << 'TEMPLATE'
# Generated by Ansible — {{ ansible_managed }}
# Host: {{ inventory_hostname }}
# Date: {{ ansible_date_time.date }}
<VirtualHost *:{{ app_port | default(80) }}>
ServerName {{ server_name | default(ansible_fqdn) }}
ServerAdmin {{ admin_email | default("webmaster@" + ansible_domain) }}
DocumentRoot {{ app_dir }}
{% if enable_https | default(false) %}
# Redirect HTTP to HTTPS
RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
{% endif %}
{% for alias in server_aliases | default([]) %}
ServerAlias {{ alias }}
{% endfor %}
<Directory {{ app_dir }}>
Options +ExecCGI {% if disable_indexes | default(true) %}-Indexes{% endif %}
AllowOverride {{ allow_override | default('All') }}
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/{{ app_name }}_error.log
CustomLog ${APACHE_LOG_DIR}/{{ app_name }}_access.log \
{% if log_format is defined %}{{ log_format }}{% else %}combined{% endif %}
</VirtualHost>
TEMPLATE
# ── Common Playbook Patterns ──────────────────────────────────
cat > /tmp/patterns.yml << 'YAML'
---
- name: Deployment patterns
hosts: webservers
become: true
tasks:
# Register + debug
- name: Get disk usage
ansible.builtin.shell: df -h / | awk 'NR==2{print $5}'
register: disk_usage
changed_when: false
- name: Show disk usage
ansible.builtin.debug:
msg: "{{ inventory_hostname }} disk: {{ disk_usage.stdout }}"
# Conditional
- name: Install Apache (Debian only)
ansible.builtin.apt:
name: apache2
state: present
when: ansible_os_family == 'Debian'
- name: Install httpd (RedHat only)
ansible.builtin.yum:
name: httpd
state: present
when: ansible_os_family == 'RedHat'
# Loop with dict
- name: Create app directories
ansible.builtin.file:
path: "{{ item.path }}"
owner: "{{ item.owner }}"
mode: "{{ item.mode }}"
state: directory
loop:
- { path: /var/www/html, owner: www-data, mode: '0755' }
- { path: /var/log/app, owner: www-data, mode: '0750' }
- { path: /etc/app/conf.d, owner: root, mode: '0755' }
# Block with rescue
- name: Deploy application
block:
- name: Pull latest code
ansible.builtin.git:
repo: https://github.com/myorg/myapp.git
dest: /var/www/html
version: main
- name: Restart service
ansible.builtin.service:
name: apache2
state: restarted
rescue:
- name: Rollback on failure
ansible.builtin.command: git -C /var/www/html checkout HEAD~1
- name: Notify on failure
ansible.builtin.debug:
msg: "Deployment failed on {{ inventory_hostname }} — rolled back"
YAML
echo "Patterns written to /tmp/patterns.yml"
# Run: ansible-playbook -i inventory patterns.yml -v