The two main ways to define a list variable in YAML (the format used by Ansible) are
the Block Sequence style and the Flow Sequence (or inline) style.
1) Block Sequence style
1.a) Block Sequence Style (Most Common)
This is the most common and most readable way to define lists, especially for longer lists or complex data structures in Ansible.
Each list item is on a new line and begins with a hyphen and a space (- ).
All list items must be at the same indentation level as the variable name.
π Example: Simple List
---
vars:
# This is a list variable named 'fruits'
fruits:
- Apple
- Orange
- Banana
- Grape
The hyphen (-) simply marks the beginning of a new item in the list.
The entire value of each list item is the string itself (Apple, Orange, etc.).
There is no need for a key like name, because the item is the value.
You would access the first item as fruits[0], which returns the string "Apple"
Each item itself is the value → "Apple", "Orange", etc.
How to refer:
Referring to the Whole List
To refer to the entire fruits list, you use the variable name defined under vars::
In YAML/Ansible (Jinja2 templating)
# Output: The list of fruits is: ['Apple', 'Orange', 'Banana', 'Grape']
Accessing Individual Items (Indexing)
Lists are ordered, meaning you can access items by their zero-based index.
Index
0refers to the first item (Apple).Index
1refers to the second item (Orange), and so on.In YAML/Ansible (Jinja2 templating): You use square brackets
[]after the variable name.
1.b List of Dictionaries: Array of Objects
This defines a list where each item is a key-value pair (a dictionary).
This is often used for defining users, packages, or firewall rules.
π Example: Dictionaries: Array of Objects
---
vars:
users:
- name: alice
uid: 1001
- name: bob
uid: 1002
- name: charlie
uid: 1003
Here each list item is not a single string — it is a dictionary/map with keys:
name → alice
uid → 1001
So each element must begin with - followed by a mapping:
Access specific element (index based)
Example: Access Bob’s UID
Indexes:
-
alice =
users[0] -
bob =
users[1] -
charlie =
users[2]
2) Flow Sequence (or inline) style.
This style is a compact, JSON-like syntax that puts the entire list on a single line. It's often used for short, simple lists.
The list is enclosed in square brackets (
[]).Items are separated by a comma and a space (
,).
You can also define lists of dictionaries this way, although it sacrifices some readability.
✔ Visualization:
Here:
-
users→ dictionary -
keys:
alice,bob,charlie -
each key contains another dictionary
No comments:
Post a Comment