Ansible: SELinux and multiple handlers

Hi,

I’m currently facing a problem that seems simple but it’s not. Here goes.

I rent a series of servers at Scaleway.com. In the default configuration SELinux is deactivated. So the first thing I do after installing Rocky Linux 8 is enable SELinux in enforcing mode:

- name: Enable SELinux
  ansible.posix.selinux:
    policy: targeted
    state: enforcing

This action would require no less than two actions:

  1. Create an empty /.autorelabel file (so the whole filesystem gets relabeled after the next reboot).
  2. Reboot.

Now how would I translate this in Ansible syntax? Here’s what I imagine:

notify: Relabel
notify: Reboot

But as far as I know, multiple handlers are not possible. And I’d also have to make sure that the Relabel handler is actually executed before the Reboot handler, which is not sure.

Any suggestions ?

I’ll answer this myself, since I just found a solution. Here goes:

- name: Enable SELinux
  ansible.posix.selinux:
    policy: targeted
    state: enforcing
  notify: Relabel

And here’s the content of handlers/main.yml :

- name: Relabel
  ansible.builtin.file:
    path: /.autorelabel
    state: touch
  notify: Reboot

- name: Reboot
  ansible.builtin.reboot:

Tested, and it works. But I’m still open for suggestions if you have a better idea.

Multiple should be possible. See ansible - Order of notify handlers - Stack Overflow

IIRC, I did try (and fail) two notify lines myself too.


Alternative is to register on the selinux task and conditionally touch the file, if selinux task did change system.

Handlers are nice when multiple tasks may require action X, but you need to do X only once, after all those tasks. I presume that you don’t need to touch /.autorelabel for any other reason than that one task?

1 Like

Yes. So a notify cascade makes sense here. Even though it’s a bit awkward.

By the way, here’s my first collection of roles and playbooks: