Dictionary elements access within group_vars

Hi,

I’m using ansible[-playbook] 1.9.0.1.

I have 4 “proxy” hosts talking to 2 “app” hosts:

proxy1 → app1
proxy2 → app1
proxy3 → app2
proxy4 → app2

In group vars I defined:

proxy_to_app_map:
1: 1
2: 1
3: 2
4: 2

proxy_no: “{{ ansible_hostname | regex_replace(‘^.*([0-9]+)$’, ‘\\1’) }}”
app_no: “{{ proxy_to_app_map[proxy_no] }}”

I’m getting:

ok: [proxy1] => {
“var”: {
“proxy_no”: “1”
}
}

and so on, but then I get a string instead of a specific dictionary value (I expect a number, 1 or 2).

ok: [proxy1] => {

“var”: {

“app_no”: “{{ proxy_to_app_map[proxy_no] }}”

}

}

I tried this:
app_no: “{{ proxy_to_app_map.proxy_no }}”

And this
app_no: proxy_to_app_map.proxy_no

And this
app_no: “proxy_to_app_map.proxy_no”

and it still does not access the value. Why does this (not) happen? Is there any documentation somewhere that would describe the rules of what gets interpolated and what doesn’t?

I have something like that later on, but it won’t work without proper app_no.

app_peer_host: “{{ ansible_hostname | regex_replace(‘^proxy’, ‘app’) | regex_replace(proxy_no + ‘$’, app_no) }}”
app_peer_ip: “{{ hostvars[app_peer_host][‘ansible_eth0’][‘ipv4’][‘address’] }}”

I’m using the hostvars trick like in the app_peer_ip in many places so some interpolation works within group vars, but not all. Is this because hostvars is a dict defined “externally” and proxy_to_app_map internally?

A workaround is something like that:

proxy_to_app_map:
proxy1: app1
proxy2: app1
proxy3: app2
proxy4: app2

app_peer_host: “{{ proxy_to_app_map[ansible_hostname] }}”

Which does work, and looks simpler, but would need to be defined for every environment separately (real hostnames are more complex than proxy and app), and that’s lots of defining.

This leads me to a conclusion that a variable defined within group_vars cannot be used as a key “identifier” to access a dictionary element if that dictionary is also defined in group_vars. Is that the case?

Regards,
Daniel

Replying to myself.

Well, it was just integer vs. string in the end. So yeah, PEBKAC. Quoting everything in proxy_to_app_map did the trick.

Regards,
Daniel