What are ad-hoc commands?
One-off module runs without writing a playbook — perfect for quick checks and small changes.
ansible <pattern> -m <module> -a "<arguments>"Flow for Day 1:
Ping → Command/Shell → Apt → Service → Setup → Mini project
1. Ping
ansible all -m ping2. Command / shell
ansible all -m command -a "uptime"
ansible all -m command -a "df -h"
ansible all -m shell -a "free -m | head"command | shell |
|---|---|
| No shell features | Pipes, redirects, $HOME work |
| Safer default | Use when you need a real shell |
3. Apt (+ --become)
--become runs with privilege escalation (sudo):
ansible all -m apt -a "update_cache=yes" --become
ansible all -m apt -a "name=nodejs,npm state=present" --become
ansible all -m shell -a "node -v"
ansible all -m apt -a "name=nodejs state=absent" --becomestate=present = ensure installed; state=absent = ensure removed.
4. Service
ansible all -m service -a "name=nginx state=started" --become
ansible all -m service -a "name=nginx state=stopped" --become
ansible all -m service -a "name=nginx state=restarted" --become
ansible all -m service -a "name=nginx enabled=yes" --become
ansible all -m service -a "name=nginx state=started enabled=yes" --become5. Setup (facts)
ansible all -m setup
ansible all -m setup -a "filter=ansible_distribution"Important concepts
| Idea | Meaning |
|---|---|
| Idempotency | Rerunning should not break state; modules skip when already correct |
--become | sudo / privilege escalation |
| Modules vs shell | Prefer modules (apt, service) over raw shell when possible |
Mini project — install Nginx on all EC2 hosts
Goal: every managed node serves Nginx.
# 1. Connectivity
ansible all -m ping
# 2. Install
ansible all -m apt -a "name=nginx state=present update_cache=yes" --become
# 3. Start
ansible all -m service -a "name=nginx state=started" --become
# 4. Enable on boot
ansible all -m service -a "name=nginx enabled=yes" --become
# 5. Status
ansible all -m command -a "systemctl is-active nginx" --become
# 6. Browser
# http://<MANAGED_PUBLIC_IP>You should see the default Nginx welcome page.
Tomorrow these same steps become an idempotent playbook — easier to version, review, and reuse.