Skip to main content
skill CX Codex

ansible-expert — Claude Code skill: what it does, how to install

Helps write Ansible playbooks, organize inventory files, and craft Jinja2 templates. Useful for server configuration and infrastructure automation.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add personamanagmentlayer/pcl --skill ansible-expert -a claude-code
Open on GitHub

What ansible-expert does

The skill guides the agent in writing declarative Ansible playbooks and managing target hosts. Inventory formats include INI and YAML. It provides patterns for dynamic inventory scripts using AWS EC2 APIs, alongside Jinja2 configuration templates. Error recovery patterns cover block, rescue, and always statements.

Variable evaluation follows 17 precedence levels — ranging from role defaults up to extra command-line flags. Terminal actions are strictly restricted to ansible, ansible-playbook, and ansible-galaxy commands. You must have Ansible installed on your host system via pip or OS packages, because the skill cannot run playbooks without the underlying binary.

What it helps with

  • build structured INI and YAML inventory files
  • write playbooks with fault tolerance using block and rescue
  • create Jinja2 service configuration templates
  • resolve variable precedence across roles and playbook runs

Example prompts for the agent

  • Generate a YAML inventory grouping web and database nodes with shared SSH variables
  • Write an idempotent playbook that starts my service and handles failures with rescue
  • Create a Jinja2 template for an application config with conditional cache settings

How to install ansible-expert

1Skills CLI (Vercel)

npx skills add personamanagmentlayer/pcl --skill ansible-expert -a claude-code

2Manually: put the files in place

~/.claude/skills/ansible-expert/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/ansible-expert/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about ansible-expert

How to install ansible-expert in Claude Code?

Run npx skills add personamanagmentlayer/pcl --skill ansible-expert -a claude-code. Alternatively, place the skill file directly into ~/.claude/skills/ansible-expert/SKILL.md.

What terminal tools can this skill execute?

Allowed Bash executions are limited to ansible, ansible-playbook, and ansible-galaxy. Other system commands are blocked by its tool permissions.

What does ansible-expert do?

It directs AI coding tools to write idiomatic Ansible automation, handle variables across 17 precedence levels, and construct inventory structures.

Source text

SKILL.md · Apache-2.0
---
name: ansible-expert
version: 1.1.0
description: >-
  Expert-level Ansible for configuration management, automation, and infrastructure as
  code. Use when the user mentions automation, configuration management, infrastructure as
  code, playbooks, or roles, or when the task involves Ansible Architecture, Basic
  Inventory, YAML Inventory, or Dynamic Inventory.
category: devops
tags: [ansible, automation, configuration-management, iac, playbooks, roles]
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash(ansible:*, ansible-playbook:*, ansible-galaxy:*)
---

# Ansible Expert

Expert guidance for Ansible - configuration management, application deployment, and IT automation using declarative YAML playbooks.

## Core Concepts

### Ansible Architecture

- Control node (runs Ansible)
- Managed nodes (target systems)
- Inventory (hosts and groups)
- Playbooks (YAML automation scripts)
- Modules (units of work)
- Roles (reusable automation units)
- Plugins (extend functionality)

### Key Features

- Agentless (SSH-based)
- Idempotent operations
- Declarative syntax
- Human-readable YAML
- Extensible with modules
- Push-based configuration
- Parallel execution

### Use Cases

- Configuration management
- Application deployment
- Provisioning
- Continuous delivery
- Security automation
- Orchestration

## Installation

```bash
# Using pip
pip install ansible

# Using apt (Ubuntu/Debian)
sudo apt update
sudo apt install ansible

# Using yum (RHEL/CentOS)
sudo yum install ansible

# Verify installation
ansible --version
```

## Inventory

### Basic Inventory (INI format)

```ini
# inventory/hosts
[webservers]
web1.example.com
web2.example.com ansible_host=192.168.1.10

[databases]
db1.example.com ansible_user=dbadmin
db2.example.com

[production:children]
webservers
databases

[production:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_connection=ssh
```

### YAML Inventory

```yaml
# inventory/hosts.yml
all:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
          ansible_host: 192.168.1.10
    databases:
      hosts:
        db1.example.com:
          ansible_user: dbadmin
        db2.example.com:
    production:
      children:
        webservers:
        databases:
      vars:
        ansible_python_interpreter: /usr/bin/python3
        ansible_connection: ssh
```

### Dynamic Inventory

