.mdc YAML Ansible DevOps

Ansible インフラコードルール

Ansibleのベストプラクティス: ロール設計、YAMLスタイル、冪等性、パフォーマンス最適化、CI/CD統合、ansible-lintによるテスト。

.mdc · 122 lines
# Ansible Best Practices

Ansible excels when treated as infrastructure-as-code. These guidelines ensure your playbooks, roles, and modules are consistent, idempotent, and production-ready.

## 1. Code Organization and Structure

**Always structure your Ansible content into roles and collections.** Roles encapsulate specific functionalities, while collections group related roles, modules, and plugins, promoting reusability and discoverability.

- **Role Scoping:** Each role or module must focus on a single, well-defined task. Avoid monolithic roles.
- **Fact Modules:** Create dedicated `_info` or `_facts` modules/tasks for gathering information, rather than overloading existing ones.

## 2. YAML Hygiene and Syntax

**Enforce strict YAML formatting.** Consistent syntax improves readability and prevents subtle parsing errors.

- All YAML files must begin with `---`
- Use two spaces for indentation, never tabs
- Standardize on `true`/`false` for booleans (not `yes`/`no` or `True`/`False`)
- Use the structured map style for module parameters, not the legacy `key=value` style
- Quote strings only when necessary; prefer single quotes

Good:
```yaml
---
- name: Install a package
  ansible.builtin.apt:
    name: my-package
    state: present
- name: Enable service
  ansible.builtin.service:
    name: my_service
    state: started
    enabled: true
```

Bad:
```yaml
- name: Install a package
  ansible.builtin.apt: name=my-package state=present
```

## 3. Naming Conventions

**Adopt consistent `snake_case` naming.** This applies to variables, tasks, files, and role names. Prefix role names with the collection namespace to prevent collisions.

## 4. Idempotency and Declarative Style

**Write idempotent tasks.** Running a playbook multiple times should yield the same result without unintended side effects. Favor declarative modules over imperative `command` or `shell`.

Good:
```yaml
- name: Ensure myapp.conf exists
  ansible.builtin.copy:
    src: myapp.conf.template
    dest: /etc/myapp.conf
    owner: root
    group: root
    mode: '0644'
    backup: true
```

Bad:
```yaml
- name: Check if file exists and create if not
  ansible.builtin.shell: |
    if [ ! -f /etc/myapp.conf ]; then
      cp /etc/myapp.conf.template /etc/myapp.conf
    fi
```

## 5. Configuration Management

- Use Jinja2 templates (`template` module) for dynamic configuration files
- Define role variables in `defaults/main.yml` (overridable) and `vars/main.yml` (not overridable)
- Never hardcode configuration values in playbooks

## 6. Performance Considerations

- Disable fact gathering (`gather_facts: false`) if not explicitly needed
- Use `async` and `poll` for long-running tasks
- Leverage Ansible's parallelism with `forks` setting

## 7. Error Handling and Logging

- Use `ansible.builtin.fail` for clear error messages: `msg: "Required variable 'app_version' is not defined."`
- Use `ansible.builtin.debug` with verbosity levels for controlled output
- Implement `block`, `rescue`, and `always` for complex error handling

## 8. Testing and Linting

- Run `ansible-lint` on every pull request
- Use `ansible-test` for unit and integration testing of custom modules and roles
- Test roles with Molecule for environment-agnostic testing

## 9. CI/CD Integration

```yaml
# .github/workflows/ansible.yml
name: Ansible CI/CD
on: [push, pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Ansible and dependencies
        run: pip install ansible ansible-lint
      - name: Run Ansible Lint
        run: ansible-lint .
  deploy:
    runs-on: ubuntu-latest
    needs: lint
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
      - name: Install Ansible Collections
        run: ansible-galaxy collection install -r requirements.yml
      - name: Run Playbook
        env:
          ANSIBLE_VAULT_PASSWORD: ${{ secrets.ANSIBLE_VAULT_PASSWORD }}
        run: ansible-playbook -i inventory/prod.yml site.yml --vault-password-file /dev/stdin
```
Share on X

こちらもおすすめ

DevOps カテゴリの他のルール

もっとルールを探す

CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 223 ルールをチェック。