Refactor Ansible Tasks into a Reusable Role Prompt
Extract a sprawling set of inline playbook tasks into a clean, parameterized Ansible role with proper defaults, vars, handlers, and a Galaxy-standard directory layout.
- Target user
- Ansible automation and platform engineers
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Ansible engineer who turns ad-hoc playbooks into reusable, well-structured roles. I will provide: - The current playbook with inline tasks (paste the YAML) - The variables it hardcodes and which ones should be configurable per environment - Any handlers, templates, or files it references Your job: 1. **Design the role layout** — produce the standard structure (`tasks/main.yml`, `defaults/main.yml`, `vars/main.yml`, `handlers/main.yml`, `templates/`, `files/`, `meta/main.yml`) and explain what goes where. 2. **Split defaults vs vars** — put overridable, sane defaults in `defaults/main.yml` (low precedence) and internal constants in `vars/main.yml`; namespace every variable with the role name to avoid collisions. 3. **Parameterize** — replace hardcoded values with variables, listing each input, its default, and whether it is required (guard required ones with `assert`). 4. **Move handlers and notifies** — relocate handlers into `handlers/main.yml` and keep `notify` references intact. 5. **Wire dependencies and metadata** — fill `meta/main.yml` (galaxy_info, platforms, dependencies) so the role is portable and Galaxy-publishable. 6. **Show the calling playbook** — give a thin playbook that includes the role with example `vars` overrides. 7. **Suggest tests** — note where a `molecule` scenario or `--check` run should validate the role. Output as: (a) the directory tree, (b) each file's contents, (c) a documented variable table (name / default / required / description), (d) the example calling playbook. Keep tasks idempotent during the move, namespace all variables, and do not change behavior — this is a structural refactor, not a feature change.
Related prompts
-
Make an Ansible Playbook Idempotent Prompt
Rewrite a playbook that reports 'changed' on every run into a truly idempotent one, replacing shell/command hacks with proper modules and adding correct change detection.
-
Write Molecule Tests for an Ansible Role Prompt
Add a Molecule test scenario to an Ansible role that converges, asserts idempotency, and verifies state, so role changes are caught before they hit real hosts.