Skip to content

Commit

Permalink
key-order: Add extra documentation (ansible#2511)
Browse files Browse the repository at this point in the history
Related: ansible#2509
  • Loading branch information
ssbarnea committed Oct 4, 2022
1 parent 0f13604 commit 7e3b389
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions src/ansiblelint/rules/key_order.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ Here are some examples of common ordering checks done for tasks and handlers:
---
- hosts: localhost
name: This is a playbook # <-- name key should be the first one
tasks: []
tasks:
- name: A block
block:
- name: Display a message
debug:
msg: "Hello world!"
when: true # <-- when key should be before block
```

## Correct code
Expand All @@ -25,5 +31,33 @@ Here are some examples of common ordering checks done for tasks and handlers:
---
- name: This is a playbook
hosts: localhost
tasks: []
tasks:
- name: A block
when: true
block:
- name: Display a message
debug:
msg: "Hello world!"
```

## Reasoning

Making decisions about the optimal order of keys for ansible tasks or plays is
no easy task, as we had a huge number of combinations to consider. This is also
the reason why we started with a minimal sorting rule (name to be the first),
and aimed to gradually add more fields later, and only when we find the proofs
that one approach is likely better than the other.

### Why I no longer can put `when` after a `block`?

Try to remember that in real life, `block/rescue/always` have the habit to
grow due to the number of tasks they host inside, making them exceed what a single screen. This would move the `when` task further away from the rest of the task properties. A `when` from the last task inside the block can
easily be confused as being at the block level, or the reverse. When tasks are
moved from one location to another, there is a real risk of moving the block
level when with it.

By putting the `when` before the `block`, we avoid that kind of risk. The same risk applies to any simple property at the task level, so that is why
we concluded that the block keys must be the last ones.

Another common practice was to put `tags` as the last property. Still, for the
same reasons, we decided that they should not be put after block keys either.

0 comments on commit 7e3b389

Please sign in to comment.