Introduction
When writing Ansible playbooks, it's important to maintain clarity and consistency in your code to ensure it's easy to understand and maintain. One common area where clarity can be improved is in handling loop variables, especially in nested loops. To address this, Ansible provides a rule called "loop-var-prefix" to help avoid conflicts and enforce clear variable naming in loops.
Why is Variable Naming Important in Loops?
In Ansible, loops are frequently used to iterate over lists of items and perform tasks. By default, Ansible uses the variable name "item" for loop iterations. While this is convenient, it can lead to ambiguity and confusion when you have nested loops or multiple loops in the same playbook.
To address this issue, the "loop-var-prefix" rule encourages users to define their loop variables explicitly, providing a more descriptive name. Additionally, it suggests that loop variables should have a prefix, which can be configured according to your preferences.
Configuring the Loop Variable Prefix
The "loop-var-prefix" rule allows you to configure the loop variable prefix to match your coding standards. You can change the default behavior by using a regular expression to enforce variable naming conventions. For instance, if you want the loop variable to start with "myrole_", you can set the rule in your .ansible-lint configuration like this:
``yaml
.ansible-lint
loop_var_prefix: "^(myrole_)"
`
With this configuration, loop variables should start with "myrole_" to ensure uniqueness and clarity.
Identifying Problematic Code
The "loop-var-prefix" rule can produce two types of messages:
1. loop-var-prefix[missing]: This message suggests that you should replace any unsafe implicit "item" loop variable by adding loop_var: <variable_name>. It means that you haven't explicitly defined a loop variable for your task, and it's still using the default "item."
2. loop-var-prefix[wrong]: This message advises ensuring that the loop variable starts with the specified prefix, as defined in the regular expression. If the loop variable doesn't match the prefix, it suggests correcting the variable name.
Problematic Code and Correct Code Examples
Let's look at some examples to understand how to use the "loop-var-prefix" rule correctly:
Problematic Code
`yaml
---
- name: Example playbook
hosts: all
tasks:
- name: Does not set a variable name for loop variables.
ansible.builtin.debug:
var: item # <- When in a nested loop, "item" is ambiguous
loop:
- foo
- bar
- name: Sets a variable name that doesn't start with <loop_var_prefix>.
ansible.builtin.debug:
var: zz_item
loop:
- foo
- bar
loop_control:
loop_var: zz_item # <- zz is not the role name so the prefix is wrong
`
Correct Code
``yaml
---
- name: Example playbook
hosts: all
tasks:
- name: Sets a unique variable_name with