Introduction
Two Ansible modules do most of this work. ansible.posix.sysctl writes and applies kernel parameters, and community.general.modprobe loads kernel modules at boot. The part that breaks in production is ordering. Any sysctl key that lives under a module’s namespace only exists after that module is loaded, so the playbook must load modules first and apply sysctl second. A run that passes on Debian and fails on RHEL with net.bridge.bridge-nf-call-iptables: No such file or directory is almost always a playbook that applied sysctl before br_netfilter was loaded.
The distribution split adds two more requirements. Debian and RHEL disagree on which keys and modules exist in a given kernel, and both accept sysctl files from several directories with different precedence. The playbook needs per-family variable files, an explicit sysctl_file target instead of the module default, and a read-back step so a silent no-op does not pass as success. Get those three in place and the same role runs on Debian 12 and RHEL 9 without forking.
Where the settings actually live
Runtime sysctl values are exposed under /proc/sys/. The dotted key net.ipv4.ip_forward is the file /proc/sys/net/ipv4/ip_forward. Writing to that file changes the value for the running kernel and disappears on reboot. Persistence comes from configuration read by systemd-sysctl.service at boot and by sysctl --system when run manually.
On systemd-based Debian and RHEL, sysctl.d files are read from /etc/sysctl.d/, /run/sysctl.d/, /usr/local/lib/sysctl.d/, and /usr/lib/sysctl.d/ (plus /lib/sysctl.d/ on some systems). Files in /etc/ override files with the same name in /run/ or /usr/, so a same-named vendor file in a lower-priority directory is ignored. Across different file names, all configuration files are sorted lexicographically regardless of directory, and the entry in the lexicographically latest file wins for a given key. sysctl --system also reads /etc/sysctl.conf last, which means a leftover key there can override a value you wrote in /etc/sysctl.d/.
Kernel modules follow a different path. The boot-time module list is /etc/modules-load.d/*.conf on systemd systems (and /etc/modules on older ones). Modprobe directives (blacklist, install, options, alias) live in /etc/modprobe.d/*.conf. Modern kmod reads /run/modprobe.d/, /etc/modprobe.d/, /usr/local/lib/modprobe.d/, /usr/lib/modprobe.d/, and /lib/modprobe.d/. Writing to /etc/modprobe.d/ is the safe default because the other directories are package-managed and can be overwritten on upgrade.
This matters because ansible.posix.sysctl defaults its sysctl_file to /etc/sysctl.conf. That default puts every managed key into a single unnumbered file, and because /etc/sysctl.conf is applied after all the sysctl.d directories, a key that also appears there keeps the value from that file. Writing a numbered drop-in under /etc/sysctl.d/ keeps managed keys separate from legacy ones and makes precedence visible in the filename. Always set sysctl_file explicitly.
The modules and when to hand-roll
ansible.posix.sysctl takes a key, a value, a target file, and three booleans. sysctl_set: true verifies the live value and sets it with sysctl -w when needed. reload: true (the default) runs sysctl -p against the target file after it is updated. state: present (the default) writes the line; state: absent removes it. The ignoreerrors flag maps to sysctl -e and suppresses errors for unknown keys, which is useful during a migration but hides real failures if used broadly.
community.general.modprobe takes a module name and a few parameters. state: present loads the module now; state: absent unloads it. params passes module options to modprobe. persistent controls boot-time persistence on systemd-based distributions (its default is disabled, which leaves persistence files alone): present adds the module name to /etc/modules-load.d/ and parameters to /etc/modprobe.d/, while absent comments those entries out so the module is not loaded on next reboot. It does not write a modprobe blacklist directive and it is separate from state (loading vs. persistence are different switches).
The module layer covers the common case. Reach for hand-written files in three situations: when you need install <module> /bin/false instead of blacklist (blacklist only prevents auto-load, it does not stop an explicit modprobe), when you want a single template that renders a whole modprobe.d file with several directives at once, and when the target is an immutable /usr like RHEL CoreOS where only /etc is writable. In all three cases ansible.builtin.template or ansible.builtin.copy is the right tool.
Structuring variables per distribution
Keep a base file with the keys every host shares, then one file per ansible_os_family for the overrides. The base file also holds the module list, because modules differ across major versions.
sysctl_base: net.ipv4.ip_forward: "1" net.ipv4.conf.all.rp_filter: "1" net.ipv4.tcp_syncookies: "1" vm.swappiness: "10" fs.file-max: "2097152"
required_modules: - overlay - br_netfiltersysctl_os_extra: fs.inotify.max_user_watches: "524288" fs.inotify.max_user_instances: "1024"sysctl_os_extra: net.core.somaxconn: "4096" net.ipv4.tcp_max_syn_backlog: "8192"
required_modules: - overlay - br_netfilter - "{{ 'nf_conntrack' if ansible_distribution_major_version | int >= 8 else 'nf_conntrack_ipv4' }}"The version check on nf_conntrack is practical, not cosmetic. The conntrack module name changed mid-way through the RHEL 8 series: Red Hat merged the address-family-specific modules nf_conntrack_ipv4 and nf_conntrack_ipv6 into a single nf_conntrack module in RHEL 8.3, and the RHEL 8.3 release notes call out that blacklisting the old per-family names no longer works. Hardcoding the old name produces a modprobe: FATAL: Module nf_conntrack_ipv4 not found in directory /lib/modules/... failure. Selecting the name from ansible_distribution_major_version (and confirming with modinfo nf_conntrack on the target kernel) keeps one playbook across both.
Pin the collections in requirements.yml and install with ansible-galaxy collection install -r requirements.yml:
collections: - name: ansible.posix version: ">=1.5.0" - name: community.general version: ">=8.0.0"Loading modules before sysctl
The full playbook below does the ordering correctly. Modules load first, sysctl applies second, and a single handler reloads the system config once at the end instead of once per key.
- name: Enforce kernel and sysctl baseline hosts: linux become: true gather_facts: true
tasks: - name: Load distribution variables ansible.builtin.include_vars: file: "vars/sysctl-{{ ansible_os_family | lower }}.yml" tags: always
- name: Merge base and OS-specific sysctl values ansible.builtin.set_fact: sysctl_all: "{{ sysctl_base | combine(sysctl_os_extra | default({})) }}"
- name: Load required kernel modules now and at boot community.general.modprobe: name: "{{ item }}" state: present persistent: present loop: "{{ required_modules }}" loop_control: label: "{{ item }}"
- name: Apply sysctl keys from the merged baseline ansible.posix.sysctl: name: "{{ item.key }}" value: "{{ item.value }}" sysctl_file: /etc/sysctl.d/90-ansible-baseline.conf sysctl_set: true reload: false state: present loop: "{{ sysctl_all | dict2items }}" loop_control: label: "{{ item.key }}" notify: Reload sysctl
handlers: - name: Reload sysctl ansible.builtin.command: sysctl --system changed_when: falseTwo details are worth pointing out. reload: false on each key stops the module from running sysctl -p 40 times in the loop; the handler runs sysctl --system once at the end, which reads every file in /etc/sysctl.d/, /run/sysctl.d/, and /usr/lib/sysctl.d/ in precedence order. That second point is also a risk: sysctl --system also applies /etc/sysctl.conf, so a legacy key left there can still override the same key in your drop-in. If a key keeps reverting, grep /etc/sysctl.conf and the vendor files under /usr/lib/sysctl.d/ before assuming the module failed.
For large baselines (50 keys or more), render one template instead of looping over the module. The template is atomic, one file change, one handler fire, and the diff in --diff mode shows the whole file in one view.
- name: Write sysctl baseline as a single file ansible.builtin.template: src: templates/90-ansible-baseline.conf.j2 dest: /etc/sysctl.d/90-ansible-baseline.conf owner: root group: root mode: "0644" notify: Reload sysctl{% for key, value in sysctl_all.items() | sort %}{{ key }} = {{ value }}{% endfor %}The trade-off is real. The module gives per-key reporting: --check shows exactly which key would change, and --diff shows the old and new value for each line. The template gives one changed file and no per-key granularity. Choose the module when you want drift detection at key level, the template when the baseline is large enough that per-key reporting is noise.
Blacklisting modules that must not load
Some modules should never initialize. Cramfs, freevxfs, jffs2, hfs, hfsplus, and udf are common candidates in filesystem-hardening baselines; confirm the exact list against the benchmark or policy your organization follows. The blacklist directive stops udev from auto-loading them but does not stop modprobe <name> from a user with root. To block explicit loads, use install <module> /bin/false, which makes modprobe return failure.
- name: Disable unused filesystem modules ansible.builtin.copy: dest: /etc/modprobe.d/99-ansible-blacklist.conf owner: root group: root mode: "0644" content: | {% for mod in blacklisted_modules %} install {{ mod }} /bin/false blacklist {{ mod }} {% endfor %} notify: - Rebuild initramfs on Debian - Rebuild initramfs on RHEL handlers: - name: Rebuild initramfs on Debian ansible.builtin.command: update-initramfs -u -k all when: ansible_os_family == "Debian" changed_when: true
- name: Rebuild initramfs on RHEL ansible.builtin.command: dracut -f when: ansible_os_family == "RedHat" changed_when: trueThe initramfs rebuild is what makes the change effective in early boot. The initramfs image carries its own copy of the modules and their configuration, so a module blocked through /etc/modprobe.d/ on the running system can still be loaded from the image before the real root filesystem is mounted. Regenerating the image after a blacklist change keeps the two in sync. The cost is real: update-initramfs -u -k all and dracut -f both rewrite the boot image, so do it in a maintenance window and keep a way back into the host.
Be careful with install /bin/false on modules that real workloads use. squashfs is the classic mistake: it looks unused on a server, but snapd mounts snaps and some container runtimes depend on it. Blocking squashfs breaks snap on Ubuntu and stalls workloads that pull squashfs images. Audit with lsmod | grep <name> and grep -r <name> /etc/ before adding a module to the blocked list.
Verifying drift after the run
The playbook writes files and sets runtime values. It does not prove the kernel accepted them. Read back every key and assert the value matches the intended baseline. This catches the case where the sysctl write succeeded but the kernel clamped or rounded the value, and the case where a vendor file overrode the key after the handler ran.
- name: Read applied sysctl values ansible.builtin.command: cmd: "sysctl -n {{ item.key }}" loop: "{{ sysctl_all | dict2items }}" register: sysctl_readback changed_when: false
- name: Assert sysctl values match the baseline ansible.builtin.assert: that: - item.stdout == (item.item.value | string) fail_msg: "{{ item.item.key }} is {{ item.stdout }}, expected {{ item.item.value }}" loop: "{{ sysctl_readback.results }}" loop_control: label: "{{ item.item.key }}"Run the role in check mode against a staging host with --check --diff before it reaches production. The --diff output on the sysctl module shows each key’s old and new value, which is the fastest way to spot a key the team did not intend to touch.
Watch for tuned on RHEL
RHEL-family hosts often run TuneD, which can apply its own sysctl settings through the active profile. TuneD ships with reapply_sysctl = 1 in /etc/tuned/tuned-main.conf on current RHEL releases: after applying the profile it reapplies sysctl values from /run/sysctl.d/, /etc/sysctl.d/, and /etc/sysctl.conf, but it does not reapply files under /usr/lib/sysctl.d/. That ordering means a key you manage in /etc/sysctl.d/ normally survives a TuneD reapply, while a key that only lives in a package file under /usr/lib/sysctl.d/ can lose to the profile. The durable fix is to keep the enforced value in /etc/sysctl.d/ and, if a TuneD profile sets the same key, carry the override in a custom TuneD profile in /etc/tuned/profiles/ rather than setting it in two places. Check tuned-adm active and tuned-adm verify on RHEL hosts; verify reports when live values no longer match the active profile.
Troubleshooting real failures
These are the errors that show up most often when a sysctl and module baseline moves across Debian and RHEL.
sysctl: cannot stat /proc/sys/net/bridge/bridge-nf-call-iptables: No such file or directory. The br_netfilter module is not loaded, so the net.bridge.bridge-* keys do not exist. The fix is the ordering already shown above: load modules before sysctl, and add br_netfilter to required_modules. A shortcut with ignoreerrors: true hides the failure and leaves the key unapplied, which is worse than a hard failure because the next run reports green while the host is out of compliance.
modprobe: FATAL: Module nf_conntrack_ipv4 not found in directory /lib/modules/.... The module name does not exist on this kernel. The IPv4 and IPv6 conntrack modules were merged into nf_conntrack in RHEL 8.3 and later, so the per-family name is gone on any recent kernel. Select the name from ansible_distribution_major_version as shown in the variable file, and confirm the actual name with modinfo nf_conntrack on the target. The same failure appears on any host where a module was merged into another or removed from the kernel tree, so check the target rather than assuming a typo.
sysctl: permission denied on key 'kernel.unprivileged_userns_clone' (or a similar “permission denied” message from the module). The key exists but the write is refused. Two common causes are an unprivileged container where /proc/sys is mounted read-only, and a kernel policy or mount that blocks the write (for example a read-only /proc/sys or kernel lockdown). Confirm with id, mount | grep '/proc/sys', and cat /sys/kernel/security/lockdown when present; skip container-only keys on container targets and apply them on the host instead.
ERROR! couldn't resolve module/action 'community.general.modprobe'. The collection is not installed on the controller. Run ansible-galaxy collection install -r requirements.yml and confirm the path with ansible-galaxy collection list. If the collection is installed but still not found, check collections_paths in ansible.cfg; a role bundled with its own ansible.cfg that sets collections_paths to a project directory will not see a collection installed globally.
sysctl: permission denied on key 'net.ipv4.ip_forward' after a successful write on the same host. This is the read-back step catching a kernel that rejected sysctl -w silently, or a later process that reset the value. Check for a conflicting sysctl --system run from another tool, for a Kubernetes or container runtime that reprograms the key on start, and for /etc/sysctl.conf holding a different value that gets applied last.
Distro differences and edge cases
Debian and RHEL releases that use systemd-sysctl follow the sysctl.d directory precedence described above, so the same sysctl.d drop-in approach works on modern releases in both families. Older, non-systemd releases handle sysctl configuration differently; if you still manage them, confirm their boot-time sysctl path before relying on /etc/sysctl.d/ and keep a separate task for that family.
On immutable hosts like Flatcar Container Linux or Red Hat CoreOS, /usr is read-only and /usr/lib/sysctl.d/ cannot be written. /etc/sysctl.d/ is a writable overlay and takes precedence, so the default target path works, but the role must not attempt to write a vendor file. Container images built on these hosts inherit the same restriction.
In containers, /proc/sys is a per-namespace view and many keys are read-only regardless of root. A playbook that targets a container with become: true will still fail on net.* keys outside its own network namespace. Gate the sysctl tasks on ansible_virtualization_type not in ['docker', 'podman', 'containerd'] and run them on the host, or use a dedicated container-security role that knows which keys are writable.
What this baseline leaves out
Kernel boot command line parameters (transparent_hugepage, intel_iommu, mitigations) live in GRUB, not in sysctl. Changing them needs grubby on RHEL or update-grub on Debian, followed by a reboot, which is a different role with a different blast radius. I/O scheduler tuning, cgroup v2 settings under /sys/fs/cgroup/, and SELinux booleans also fall outside the two modules covered here.
The baseline also does not manage sysctl keys that only exist inside a network namespace. A pod or a container with its own net namespace has its own /proc/sys/net/, and the host-level values set by this role do not apply inside it. If the workload needs a different net.core.somaxconn inside a container, set it in the container runtime or the pod spec, not in this playbook.
The scope that remains is the one that matters for most fleets: the kernel parameter baseline every Linux host should share regardless of role, applied idempotently, loaded in the right order, and verified against the running kernel instead of trusting the file write. That is a small amount of YAML, but the ordering and the read-back are what separate a role that runs from a role that converges.