Ansible Playbook key-order: Keeping Your Playbooks Neat and Error-Free
In the world of Ansible, maintaining well-structured and readable playbooks is essential. The key-order rule is your secret weapon for keeping your playbooks clean and less prone to errors. This rule offers key reordering recommendations to enhance your Ansible coding skills and streamline your playbook development.
The Anatomy of key-order
The key-order rule comes with some essential guidelines:
1. "name" Comes First: For plays, tasks, and handlers, the "name" key should always be the first one. This naming convention helps you quickly grasp the purpose of a specific block of code.
2. "block," "rescue," and "always" Are Last: In tasks, the "block," "rescue," and "always" keys should be positioned at the end. This arrangement reduces the likelihood of accidental misindentation errors, especially when dealing with complex playbooks.
Spotting the Problem
Let's take a look at a problematic code snippet:
``yaml
---
- hosts: all
name: This is a playbook # <-- "name" key should be the first one
tasks:
- name: A block
block:
- name: Display a message
ansible.builtin.debug:
msg: "Hello world!"
when: true # <-- "when" key should be before "block"
`
Here, we encounter a playbook where the "name" key isn't at the beginning, and the "when" key appears after the "block" key, violating the key-order rule.
Ansible Lint Output
`bash
WARNING Listing 3 violation(s) that are fatal
key-order[play]: You can improve the play key order to: name, hosts, tasks
key-order.yml:2
key-order[task]: You can improve the task key order to: name, when, block
key-order.yml:5 Task/Handler: A block
fqcn[action-core]: Use FQCN for builtin module actions (debug).
key-order.yml:7 Use ansible.builtin.debug or ansible.legacy.debug instead.
Read documentation for instructions on how to ignore specific rule violations.
Rule Violation Summary
count tag profile rule associated tags
1 key-order[play] basic formatting
1 key-order[task] basic formatting
1 fqcn[action-core] production formatting
Failed: 3 failure(s), 0 warning(s) on 1 files. Last profile that met the validation criteria was 'min'.
`
The Correct Order
Let's rectify the previous example and adhere to the key-order rule:
`yaml
---
- name: This is a playbook
hosts: all
tasks:
- name: A block
when: true
block:
- name: Display a message
ansible.builtin.debug:
msg: "Hello world!"
`
Now, we have reordered the keys according to the key-order rule recommendations.
Why Does key-order Matter?
The key-order` rule is not about arbitrary rules but rather a best practice. Here's why it's essential:
1. Code Maintenance:
Properly ordered keys make your play