6

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?

crusadecoder
  • 651
  • 1
  • 11
  • 26

2 Answers2

10

Ok finally came up with a logic that works. Hopefully this helps someone who has similar issues.

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

- name: Run restore context to reload selinux
  shell: restorecon -R -v /var/lib/{{ item.target }}
  when: filecontext.results[item.index]|changed
  with_items:
  - { index: 0, target: 'dir1' }
  - { index: 1, target: 'dir2' }
crusadecoder
  • 651
  • 1
  • 11
  • 26
  • I expected 'reload: True' in the first play to do the same thing as the next play. Is that not true? – Josiah Apr 05 '18 at 14:08
  • No, reload: True does something very different. From the ansible documentation: "Reload SELinux policy after commit. Note that this does not apply SELinux file contexts to existing files." – Kevin Keane May 20 '19 at 21:47
4

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.

Kevin Keane
  • 1,506
  • 12
  • 24