Home > Net >  Ansible Roles Handlers for Windows and Linux
Ansible Roles Handlers for Windows and Linux

Time:06-18

Goal: I'm trying to build a role where I have handlers for Windows and Linux.

Problem: Where to put the handlers?

Idea 1: Put handlers in roles/handlers/main.yaml.

Issue: If its a linux machine the windows part throws an error and vice versa:

ERROR! couldn't resolve module/action 'ansible.windows.win_shell'.

Idea 2: Put handlers in roles/tasks/main.yaml

Issue: It's an include_task, so it expects a list of tasks, not handlers.

ERROR! The tasks/main.yml file for role 'test_role' must contain a list of tasks

Background:

File structure:

main_playbook.yaml
roles/test_role/tasks/main.yaml
roles/test_role/handlers/main.yaml

If I try the second example from the docu and put that snippet in an include task, I get following error:

ERROR! conflicting action statements: ansible.builtin.template, handlers

CodePudding user response:

Quick N dirty pseudo code to put you on track (and by far not the only solution). For the below, to work, you need to have facts gathered on all the relevant targets.

In handlers/main.yml

- name: React to something
  include_tasks: "react_to_something_{{ ansible_system }}.yml"

You can then create tasks/react_to_something_Linux.yml and tasks/react_to_something_Win32NT.yml which will be included by your handler depending on the remote target system.

You can debug the ansible_system variable on your different system to see if it correctly matches my above examples. To go further:

  • you may want to explore the ansible_distribution* vars to see if they better suit your needs (not sure they exist on windows...)
  • you can have a look at the first_found lookup which will be helpfull if you need to load in a preferred order e.g. a very specific set of tasks for a very precise distribution or a general set of tasks for an overall global system flavor or a default set of tasks in case none of the previous matched.
  • Related