Search code examples
rolesansible

Ansible include roles that have been defined in hostvars


I am trying to do the following:

  1. define appropriate host roles in hostvars
  2. create a role to call ONLY the roles that relate to specific host and have been defined in a variable in hostvars

Is there a way to do this?

eg:

host_vars/hostname_one/mail.yml

roles_to_install:
  - role_one
  - role_two
  - ...

run_all_roles.yml

---
- hosts: '{{ TARGET }}'

  become: yes
  ... 
  roles:
    - { role: "roles_to_install"}

Obviously this does not work.

Is there a way to make ansible-playbook -i <hosts_file> run_all_roles.yml -e "TARGET=hostname_one" to run?


Solution

  • As I commented the solution was easier than expected:

    --- 
    - hosts: '{{ TARGET }}' 
      become: yes 
    
      vars_files: 
      - ./vars/main.yml 
    
      roles: 
        - { role: "roleA", when: "'roleA' in roles_to_install" } 
        - { role: "roleB", when: "'roleB' in roles_to_install" } 
        ... 
    

    Assuming that a correct roles_to_install var is defined inside host_vars/$fqdn/main.yml like so:

    ---
    roles_to_install:
      - roleA
      - roleB
      - ...
    

    Thank you for you assistance guys