diff --git a/README.md b/README.md index ad8e5a9..dde1ffc 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,13 @@ -## README.md +# Ansible Study Guide -# Documentation Project Structure +This repository is a hands‑on learning playground for Ansible. +The documents below walk you through the core concepts, common pitfalls, and practical patterns +in a “problem‑situation‑solution” format that’s easy to digest. -This documentation project provides comprehensive information about various topics related to Ansible. The following sections are included: +- [Introduction](#introduction) +- [Key Features](#key-features) +- [Core Concepts](#core-concepts) +- [Quick‑Start](#quick-start) +- …and much more! -## 1. Introduction -- [Introduction](intro.md) -- [Quick Start](quick-start.md) -- [Core Concepts](core-concepts.md) -- [Key Features](key-features.md) - -## 2. Basic Concepts -- [Variables](variables.md) -- [Conditionals](conditionals.md) -- [Loops](loops.md) -- [Templates](templates.md) - -## 3. Advanced Topics -- [Vault](vault.md) -- [Roles](roles.md) -- [Handlers](handlers.md) -- [Delegation](delegation.md) - -## 4. Best Practices -- [Best Practices](best-practices.md) - -## 5. Error Handling -- [Error Handling](error-handling.md) - -## 6. Async Tasks -- [Async](async.md) - -## 7. Dynamic Inventory -- [Dynamic Inventory](dynamic-inventory.md) - -## 8. Galaxy -- [Galaxy](galaxy.md) - -## 9. Modules Reference -- [Modules Reference](modules-reference.md) - -## 10. Ad-hoc Commands -- [Ad-hoc Commands](ad-hoc-commands.md) - -## 11. Check Mode -- [Check Mode](check-mode.md) - -## 12. Tags -- [Tags](tags.md) - -## 13. Glossary - -This documentation project is organized to provide a comprehensive understanding of Ansible's features and best practices. Each section provides detailed information about specific topics, allowing users to navigate and understand the material efficiently. \ No newline at end of file +> **Tip** – If you’re new to Ansible, start at the **Intro** and progress gradually. diff --git a/ad-hoc-commands.md b/ad-hoc-commands.md index c7c4f54..f5594ba 100644 --- a/ad-hoc-commands.md +++ b/ad-hoc-commands.md @@ -1,11 +1,20 @@ -## Ad-Hoc Commands +# Ad‑hoc Commands + +**Problem** – “I need to run a quick check or command on a host without writing a full playbook.” + +**Solution** – Use the `ansible` command with the `-m` (module) option. + +| Use‑case | Command | What it does | +|----------|---------|--------------| +| Ping a host | `ansible host1 -m ping` | Verifies connectivity. | +| List services | `ansible host1 -m shell -a 'systemctl list-units --type=service'` | Executes a shell command. | +| Gather facts | `ansible all -m setup` | Collects system information. | +| Run playbook file only | `ansible-playbook site.yml` | Executes the full playbook. | + +**Example – Quick package check** ```bash -ansible all -m ping -ansible all -m command -a "uptime" -ansible webserver -m apt -a "name=vim state=present" +ansible web2 -m yum -a "name=nginx state=latest" ``` -Ansible is ideal for orchestrating infrastructure as code across cloud, on-premise, and hybrid environments. - ---- +> **Tip** – Add `-vv` for verbose output to see command execution details. diff --git a/async.md b/async.md index 9e48a7c..7899d4a 100644 --- a/async.md +++ b/async.md @@ -1,25 +1,75 @@ -## Async +## Asynchronous Tasks in Ansible -Run tasks asynchronously to avoid blocking: +### Problem: Blocking Long-Running Tasks + +When executing long-running tasks (e.g., backups, migrations, or API calls), Ansible's default behavior blocks the playbook execution until the task completes. This creates delays and reduces efficiency, especially when managing large infrastructure. + +### Solution: Async Mode + +Ansible's async mode allows tasks to run asynchronously, freeing the playbook to continue executing other tasks while the async operation completes in the background. ### Key Parameters -- `async`: Maximum number of seconds to wait for the task to complete -- `poll`: Number of seconds to wait between checks (0 means no polling) - -### Example Playbook +- `async`: Maximum number of seconds to wait for the task to complete (e.g., `async: 30` waits 30 seconds) +- `poll`: Number of seconds between status checks (0 means no polling) +### Example: Database Migration ```yaml -- name: Restart service asynchronously - service: - name: apache2 +- name: Initiate database migration + mysql_db: + name: production_db state: restarted - async: 10 - poll: 0 + async: 60 + poll: 5 -# Check async task status: -# ansible-playbook site.yml --check -``` +- name: Check migration status + async_status: + jid: "{{ async_jid }}" + register: migration_result + +- name: Fail task if migration failed + fail: + msg: "Database migration failed: {{ migration_result.stdout }}" + when: migration_result.failed +""" + +### Best Practices +1. Use async for I/O-bound tasks (e.g., API calls, file transfers) +2. Combine with `ignore_errors: yes` for resilient workflows +3. Always register async job IDs (`async_jid`) for monitoring +4. Use `--check` flag to simulate async operations without executing + +### Monitoring Async Tasks +Use the `async_status` module to track progress: +```yaml +- name: Monitor async task + async_status: + jid: "{{ async_jid }}" + register: task_result + +- name: Display task status + debug: + msg: "Task status: {{ task_result.status }}" +""" + +### Troubleshooting +- Use `--verbosity=2` to see detailed async output +- Check the `ansible_async` directory for job logs +- Verify network connectivity for remote tasks +- Ensure correct credentials for authenticated operations + +### When to Use Async +- API calls with long response times +- File transfers between nodes +- Scheduled maintenance windows +- Operations requiring user intervention + +### When Not to Use Async +- Simple, fast operations +- Tasks requiring immediate feedback +- Operations with strict timing requirements + +Async mode transforms Ansible from a sequential executor to a parallel orchestrator, enabling more efficient management of complex infrastructure workflows. ### Best Practices diff --git a/check-mode.md b/check-mode.md index cc4c8d0..c62b802 100644 --- a/check-mode.md +++ b/check-mode.md @@ -1,14 +1,69 @@ -## Check Mode +# Check Mode -Run playbooks in simulation mode without making changes: +## Why It Matters +In production or when iterating on a large inventory, you often want to know *what* an Ansible playbook would do **without** actually applying any changes. Guessing can lead to downtime, broken services, or costly rollbacks. Check mode gives you a safe “dry‑run” that reports what would change, allowing you to spot mistakes before they hit reality. +## Problem • Solution Flow +| Problem | How check mode solves it | +|---|---| +| **Unsure if a task will break services** | Run with `--check` and inspect the `changed` flag before you hit a live host. | +| **Running a new module on many nodes** | Ansible tells you which hosts *would* be affected, helping you validate scope early. | +| **Complex variable sets that might collide** | Check mode can surface potential conflicts without touching files or services. | +| **Auditing compliance** | Generates a report of intended changes, useful for audit trails. | + +## How It Works +1. **Modules that support check mode** return a `changed` status of *false* and may provide a simulated diff. The default is to let the module run as normal – many built‑in modules honour the global `--check` flag. +2. **Task‑level override** – you can set `check_mode: yes` on a task to force that task into check mode even if the playbook is run normally. +3. **Playbook‑level flag** – running the entire playbook with `ansible‑playbook --check` (short‐hand `-C`) tells Ansible to execute all modules in simulation mode. + +## Practical Example ```yaml -- name: Restart service (check mode) - service: - name: apache2 - state: restarted - check_mode: yes +- hosts: webservers + gather_facts: false + tasks: + - name: Ensure Apache is started + service: + name: apache2 + state: started + # Even if we forget `--check`, this task will be skipped in check mode + check_mode: yes -# Run with check mode: -# ansible-playbook site.yml --check -``` \ No newline at end of file + - name: Update configuration file + copy: + dest: /etc/apache2/sites-available/000-default.conf + content: "{{ apache_conf }}" + owner: root + group: root + mode: '0644' + # Default behaviour – will run in check mode if the playbook is invoked with --check +``` + +Run: `ansible-playbook site.yml -C` or `ansible-playbook site.yml --check`. + +You’ll see output similar to: +``` +TASK [Update configuration file] (skipping because of --check) +... changed: false +``` +The diff section (if the module supports it) will show the line‑by‑line differences. + +## Tips & Gotchas +- **Not all modules support check mode** – e.g., `service` may report *changed* even in ``--check``. Check the module docs or run a small test. +- **Dependencies between tasks** – a task that *requires* a successful change will *not* run in check mode. Use `--diff` to verify the intent. +- **Verbose output** – `-vvv` shows the value‑of‐variables and the simulated changes, useful for debugging. +- **Ad‑hoc commands** – you can also use `--check` with `ansible -m shell -a "..."`. +- **Idempotence** – if a playbook is truly idempotent, running it in check mode should report *no changes* after the first pass. + +## Common Use Cases +1. **CI/CD pipelines** – add a check‑mode job to validate that the configuration will apply correctly before the actual deployment. +2. **Policy enforcement** – generate a dry‑run report to confirm that no unauthorized package updates will occur. +3. **Learning & teaching** – students can see the impact of changes before committing, reinforcing the concept of desired state. + +## Further Reading +- [Ansible documentation – Running in Check Mode](https://docs.ansible.com/ansible/latest/user_guide/playbooks_check_mode.html) +- [Module reference – Check mode support](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/index.html) +- [Troubleshooting Check Mode Issues](https://docs.ansible.com/ansible/latest/user_guide/troubleshooting.html#check-mode-issues) + +--- + +*Happy dry‑running!* \ No newline at end of file