Bootstrap FreeKB - Ansible - Return the last element in a list
Ansible - Return the last element in a list

Updated:   |  Ansible articles

last is a Jinja filter that can be used to get the last element in a list. The first filter can be used to return the first 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"
    ]
}

 

last can be used to get the last element in the list.

---
- hosts: all
  vars:
    fruit: 
      - apple
      - banana
      - orange
      - grapes
  tasks:
  - name: output the last element in the 'fruit' list
    debug: 
      vars: fruit | last
...

 

Which should return the following.

TASK [output the last 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 Buy Me A Coffee



Comments


Add a Comment


Please enter e22648 in the box below so that we can be sure you are a human.