AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible-Lint Error key-order: Fix YAML Key Ordering in Playbooks

By Luca Berton · Published 2024-01-01 · Category: installation

Fix ansible-lint key-order error. Understand recommended YAML key ordering for tasks, plays, and roles. Configure or skip the rule with examples.

Ansible-Lint Error key-order: Fix YAML Key Ordering in Playbooks

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.

See also: Ansible troubleshooting - Error: name[casing]

The Anatomy of key-order

The key-order rule comes with some essential guidelines: "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. "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:

---
- 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

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'.

See also: Ansible troubleshooting - Error: name[play]

The Correct Order

Let's rectify the previous example and adhere to the key-order rule:

---
- 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 playbooks more accessible to read and understand, especially for large and complex scripts. When your playbook grows in complexity, you'll appreciate the consistency in key ordering.

2. Error Prevention:

Correct key ordering reduces the chances of misindentation errors. It keeps the essential keys in predictable locations, minimizing the risk of misplaced keys and accidental mistakes.

3. Rule Evolution:

The key-order rule is not set in stone. It's designed to evolve as the community gathers more evidence on optimal key ordering. It starts with simple guidelines like "name first" and expands as better practices emerge.

4. Playbook Resilience:

By adhering to key ordering, you ensure that your playbooks are robust and adaptable. key-order maintains the playbook's resilience when tasks are moved or modified within the script.

See also: Ansible troubleshooting - Error: no-jinja-when

A Note on Automation

The key-order rule doesn't just recommend; it can automatically fix the key ordering using the ansible-lint --fix option. This means that you can effortlessly adhere to this rule without manual reordering, fostering consistency and adherence to best practices in your Ansible code.

Conclusion

In conclusion, the key-order rule in Ansible is your ally in creating well-structured, error-free playbooks. By following this rule, you enhance the readability of your code, reduce the likelihood of errors, and ensure that your playbooks remain resilient as they evolve. It's not just a set of arbitrary guidelines; it's a best practice that grows with the Ansible community's collective wisdom.

Adhering to the key-order rule not only benefits you but also anyone who collaborates with your Ansible projects. It streamlines the development process and promotes code consistency, making it easier for your team to maintain and extend playbooks.

With automation capabilities to automatically enforce this rule, Ansible ensures that your playbooks are not only functional but also structured in a way that reflects best practices. So, the next time you dive into Ansible playbook development, keep the key-order rule in mind to maximize your efficiency and produce high-quality, maintainable code. Happy Ansible coding!

The Error

key-order[task]: You can improve the task key order to: name, when, block, ...
# Correct order for task keys
- name: Install nginx            # 1. name (always first)
  ansible.builtin.apt:           # 2. module/action
    name: nginx
    state: present
  when: ansible_os_family == "Debian"  # 3. conditionals
  become: true                   # 4. become
  register: install_result       # 5. register
  changed_when: false            # 6. changed_when
  failed_when: false             # 7. failed_when
  ignore_errors: true            # 8. ignore_errors
  no_log: true                   # 9. no_log
  tags:                          # 10. tags
    - packages
  notify: restart nginx          # 11. notify

Common Violations

# WRONG — name not first
- apt:
    name: nginx
  name: Install nginx

# CORRECT - name: Install nginx apt: name: nginx

# WRONG — tags before module - name: Install nginx tags: [packages] apt: { name: nginx }

# CORRECT - name: Install nginx apt: name: nginx tags: [packages]

Block Key Order

- name: Handle web server setup
  when: setup_web | default(false)
  block:
    - name: Install nginx
      apt: { name: nginx, state: present }
    - name: Start nginx
      service: { name: nginx, state: started }
  rescue:
    - debug: msg="Setup failed"
  always:
    - debug: msg="Cleanup done"
  become: true
  tags: [web]

Full Key Order Reference

# Play level
- name:           # Play name
  hosts:          # Target hosts
  gather_facts:   # Fact gathering
  become:         # Privilege escalation
  vars:           # Variables
  vars_files:     # Variable files
  pre_tasks:      # Pre-tasks
  roles:          # Roles
  tasks:          # Tasks
  post_tasks:     # Post-tasks
  handlers:       # Handlers
  tags:           # Tags

Suppress the Rule

# .ansible-lint
skip_list:
  - key-order[task]
  - key-order[play]

# Or per-task - name: My task # noqa: key-order[task] tags: [first] apt: { name: nginx }

Auto-Fix

# ansible-lint can fix key ordering automatically
ansible-lint --fix

FAQ

Is key order just cosmetic?

Yes — YAML key order doesn't affect execution. But consistent ordering improves readability and makes code reviews easier.

What's the full recommended order?

name → module → args → when → become → register → changed_when → failed_when → ignore_errors → no_log → loop → tags → notify → delegate_to

Can I customize the expected order?

Not directly in ansible-lint. You can skip the rule or accept the default ordering convention.

# CORRECT order
- name: Install nginx           # 1. name (always first)
  ansible.builtin.apt:          # 2. module
    name: nginx
    state: present
  become: true                   # 3. task keywords
  when: ansible_os_family == "Debian"
  register: install_result
  notify: restart nginx
  tags: [packages]
- name: Configure webservers    # 1. name
  hosts: webservers             # 2. hosts
  become: true                  # 3. become
  gather_facts: true            # 4. gather_facts
  vars:                         # 5. vars
    app_port: 8080
  pre_tasks:                    # 6. pre_tasks
    - debug: msg="Starting"
  roles:                        # 7. roles
    - nginx
  tasks:                        # 8. tasks
    - debug: msg="Done"
  handlers:                     # 9. handlers
    - name: restart nginx
      service: { name: nginx, state: restarted }

Common Violations

# WRONG — name should come first
- apt:
    name: nginx
  name: Install nginx           # name after module!
  become: true

# CORRECT - name: Install nginx apt: name: nginx become: true

Skip the Rule

# Per task
- name: Special case
  command: /opt/script.sh  # noqa: key-order

# Globally in .ansible-lint skip_list: - key-order

FAQ

Why does key order matter?

Consistent ordering improves readability. When every task follows the same pattern, scanning playbooks becomes faster. It's a style rule, not a functional one.

Does wrong order break anything?

No — YAML doesn't care about key order. This is purely a linting/style rule for team consistency.

What's the full recommended order for tasks?

name → module → module args → become/become_userwhenregisterchanged_when/failed_whennotifylooptagsno_log.

Related Articles

publishing collections to Ansible Galaxyusing when in Ansible playbooksAnsible Loops Guideflush_handlers in Ansible

Category: installation

Browse all Ansible tutorials · AnsiblePilot Home