```python
#!/usr/bin/env python3
# inventory/aws_ec2.py
import json
import boto3

def get_inventory():
    ec2 = boto3.client('ec2', region_name='us-east-1')
    response = ec2.describe_instances(Filters=[
        {'Name': 'instance-state-name', 'Values': ['running']}
    ])

    inventory = {
        '_meta': {'hostvars': {}},
        'all': {'hosts': []},
        'webservers': {'hosts': []},
        'databases': {'hosts': []},
    }

    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            ip = instance['PrivateIpAddress']
            tags = {tag['Key']: tag['Value'] for tag in instance.get('Tags', [])}

            inventory['all']['hosts'].append(ip)
            inventory['_meta']['hostvars'][ip] = {
                'ansible_host': ip,
                'instance_id': instance['InstanceId'],
                'instance_type': instance['InstanceType'],
            }

            # Group by role tag
            role = tags.get('Role', '')
            if role in inventory:
                inventory[role]['hosts'].append(ip)

    return inventory

if __name__ == '__main__':
    print(json.dumps(get_inventory(), indent=2))
```

## Templates (Jinja2)

```jinja2
{# templates/app.conf.j2 #}
# Application configuration for {{ app_name }}
# Generated by Ansible on {{ ansible_date_time.iso8601 }}

[server]
host = {{ ansible_default_ipv4.address }}
port = {{ app_port }}
workers = {{ ansible_processor_vcpus }}

[database]
host = {{ db_host }}
port = {{ db_port }}
name = {{ db_name }}
user = {{ db_user }}
password = {{ db_password }}

[cache]
enabled = {{ cache_enabled | default(true) | lower }}
{% if cache_enabled | default(true) %}
backend = redis
redis_host = {{ redis_host }}
redis_port = {{ redis_port }}
{% endif %}

[features]
{% for feature, enabled in features.items() %}
{{ feature }} = {{ enabled | lower }}
{% endfor %}

{% if environment == 'production' %}
[production]
debug = false
log_level = warning
{% else %}
[development]
debug = true
log_level = debug
{% endif %}
```

## Variables and Facts

### Variable Precedence (low to high)

1. Role defaults
2. Inventory file/script group vars
3. Inventory group_vars/all
4. Playbook group_vars/all
5. Inventory group_vars/\*
6. Playbook group_vars/\*
7. Inventory file/script host vars
8. Inventory host_vars/\*
9. Playbook host_vars/\*
10. Host facts
11. Play vars
12. Play vars_prompt
13. Play vars_files
14. Role vars
15. Block vars
16. Task vars
17. Extra vars (-e flag)

### Using Variables

```yaml
---
- name: Variable examples
  hosts: all
  vars:
    app_name: myapp
    app_version: 1.0.0
  vars_files:
    - vars/common.yml
    - 'vars/{{ environment }}.yml'

  tasks:
    - name: Load variables from file
      include_vars:
        file: 'vars/{{ ansible_distribution }}.yml'

    - name: Set fact
      set_fact:
        full_app_name: '{{ app_name }}-{{ app_version }}'

    - name: Register output
      command: hostname
      register: hostname_output

    - name: Use registered variable
      debug:
        msg: 'Hostname is {{ hostname_output.stdout }}'

    - name: Access facts
      debug:
        msg: |
          OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
          Kernel: {{ ansible_kernel }}
          CPU: {{ ansible_processor_vcpus }} cores
          Memory: {{ ansible_memtotal_mb }} MB
          IP: {{ ansible_default_ipv4.address }}
```

## Error Handling

```yaml
---
- name: Error handling examples
  hosts: all
  tasks:
    - name: Task that might fail
      command: /bin/false
      ignore_errors: yes

    - name: Task with custom error handling
      block:
        - name: Try to start service
          systemd:
            name: myapp
            state: started
      rescue:
        - name: Log error
          debug:
            msg: 'Failed to start myapp'

        - name: Try alternative
          systemd:
            name: myapp-fallback
            state: started
      always:
        - name: This always runs
          debug:
            msg: 'Cleanup task'

    - name: Assert condition
      assert:
        that:
          - ansible_memtotal_mb >= 2048
          - ansible_processor_vcpus >= 2
        fail_msg: 'Server does not meet minimum requirements'

    - name: Fail when condition
      fail:
        msg: 'Production deployment requires version tag'
      when:
        - environment == 'production'
        - app_version == 'latest'

    - name: Changed when condition
      command: /usr/local/bin/check_status.sh
      register: result
      changed_when: "'updated' in result.stdout"
      failed_when: result.rc not in [0, 2]
```

## Ansible Vault

```bash
# Create encrypted file
ansible-vault create secrets.yml

# Edit encrypted file
ansible-vault edit secrets.yml

# Encrypt existing file
ansible-vault encrypt vars/production.yml

# Decrypt file
ansible-vault decrypt vars/production.yml

# View encrypted file
ansible-vault view secrets.yml

# Rekey (change password)
ansible-vault rekey secrets.yml
```

