There are two ways to set selinux contexts on a file in Ansible. One way is to use the setype argument to the file module. One problem with setting file context via the file module is that it only acts on the file and not the host’s selinux policy. This means that changes to the file’s context will NOT survive a relabel.
To work with the host’s selinux policy directly use the sefcontext module, and then run restorecon on the file. This will ensure the file retains the context you set in the event of a relabel.
In this example, I’m working with a test system named ans1.
--- - name: Demo setting selinux context on a file hosts: ans1 tasks: # The package policycoreutils-python-utils must # be present to do things with file contexts. - name: Ensure policycoreutils-python-utils is installed yum: name: policycoreutils-python-utils state: present # Create a file in /tmp with the root_t context - name: Create a file to set context on file: mode: '0644' owner: root path: /tmp/selinuxcheck setype: root_t state: touch - name: Set the tmp_t context on /tmp/selinuxcheck sefcontext: target: /tmp/selinuxcheck setype: tmp_t state: present notify: Run restorecon on /tmp/selinuxcheck # The sefcontext module only modifies SeLinux policy. # It is still necessary to run restorecon on the file. # A handler works well for this. handlers: - name: Run restorecon on /tmp/selinuxcheck command: restorecon -v /tmp/selinuxcheck ...
In this example I create a file on the managed host named /tmp/selinuxcheck and set a context of root_t on it. If I were to stop execution here and run an ad-hoc command to check its context, this is what I would see:
# ansible ans1 -a 'ls -lZ /tmp/selinuxcheck' ans1 | CHANGED | rc=0 >> -rw-r--r--. 1 root root unconfined_u:object_r:root_t:s0 0 Feb 13 11:23 /tmp/selinuxcheck
However, if execution is allowed to complete on the entire playbook, including invocation of the sefcontext module, the output of the ad-hoc command becomes:
# ansible ans1 -a 'ls -lZ /tmp/selinuxcheck' ans1 | CHANGED | rc=0 >> -rw-r--r--. 1 root root unconfined_u:object_r:tmp_t:s0 0 Feb 13 11:26 /tmp/selinuxcheck