Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restore Selinux file context in ansible on multiple directories

Tags:

yaml

ansible

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?

like image 443
crusadecoder Avatar asked Dec 23 '22 16:12

crusadecoder


2 Answers

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' }
like image 104
crusadecoder Avatar answered May 20 '23 16:05

crusadecoder


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.

like image 45
Kevin Keane Avatar answered May 20 '23 16:05

Kevin Keane