Bootstrap FreeKB - Ansible - Return the number of items in a variable or list using the length filter
Ansible - Return the number of items in a variable or list using the length filter

Updated:   |  Ansible articles

length is a Jinja filter used to return the number of elements in a variable or list. For example, let's say you've created the following variables and lists using vars and debug.

---
- name: main play
  hosts: localhost
  vars:
    foo: "Hello World"
    emptyfoo: ""
    bar:[ 'Hello', 'World' ]
    emptybar: []
  tasks:
  - debug:
      var: foo | length

  - debug:
      var: emptyfoo | length

  - debug:
      var: bar | length

  - debug:
      var: emptybar | length
...

 

Something like this should be returned.

TASK [debug]
ok: [server1.example.com] => {
    "foo | length": "11"
}

TASK [debug]
ok: [server1.example.com] => {
    "emptyfoo | length": "0"
}

TASK [debug]
ok: [server1.example.com] => {
    "bar | length": "2"
}

TASK [debug]
ok: [server1.example.com] => {
    "emptybar | length": "0"
}

 

This could also be used in a when statement.

---
- name: main play
  hosts: localhost
  vars:
    foo: "Hello World"
    emptyfoo: ""
    bar:[ 'Hello', 'World' ]
    emptybar: []
  tasks:
  - debug:
      msg: foo length is greater than zero
    when: foo | length > 0

  - debug:
      msg: emptyfoo length is greater than zero
    when: emptyfoo | length > 0

  - debug:
      msg: bar  length is greater than zero
    when: bar | length > 0

  - debug:
      msg: emptybar length is greater than zero
    when: emptybar | length > 0
...

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


July 20 2022 by Fathima
How to get count from variable bar if bar takes value from a global variable say example bar: "{{ server_ip }}" where serve_ip holds value spas server_ip : 192.168.100.12,192.168.100.13. bar value length should be returned as 2

July 23 2022 by Jeremy (moderator)
You could have the IP addresses in an array such as ips: [ '192.168.100.12', '192.168.100.13' ] and then the length value will be 2

Add a Comment


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