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

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


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