leontp587
leontp587

Reputation: 791

Ansible filter by attribute contains a value

In Ansible, how do I filter objects by whether the object's attribute contains a value?

For example: I want to return the private_man object which has attribute name="a2" by filtering private_man objects where addr contains "1.2.3.4".

Here's the Ansible code:

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    network:
      addresses:
        private_ext:
          - name: a1
            addr:
              - 1.2.3.4
        private_man:
          - name: a2
            addr:
              - 10.10.20.30
              - 1.2.3.4
          - name: a3
            addr:
              - 10.90.80.10

I tried the following:

- debug:
    msg: "{{ item.name }}"
  with_items: "{{ network.addresses.private_man | selectattr('addr', 'in', '1.2.3.4') | list }}"

I expected this to display a2 because the a2 object's addr element contains 1.2.3.4

When I ran this, however, it failed completely, probably because selectaddr('addr', 'in', '1.2.3.4') is not valid.

Upvotes: 4

Views: 14380

Answers (3)

shawnjohnson
shawnjohnson

Reputation: 405

I was just able to use the following to narrow the results from ec2_asg_facts to only those with a given variable value in the launch_configuration_name. The search test doesn't seem to be well documented, and it may be an add-on? I thought I would share in case others wanted to do something similar. Below appRole.name could be something like "employee" or "data".

  - name: Narrow my list
    set_fact:
      asgList: "{{ autoScalingGroupNames.results | selectattr('launch_configuration_name', 'search', appRole.name) | list }}"

Upvotes: 1

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68239

You can use only Jinja2 tests in selectattr:
http://jinja.pocoo.org/docs/2.9/templates/#builtin-tests http://docs.ansible.com/ansible/latest/playbooks_tests.html

For your example:

- debug:
    msg: "{{ item.name }}"
  with_items: "{{ network.addresses.private_man | selectattr('addr','issuperset',['1.2.3.4']) | list }}"

Upvotes: 6

helloV
helloV

Reputation: 52375

Will this work?

  - debug:
      msg: "{{ item.name }}"
    with_items: "{{network.addresses.private_man}}"
    when: '"1.2.3.4" in item.addr'

Upvotes: 4

Related Questions