Project 9: Ansible SELinux Hardening Role

A comprehensive Ansible role that configures SELinux across a fleet of servers: enforcing mode, proper booleans for services, custom file contexts, and port definitions.

Quick Reference

Attribute Value
Primary Language YAML (Ansible)
Alternative Languages Puppet, Chef, SaltStack
Difficulty Level 2: Intermediate
Time Estimate 1-2 weeks
Knowledge Area SELinux Automation / Configuration Management
Tooling Ansible, ansible-selinux modules
Prerequisites Basic Ansible knowledge, Projects 1-2 completed

What You Will Build

A comprehensive Ansible role that configures SELinux across a fleet of servers: enforcing mode, proper booleans for services, custom file contexts, and port definitions.

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • Idempotent SELinux configuration → maps to state management
  • Handling different distro defaults → maps to policy variations
  • Testing SELinux changes safely → maps to operational safety
  • Role-based configuration (web, db, app) → maps to policy by function

Key Concepts

  • Ansible SELinux Modules: Ansible documentation (selinux, seboolean, sefcontext)
  • Configuration Management: Ansible for DevOps - Jeff Geerling
  • SELinux State Machine: Enforcing vs Permissive transitions
  • Fleet Management: CIS Benchmarks SELinux sections

Real-World Outcome

# roles/selinux_hardening/tasks/main.yml
---
- name: Ensure SELinux is enforcing
  ansible.posix.selinux:
    policy: targeted
    state: enforcing
  register: selinux_state

- name: Configure web server booleans
  ansible.posix.seboolean:
    name: "{{ item.name }}"
    state: "{{ item.state }}"
    persistent: true
  loop:
    - { name: httpd_can_network_connect, state: true }
    - { name: httpd_can_network_connect_db, state: true }
    - { name: httpd_execmem, state: false }
  when: "'webservers' in group_names"

- name: Set custom file contexts
  community.general.sefcontext:
    target: '/opt/myapp(/.*)?'
    setype: httpd_sys_content_t
    state: present
  notify: Restore SELinux contexts

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References

  • Main guide: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • “Ansible for DevOps” by Jeff Geerling