home / skills / sigridjineth / hello-ansible-skills / ansible-playbook

ansible-playbook skill

/skills/ansible-playbook

This skill helps you develop and debug Ansible playbooks, convert shells to YAML, and resolve syntax, module, or variable issues.

npx playbooks add skill sigridjineth/hello-ansible-skills --skill ansible-playbook

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.4 KB
---
name: ansible-playbook
description: Use when creating playbooks, roles, or inventory files. Use when automating infrastructure with Ansible. Use when encountering YAML syntax errors, module failures, or variable precedence issues.
---

# Ansible Playbook Development

## Overview

Ansible playbooks declare desired system state rather than imperative commands. The core principle is idempotency: running a playbook multiple times produces the same result without unintended changes.

## When to Use

- Creating new playbooks or roles
- Writing inventory files
- Debugging YAML syntax errors
- Troubleshooting module parameter issues
- Understanding variable precedence
- Converting shell scripts to Ansible

## Quick Reference

### Project Structure

```
project/
├── ansible.cfg          # Configuration
├── inventory            # Host definitions
├── group_vars/          # Group variables
├── host_vars/           # Host-specific vars
├── roles/               # Reusable roles
└── playbooks/           # Playbook files
```

### Essential ansible.cfg

```ini
[defaults]
inventory = ./inventory
roles_path = ./roles
host_key_checking = False
stdout_callback = yaml

[privilege_escalation]
become = True
become_method = sudo
```

### Module Patterns

| Operation | Module | Key Parameters |
|-----------|--------|----------------|
| Create directory | `ansible.builtin.file` | `state: directory`, `mode`, `owner` |
| Copy file | `ansible.builtin.copy` | `src`, `dest`, `mode` |
| Template | `ansible.builtin.template` | `src`, `dest`, variables in `.j2` |
| Install package | `ansible.builtin.package` | `name`, `state: present` |
| Manage service | `ansible.builtin.service` | `name`, `state`, `enabled` |
| Run command | `ansible.builtin.command` | `cmd`, register result, set `changed_when` |

### Variable Precedence (lowest to highest)

1. Role defaults (`defaults/main.yml`)
2. Inventory group_vars
3. Inventory host_vars
4. Playbook vars
5. Role vars (`vars/main.yml`)
6. Task vars
7. Extra vars (`-e`)

### Handlers

```yaml
tasks:
  - name: Update config
    ansible.builtin.template:
      src: app.conf.j2
      dest: /etc/app.conf
    notify: Restart app

handlers:
  - name: Restart app
    ansible.builtin.service:
      name: app
      state: restarted
```

### Error Handling

```yaml
- block:
    - name: Risky operation
      ansible.builtin.command: /opt/app/upgrade.sh
  rescue:
    - name: Handle failure
      ansible.builtin.debug:
        msg: "Upgrade failed, rolling back"
  always:
    - name: Cleanup
      ansible.builtin.file:
        path: /tmp/upgrade.lock
        state: absent
```

## Common Mistakes

| Mistake | Fix |
|---------|-----|
| Using short module names | Always use FQCN: `ansible.builtin.copy` not `copy` |
| Hardcoded values | Extract to variables in `defaults/main.yml` |
| Missing `changed_when` on commands | Add `changed_when: "'created' in result.stdout"` |
| Forgetting handler flush | Use `meta: flush_handlers` when needed before dependent tasks |
| YAML indentation errors | Use 2 spaces, never tabs |
| Colon in unquoted string | Quote values containing `: ` |

## Verification Commands

```bash
ansible-playbook --syntax-check playbook.yml  # Check YAML
ansible-playbook --check playbook.yml         # Dry run
ansible-playbook --check --diff playbook.yml  # Show file changes
ansible-inventory --list                       # Verify inventory
ansible-inventory --host hostname             # Check host vars
```

Overview

This skill helps you develop, debug, and run Ansible playbooks, roles, and inventory files for infrastructure automation. It focuses on idempotent configuration, common module patterns, and practical checks to avoid typical YAML or runtime errors. Use it to convert shell scripts into reusable Ansible tasks and to enforce reliable, repeatable deployments.

How this skill works

The skill inspects playbook structure, variable placement, and module usage to surface issues like syntax errors, wrong FQCNs, or variable precedence mistakes. It suggests best-fit modules and patterns (file, copy, template, package, service, command), shows handler and error-handling examples, and recommends verification commands and config settings. It also guides on testing with --check, --diff, and inventory validation.

When to use it

  • Creating new playbooks, roles, or inventory layouts
  • Debugging YAML syntax and indentation errors
  • Troubleshooting module parameter failures or unexpected task results
  • Resolving variable precedence and scoping issues
  • Converting shell scripts into idempotent Ansible tasks

Best practices

  • Always use fully qualified collection names (e.g., ansible.builtin.copy) instead of short module names
  • Keep secrets and environment-specific values in group_vars/host_vars or use vault, not hardcoded values
  • Follow a consistent project structure (ansible.cfg, inventory, group_vars, host_vars, roles, playbooks)
  • Add changed_when/failed_when for commands and use handlers with notify and meta: flush_handlers when needed
  • Run ansible-playbook --syntax-check and --check --diff before applying changes to production

Example use cases

  • Create a role that installs packages, deploys config templates, and ensures services are enabled and started
  • Debug a playbook failing due to an unquoted string containing a colon or a YAML indentation issue
  • Convert a maintenance shell script into a playbook with idempotent file and service tasks
  • Implement a safe upgrade task using block/rescue/always for rollback and cleanup
  • Validate inventory and host-specific variables with ansible-inventory --list and --host hostname

FAQ

How do I check a playbook without making changes?

Run ansible-playbook --check --diff playbook.yml to simulate changes and preview diffs for file edits.

Where should I put default values and environment-specific overrides?

Put defaults in roles/<role>/defaults/main.yml and environment or host overrides in group_vars/ or host_vars/ respectively; extra vars (-e) have the highest precedence.

Why did a handler not run after a notified task?

Handlers run at the end of the play; use meta: flush_handlers before dependent tasks if you need immediate handler execution.