Nelson G.
Nelson G.

Reputation: 5441

How to use a role's default value through `hostvars`

I'm trying to create a role inspired by this one: ansible-cassandra.

In this role, there is a default value for variable cassandra_network_iface:

cassandra_network_iface: eth0

And a template file cassandra.yaml.j2 that use it through hostvars:

...
- seeds: "{% for host in groups[cassandra_ansible_groupname] %}{{hostvars[host]['ansible_' + hostvars[host]['cassandra_network_iface']]['ipv4']['address']}}{% if not loop.last %},{% endif %}{% endfor %}"
...

When I use this template file with a task:

- name: configure...
  template: >-
    src=cassandra.yaml.j2
    dest=/tmp/cassandra.yaml
    mode=0644

I have this error:

fatal: [...]: FAILED! => {"changed": false, "failed": true, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'cassandra_network_iface'"}

The problem is variable cassandra_network_iface is not defined into hostvars[host] scope (I checked that with a debug task), otherwise I can use it directly.

My question: is there a way to reach variable cassandra_network_iface through hostvars ?

Note: I tried with ansible 2.1 and 2.2

Upvotes: 1

Views: 1663

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68229

You can't access roles' default var via hostvars.

Try:

- seeds: "{% for host in groups[cassandra_ansible_groupname] %}{{hostvars[host]['ansible_' + (hostvars[host]['cassandra_network_iface']|default(cassandra_network_iface))]['ipv4']['address']}}{% if not loop.last %},{% endif %}{% endfor %}"

This way, if cassandra_network_iface is overridden per host, value from hostvars will be used; otherwise – default roles' value.

Upvotes: 2

Related Questions