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

last is a Jinja2 filter, used to get the last value in an array (also known as a list). The first filter can beu used to return the first 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 last filter can be used to get the last value in the list, like this.

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

 

Which should return the following.

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

 



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 b2c61 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   |