Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ansible check if value exists in dictionary list

Below is my variable list

hostlist:
  - { name: 'host1', ip_addr: '192.168.2.31', hostgrp: 'physical_workstation' }
  - { name: 'host2', ip_addr: '192.168.2.32', hostgrp: 'physical_workstation' }
  - { name: 'host3', ip_addr: '192.168.2.33', hostgrp: 'virtual_machine' }

I treid below

- name: Conditional test
  debug:
    msg: "hello world"
  when: hostlist|selectattr("name", "equalto", "host1")|list|length != 0

This does not work as showing below error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The error was: TemplateRuntimeError: no test named 'equalto'

There is solution of upgrding Jinaj2. But is there any other method instead of using selectattr. I wish not to upgrade Jinja2

>Solution :

Create the list of names and test the name is in the list, e.g.

    - debug:
        msg: "hello world"
      loop:
        - 'host1'
        - 'host9'
      when: item in _names
      vars:
        _names: "{{ hostlist|map(attribute='name')|list }}"

gives

ok: [localhost] => (item=host1) => 
  msg: hello world
skipping: [localhost] => (item=host9)

Check only host1

    - debug:
        msg: "hello world"
      when: "'host1' in _names"
      vars:
        _names: "{{ hostlist|map(attribute='name')|list }}"

gives

ok: [localhost] => (item=host1) => 
  msg: hello world
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading