Ansible - Return the first element in a list
by
Jeremy Canfield |
Updated: November 06 2023
| Ansible articles
first is a Jinja filter that can be used to get the first element in a list. The last filter can be used to return the last element in an list. Let's say you are using vars to create an list of fruit. debug can be used to output the entire list.
---
- hosts: all
vars:
fruit:
- apple
- banana
- orange
- grapes
tasks:
- name: output the contents of the 'fruit' list
debug:
vars: fruit
...
Which should return the following.
TASK [output the contents of the 'fruit' list]
ok: [server1.example.com] => {
"fruit": [
"apple"
"banana",
"orange",
"grapes"
]
}
first can be used to get the first element in the list.
---
- hosts: all
vars:
fruit:
- apple
- banana
- orange
- grapes
tasks:
- name: return the first element in the 'fruit' list
debug:
vars: fruit | first
...
Which should return the following.
TASK [return the first element in the 'fruit' list]
ok: [server1.example.com] => {
"fruit": [
"grapes"
]
}
Did you find this article helpful?
If so, consider buying me a coffee over at