jinja2ansible

Ansible: filter a list by its attributes


I have variable named "network" registered in Ansible:

{
    "addresses": {
        "private_ext": [
            {
                "type": "fixed",
                "addr": "172.16.2.100"
            }
        ],
        "private_man": [
            {
                "type": "fixed",
                "addr": "172.16.1.100"
            },
            {
                "type": "floating",
                "addr": "10.90.80.10"
            }
        ]
    }
}

Is it possible to get the IP address ("addr") with type="floating" doing something like this?

- debug: var={{ network.addresses.private_man | filter type="fixed" | get "addr" }}

I know the syntax is wrong but you get the idea.


Solution

  • I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:

    - debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"
    

    would return:

    ok: [localhost] => {
        "msg": [
            "172.16.1.100"
        ]
    }