```yaml
# secrets.yml - what `ansible-vault view secrets.yml` shows you.
# On disk this file is ciphertext; it is only ever plaintext in memory and in
# your editor during `ansible-vault edit`. Never commit the decrypted form.
---
db_password: "{{ lookup('env', 'DB_PASSWORD') }}"
api_key: "{{ lookup('env', 'API_KEY') }}"
ssl_key: "{{ lookup('env', 'SSL_PRIVATE_KEY') }}"


# The same file at rest, after `ansible-vault encrypt`:
#   $ANSIBLE_VAULT;1.1;AES256
#   66386439653236336462626566653063336164663966303231363934653561363964363833313662
#   ...

# Use in playbook
---
- name: Deploy with secrets
  hosts: production
  vars_files:
    - secrets.yml
  tasks:
    - name: Configure database
      template:
        src: db.conf.j2
        dest: /etc/db.conf
      no_log: yes # Don't log sensitive data
```

```bash
# Run playbook with vault password
ansible-playbook playbook.yml --ask-vault-pass

# Use password file
ansible-playbook playbook.yml --vault-password-file ~/.vault_pass

# Use multiple vault IDs
ansible-playbook playbook.yml --vault-id prod@prompt --vault-id dev@~/.vault_dev
```

## Testing

### Molecule (Role Testing)

```bash
# Install molecule
pip install molecule molecule-docker

# Initialize molecule
cd roles/myapp
molecule init scenario

# Run tests
molecule test

# Test workflow
molecule create    # Create test instances
molecule converge  # Run playbook
molecule verify    # Run tests
molecule destroy   # Cleanup
```

```yaml
# molecule/default/molecule.yml
---
dependency:
  name: galaxy
driver:
  name: docker
platforms:
  - name: ubuntu
    image: geerlingguy/docker-ubuntu2004-ansible
    pre_build_image: yes
provisioner:
  name: ansible
verifier:
  name: ansible
```

## Anti-Patterns to Avoid

❌ **Not using roles**: Organize code in reusable roles
❌ **Shell commands everywhere**: Use modules when available
❌ **Hardcoded values**: Use variables
❌ **No error handling**: Use blocks, rescue, always
❌ **Storing secrets in plaintext**: Use Ansible Vault
❌ **Not testing**: Use molecule for role testing
❌ **Ignoring idempotency**: Tasks should be safe to run multiple times
❌ **Complex playbooks**: Break into smaller, focused playbooks

## Reference Documentation

Detailed material lives alongside this skill and is read on demand:

- [Best Practices](references/BEST_PRACTICES.md) — Playbook Organization, Idempotency, Performance, Security
- [Playbooks](references/PLAYBOOKS.md) — Basic Playbook, Advanced Playbook, Conditionals and Loops
- [Roles](references/ROLES.md) — Role Structure, Example Role, Role Dependencies

## Resources

- Ansible Documentation: https://docs.ansible.com/
- Ansible Galaxy: https://galaxy.ansible.com/
- Molecule: https://molecule.readthedocs.io/
- Best Practices: https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html

© personamanagmentlayer · Apache-2.0 · personamanagmentlayer/pcl

Similar skills

All skills for DevOps and infrastructure →

From the same set25

manufacturing-expert This skill gives coding agents manufacturing context for Industry 4.0, MES, PLCs, and quality analysis. Use it for production-system and process-control tasks. CX Codex +1 613installs data-science-expert A skill for analytics, statistics and visualization that kicks in when a task mentions pandas, NumPy or exploratory data analysis. CX Codex +1 573installs logistics-expert Provides domain logic for supply chain management, warehouse operations, and delivery route optimization. Useful when building logistics software. CX Codex +1 567installs gcp-expert A skill that hands your agent working GCP examples: Cloud Functions, BigQuery, Firestore, Pub/Sub and gcloud commands. Useful when the code targets Google Cloud. CX Codex +1 547installs retail-expert This skill gives an agent retail-system context for POS, inventory, e-commerce, CRM, and omnichannel work. Use it for design and analysis tasks. CX Codex +1 526installs argocd-expert A skill that turns your agent into an ArgoCD operator: GitOps deploys, app sync, AppProject and ApplicationSet. Useful when your deployment lives in Git. CX Codex +1 509installs lawyer-expert Equips the agent with legal domain logic for contract drafting and regulatory compliance audits against GDPR or HIPAA. CX Codex +1 475installs automotive-expert A skill that gives your agent automotive domain knowledge: connected vehicles, telemetry, ADAS, OBD-II diagnostics. Useful when the project touches fleet software or in-vehicle systems. CX Codex +1 467installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor