Restore Selinux file context in ansible on multiple directories

Viewed 7319

I am currently using the sefcontext module to manage my servers SeLinux file context

Below is an example of a task used to manage some of the directories.

name: Set selinux policy for directories
sefcontext:
 target: '{{ item.target }}(/.*)?'
 setype: "{{ item.setype }}"
 reload: True
 register: "{{item.register}}"
 state: present
with_items:
- { target: '/var/lib/dir1', setype: 'public_content_rw_t', register: 'dir1' }
- { target: '/var/lib/dir2', setype: 'public_content_rw_t', register: 'dir2' }

The problem i am running into now is that doing something like this isn't working to restore the file labels and also for idempotency

name: Run restore context to reload selinux
shell: restorecon -Rv /var/lib/{{ item.shell }}
when: "{{ item.when }}"
with_items:
- { shell: 'dir1', when: 'dir1|changed' }
- { shell: 'dir2', when: 'dir2|changed' }

Any idea how i can restore file labels on multiple directories while preserving idempotency?

2 Answers

The easiest way to solve this may be with a handler:

name: Set selinux policy for directories
sefcontext:
 target: '{{ item.target }}(/.*)?'
 setype: "{{ item.setype }}"
 reload: True
 state: present
with_items:
- { target: '/var/lib/dir1', setype: 'public_content_rw_t' }
- { target: '/var/lib/dir2', setype: 'public_content_rw_t' }
notifies:
  - Run restore context to reload selinux

And in your handlers/main.yaml, you would then have this task:

name: Run restore context to reload selinux
shell: restorecon -Rv /var/lib/{{ item }}
with_items:
- 'dir1'
- 'dir2'

Both using a handler, and using the filecontext from the earlier solution, have the drawback that they will not be truly idempotent in that they will not be called if sefcontext has already been set earlier.

Related