Maikol
Maikol

Reputation: 359

Is there a better alternative to importing roles in Ansible?

I'm trying to write a playbook that either installs and uninstall a custom tool depending on a parameter passed in at runtime. For this purpose I've defined a role to install it and another to uninstall.

The issue I'm having is that there are quite a few variables and handlers shared amongst the roles. However, as only one of the roles is imported at a time, any handlers or variables defined in the other role aren't available.

This leads me to think that the approach of conditionally importing the role may not be correct.

Sample code:

- hosts: all

  vars_files:
    - vars/main.yml    # <-- I had to explicitly define the path of the shared variables file

  tasks:
    - import_role:
        name: install_script_discovery
      when: install | bool
    - import_role:
        name: uninstall_script_discovery
      when: not install | bool  

  handlers: 
    - name: reload audit daemon
      command: /usr/sbin/service auditd reload

What I don't like is that the path of the main.yml variable file had to be explicitly set, and same for the handler in the playbook main.yml file. The beauty of roles is that you can create a /vars or /handlers directory and place your main.yml file inside, and those files will be loaded automatically keeping the roles code clean and short.

So I'm wondering if it's either possible to replicate this behaviour but at the playbook level or is perhaps the approach of conditionally importing the roles incorrect given that both variables and handlers should be accessible across all roles regardless of where they have been loaded from?

Upvotes: 1

Views: 134

Answers (1)

larsks
larsks

Reputation: 311713

Why not use a single role with two task files? That is, a layout like this:

roles/
  script_discovery/
    tasks/
      install.yaml
      uninstall.yaml

And then in your playbook:

tasks:
  - import_role:
      name: script_discovery
      tasks_from: install.yaml
    when: install | bool
  - import_role:
      name: script_discovery
      tasks_from: uninstall.yaml
    when: not install | bool  

This allows you to share handlers, variables, etc, between the install and uninstall task lists.


You may prefer include_role over import_role: with include_role, the when condition is applied to the include_role task itself; when using import_role, the when condition is applied to each task inside the role.

Upvotes: 2

Related Questions