Ansible roles

Hi

There are 100 cassandra hosts (cass01.example.com,…,cass100.example.com)
All shall have the same role common and the same role cassandra.
In addition, 10 out of the 100 cassandra hosts do have additional host-specific configurations
and to make things worse, these configurations differ across the 10 hosts. The 10 cassandra hosts shall be
cass40.example.com,…,cass49.example.com. Finally, the additional host-specific configurations
should be applied after the role common and role cassandra.

To solve this problem, I created a role for each cass40.example.com,…,cass49.example.com.
Each role has the tasks which are specific to that host:

…/roles/common
cassandra
cass40.example.com/tasks/main.yml

cass49.example.com/tasks/main.yml

Inventory file:

(…)
[cassandra]
cass01.example.com

cass100.example.com
(…)

The playbook has the two roles common and cassandra and an additional third role called “{{ inventory_hostname }}”
when a host has a defined variable "has_own_role " in a file …/host_vars/cassxx.example.com. The variable
“{{ inventory_hostname }}” is equal to the FQDN written in the inventory file.

  • hosts: [cassandra}
    user: ansible
    sudo: yes
    roles:
  • common
  • cassandra
  • { role: “{{ inventory_hostname }}” , when: has_own_role is defined }

The files in …/host_vars/… are:

cat …/host_vars/cass40.example.com
has_own_role: True

cat …/host_vars/cass49.example.com
has_own_role: True

When the playbook is run, ansilbe complains that there is no role {{ inventory_hostname }}:


ERROR: cannot find role in /data/ansible/roles/{{ inventory_hostname }} or /data/ansible/{{ inventory_hostname }} or /etc/ansible/roles/{{ inventory_hostname }}

However, if I hard code a fix role (foo), the playbook works as intended :

  • { role: foo , when: has_own_role is defined }

Queston 1:
Is there a way to provide a role name as a variable in the following line instead of a fixed string (foo) ?

  • { role: foo , when: has_own_role is defined }

Question 2;
In general, I do not know how to deal with the following (common) situation in Ansible:
There is a bunch of equal hosts (cassandra) in the data center, but a few of them a some random additional configurations

Hi Phonthip,

Roles are read in at YAML parsing time, so inventory variables as you’re using here are not yet available. Unfortunately the only way to do this in 1.9 and lower would be to create a new role and use “include:” for each given hostname.

In the future (2.0), this will be much easier, as you could do this:

  • include: {{inventory_hostname}}.yml
    when: has_own_role is defined

And then each hosts YAML file would be in the tasks/ directory of your special role.

Hope that helps!