Ansible - Return the first value in an array using the first filter

first is a Jinja2 filter, used to get the first value in an array (also known as a list). The last filter can be used to return the last value in an array. Let's say you are using the vars plugin to create an array of fruit, like this.

vars:
  fruit: 
    - apple
    - banana
    - orange
    - grapes

 

The debug module can be used to output the entire array, like this.

- name: output the contents of the 'fruit' array
  debug: 
    msg: "{{ fruit }}"

 

Which should return the following.

TASK [output the contents of the 'fruit' array]
ok: [server1.example.com] => {
    "msg": [
        "apple"
        "banana",
        "orange",
        "grapes"
    ]
}

 

The first filter can be used to get the first value in the list, like this.

- name: output the first value in the 'fruit' array
  debug: 
    msg: "{{ fruit | first }}"

 

Which should return the following.

TASK [output the first value in the 'fruit' array]
ok: [server1.example.com] => {
    "msg": [
        "apple"
    ]
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |