The Linux kernel exposes hundreds of tunables — socket backlog, swappiness, inotify limits, anti-spoofing flags — as files under /proc/sys, and the sysctl command line is the ordinary way to read and write them. A runtime change made with sysctl -w is lost on reboot; persistence lives in /etc/sysctl.conf and the drop-ins under /etc/sysctl.d, and only a reload bridges the files and the running kernel. Managing that triangle — live values, config files, and the reload that reconciles them — is exactly what configuration management is for.
Reemote is a pure-Python configuration-management library. Instead of a domain-specific language, you write an ordinary Python generator that yields operations against a host, gather typed facts from the target, and await a two-phase run that previews the whole plan before it changes anything. It needs no agent, no interpreter and no template file on the managed machine — only the procps tools every Linux base image already ships, plus a POSIX shell and an SSH connection.
Two modules cover the space, and the split is deliberate. The sysctl module manages the parameter: sysctl.setting treats one kernel key as the resource, gating a runtime half (sysctl -w, compared against the live Sysctl fact) and a persistence half (one keyed line in a config file, compared against SysctlFile) independently; sysctl.conf owns a whole config file as an ordered set of assignments. The sysctl_d module manages the drop-in file in /etc/sysctl.d: sysctl_d.file owns a named file end to end, sysctl_d.setting edits a single assignment inside one while preserving comments and foreign lines, sysctl_d.reload is the explicit activation step, and sysctl_d.prune retires everything outside an allowlist. Use sysctl when you care about a value and where it persists; use sysctl_d when you care about the file — its layout, its ownership, its place in the merge order, and when the kernel should read it.
Try the canonical example first
Install Python 3.13 or newer and Docker or Podman. The connector requires you to name the CLI explicitly; there is no default.
uv venv .venv
source .venv/bin/activate
uv pip install reemote
Save this as hello.py. It is the canonical example configured for Podman. The offline pytest suite simulates the connector, and the example was also verified live with Podman. Change both docker_cmd values to "docker" if that is your local CLI.
# hello.py
import asyncio
from reemote import files, format_log, format_plan, op, run
INVENTORY = [
{
"host": "demo0",
"family": "Alpine",
"connection": {
"connector": "docker",
"identifier": "alpine:3.20",
"docker_cmd": "podman",
},
},
{
"host": "demo1",
"family": "Alpine",
"connection": {
"connector": "docker",
"identifier": "alpine:3.20",
"docker_cmd": "podman",
},
},
]
def deploy(host):
yield op(
files.install,
name="Write a greeting",
content="Hello from reemote!\n",
dest="/tmp/reemote-hello.txt",
mode="0644",
)
yield op(
files.install,
name="Record the host name",
content=f"written on {host.name}\n",
dest="/tmp/reemote-host.txt",
mode="0644",
)
async def main():
plans, report, _ = await run(INVENTORY, deploy, dry=True)
print("== Dry run ==")
print(format_plan(plans))
assert report is None
_, report, _ = await run(INVENTORY, deploy)
print("\n== Applied ==")
assert report is not None
print(format_log(report))
asyncio.run(main())
Run it with python hello.py. The dry run connects to both containers and reads real state, but sends no mutating deploy commands inside them. The connector may still create, commit, and remove its temporary containers. The apply then advances through the two operations in lockstep: both hosts finish writing the greeting before either starts recording its name.
Verified output from Podman is shown below. The dry-run plan is host-major, while the apply log is step-major: both Write a greeting entries appear before either Record the host name entry.
== Dry run ==
demo0: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
demo0: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
demo1: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
demo1: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
== Applied ==
demo0: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo1: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo0: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'
demo1: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'
An image identifier creates a throwaway container for each host. On close, Reemote commits it to a new image and removes the container. That makes every run start fresh; idempotence is demonstrated later against an existing container instead.
Unlike the throwaway-container quickstart, the migration examples below reuse the same Ubuntu hosts, so repeated runs demonstrate convergence against persistent host state.
How sysctl configures the kernel
The sysctl -a dump is the kernel talking; everything else is an approximation of it. Five properties of that arrangement decide how an automation tool has to treat it.
-
Runtime is the truth, files are intent.
/proc/sysholds the live values;/etc/sysctl.confand/etc/sysctl.d/*.confhold what the host wants at boot.sysctl -w key=valuechanges the former, a reload (sysctl -p <file>orsysctl --system) bridges file to kernel, and nothing at all reconciles them continuously. A deploy has to read both sides and act on the difference. -
Persistence is spread across files, and order decides. Modern procps loads
/etc/sysctl.din lexicographic order, then/run/sysctl.d,/usr/local/lib/sysctl.d,/usr/lib/sysctl.dand/lib/sysctl.d— where a file is masked by an earlier file of the same basename — and applies the legacy/etc/sysctl.conflast. Inside one file, the last assignment of a key wins. That is why local policy belongs in a higher-numbered drop-in such as99-…: it overwrites rather than competes. -
Values are strings, and some hold several tokens.
net.ipv4.ip_local_port_rangeis10240 65535, and a few keys print space- or tab-separated lists. The dump can also format a value differently from the file that set it, so comparing wanted against actual has to parse assignments — splitting tokens and coercing integers — rather than diff bytes. -
Reading is cheap, writing is root. The whole dump and every config file are world-readable on most hosts, while
sysctl -wand writes under/etcneed elevation. A tool can preview an unlimited number of facts unprivileged and elevate only the mutations. - A kernel parameter cannot be unset. Removing a line from a config file changes what the next reload applies; the live value stays until something writes over it or the host reboots. The honest form of "absent" is therefore file-level: drop the assignment and leave the runtime alone.
The Reemote sysctl modules
The sysctl module answers the parameter's two questions — what does the kernel run, and what does the file say — with three facts. Sysctl is the live dump as a key -> value dict with simple values int-coerced, SysctlFile is the raw text of one named config file, and SysctlFiles is every administrator-managed file (/etc/sysctl.conf plus /etc/sysctl.d/*.conf) parsed into path -> {key: value}. Its two operations consume them per half: sysctl.setting gates a runtime sysctl -w against Sysctl and a keyed line edit against SysctlFile, so a value that is live but unpersisted gets only a file write, and a line that is on disk but drifted gets only a reload; sysctl.conf owns a whole file from an ordered tuple of (key, value) pairs, compares it through the same read-back, and reloads the file when an unchanged file still disagrees with the runtime. Flags follow the sysctl CLI: persist=False skips the file, sysctl_set=False skips the direct write, reload=False defers activation, and present=False means "remove the key's line" or "uninstall the file".
The sysctl_d module manages the drop-in itself as the resource. Its facts are directory-shaped: SysctlDropInFiles lists the *.conf files in a directory in merge order, SysctlDropInConfig parses the assignments of one named file, and SysctlEffective is the runtime dump kept as raw strings so it can be compared with file content without coercion games. sysctl_d.file writes a whole drop-in deterministically — a # Managed by reemote header plus one key = value line per setting, sorted by key — and, because it compares parsed assignments, a changed comment or reordered line never provokes a rewrite; sysctl_d.setting edits one key inside a file while preserving comments and foreign lines; sysctl_d.reload applies one file (sysctl -p) or the whole system configuration (sysctl --system) as a stateless request that always reports a change; and sysctl_d.prune removes every drop-in in a directory outside an explicit allowlist. The apply=False flag on the write operations is what makes staging possible: the file lands, and activation happens when you schedule the reload.
The split to keep in mind: sysctl keys a request on a parameter name, sysctl_d keys it on a file path. Neither module installs procps, neither manages the kernel itself, and neither writes to /run or the vendor directories — pair them with the apt module for packages, and use when=is_ubuntu so a mixed inventory skips hosts the family guard excludes rather than failing on them.
Managing kernel parameters in Python
Every shape the article needs is one request long:
- Set one parameter live and persist one line:
op(sysctl.setting, key=..., value=..., sudo=True). - Own a whole tuning file:
op(sysctl.conf, settings=(...), sysctl_file=..., sudo=True). - Own a numbered drop-in with a deterministic render:
op(sysctl_d.file, path=..., settings=(...), sudo=True). - Edit one assignment inside a drop-in, keeping its comments:
op(sysctl_d.setting, file=..., key=..., value=..., sudo=True). - Stage a file without touching the running kernel:
apply=False(orsysctl_set=False, reload=Falsein thesysctlnamespace). - Activate deliberately:
op(sysctl_d.reload, sudo=True), orfile=...for a scoped reload. - Remove a line or retire a file:
present=Falseon the same operations. - Read back either side: the
Sysctl,SysctlFile,SysctlFiles,SysctlDropInConfigandSysctlEffectivefacts, gathered fleet-wide withgather_fact.
Two conventions carry through every example below. Arguments passed to op() must stay hashable, so a profile is a tuple of (key, value) pairs rather than a dict — and the order of that tuple is the order written to the file. And the escalation flag belongs to the request (sudo=True) while the run-as user stays a property of the inventory: the spool transfer to /tmp always runs as the login user, and only the install step and the sysctl invocations are elevated.
Inventory for the sysctl hosts
The examples use the repository's real Ubuntu SSH host. Save an equivalent inventory as inventory.json:
[
{
"host": "ubuntu",
"family": "Ubuntu",
"connection": {
"connector": "ssh",
"address": "192.168.0.251",
"port": 22,
"username": "supervisor",
"key_path": "~/.ssh/id_ed25519"
},
"tags": ["ubuntu_host", "apt_package_manager"]
}
]
Replace the address, user and key path with your own. Every managed request writes under /etc, so the login needs passwordless sudo; verify the host key and populate ~/.ssh/known_hosts rather than disabling host-key checking, as the SSH connector reference describes. Check what the host already has before you start, because the existing drop-ins are not yours to overwrite:
ssh supervisor@192.168.0.251 'sysctl vm.swappiness; ls -l /etc/sysctl.conf /etc/sysctl.d'
Runnable examples for the inventory Ubuntu host
Clone the repository and edit its inventory.json, or replace that file with the inventory above:
git clone https://github.com/kimjarvis/reemote.git
cd reemote
The scripts under examples/articles/sysctl/ load that inventory, select only entries whose family is Ubuntu, and use sudo for the root-owned state. Mutating scripts preview by default and require --apply; the inspection script is read-only. They share one helper, sysctl_article_common.py, which holds the managed paths and the preview/apply driver.
| Example | Article concept |
|---|---|
sysctl_hello.py |
The canonical two operations against persistent SSH hosts |
sysctl_one_parameter.py |
One parameter live and persisted, with sysctl.setting
|
sysctl_network_profile.py |
A whole ordered tuning file with sysctl.conf
|
sysctl_security_profile.py |
A deterministic hardening drop-in owned by sysctl_d.file
|
sysctl_dropin_edit.py |
Two keyed edits that share one drop-in and still converge |
sysctl_staged_apply.py |
Stage a file with apply=False, activate later with sysctl_d.reload
|
sysctl_inspect.py |
Read back runtime, files and config/runtime drift |
sysctl_cleanup.py |
Remove every setting the article manages |
Every parameter this article sets is safe on a host you are logged into: none changes routing, disables a protocol, or touches the address carrying the session. Run a read-only preview from the repository root:
uv run python examples/articles/sysctl/sysctl_one_parameter.py
Run the canonical pair on a real host
The first script is the quickstart's two files.install operations, kept as the article's baseline against a persistent host: same requests, same preview-then-apply shape, SSH instead of a container, and a family guard so a RedHat host in the same inventory is skipped rather than failing.
# sysctl_hello.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Run the canonical two operations against persistent Ubuntu SSH hosts."""
import asyncio
import sys
from pathlib import Path
from reemote import files, op
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import execute, is_ubuntu, load_inventory, parser
def deploy(host):
yield op(
files.install,
name="Write a greeting",
content="Hello from reemote!\n",
dest="/tmp/reemote-hello.txt",
mode="0644",
when=is_ubuntu,
)
yield op(
files.install,
name="Record the host name",
content=f"written on {host.name}\n",
dest="/tmp/reemote-host.txt",
mode="0644",
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The preview reads the host and reports what it would write, without sending a mutating command:
== Preview ==
ubuntu: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
ubuntu: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
Preview only; pass --apply to change the hosts.
Because the host persists between runs, a second pass has something to be up to date about: both requests report no change and send no commands — the convergence behaviour every later example relies on.
Set one parameter live and in the config file
sysctl.setting is the module's single-parameter operation, and one request carries both halves of the job: it applies sysctl -w vm.swappiness=10 only when the live value differs, and it edits the keyed line in the persistence file only when the file's text lacks it. The write is a spool transfer plus an elevated install, followed by a scoped sysctl -p, so the file and the kernel are reconciled through the same command the administrator would type.
# sysctl_one_parameter.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Set one kernel parameter end to end with ``sysctl.setting``.
The example manages ``vm.swappiness`` in the legacy ``/etc/sysctl.conf``.
``sysctl.setting`` is the module's single-parameter operation, and it runs two
independent halves gated by two different facts: the runtime half compares the
live value from the ``Sysctl`` fact and applies ``sysctl -w`` only on a real
difference; the persistence half reads the file's raw text with ``SysctlFile``
and rewrites it only when the keyed line is missing or wrong. The write spools
the new text to ``/tmp`` as the login user, then one elevated ``sh -c`` installs
it ``0644`` and a scoped ``sysctl -p`` follows.
Because the file edit is keyed rather than appended, re-running the deploy
converges: the line is replaced in place, duplicate assignments collapse, and a
third pass sends no commands at all. Both halves write or apply root-owned
state, so the request elevates with ``sudo=True``.
Run it with::
uv run python examples/articles/sysctl/sysctl_one_parameter.py
uv run python examples/articles/sysctl/sysctl_one_parameter.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, sysctl
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import (
SWAPPINESS_KEY,
execute,
is_ubuntu,
load_inventory,
parser,
)
SWAPPINESS_VALUE = 10
def deploy(host):
yield op(
sysctl.setting,
name="Set vm.swappiness to 10",
key=SWAPPINESS_KEY,
value=SWAPPINESS_VALUE,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The preview already reads both halves and names each one's verdict in a single reason, joined by semicolons:
== Preview ==
ubuntu: Set vm.swappiness to 10 [changed: vm.swappiness not set to 10 at runtime, will apply; /etc/sysctl.conf missing or differs for vm.swappiness, will write]
Preview only; pass --apply to change the hosts.
The apply shows all four commands the request expanded into — the direct runtime write, the spool transfer, the elevated install, and the scoped reload that confirms the file through the same path sysctl --system would take at boot:
== Applied ==
ubuntu: Set vm.swappiness to 10 [changed: vm.swappiness not set to 10 at runtime, will apply; /etc/sysctl.conf missing or differs for vm.swappiness, will write]
$ sudo sysctl -w vm.swappiness=10
$ scp <sysctl conf> -> /tmp/reemote-sysctl-4bac2aa6ea0d0640/sysctl.conf
$ sudo sh -c 'mkdir -p /etc && cp /tmp/reemote-sysctl-4bac2aa6ea0d0640/sysctl.conf /etc/sysctl.conf && chmod 0644 /etc/sysctl.conf && rm -rf /tmp/reemote-sysctl-4bac2aa6ea0d0640'
$ sudo sysctl -p /etc/sysctl.conf
Running the same script again sends nothing, and each half reports its own agreement:
== Preview ==
ubuntu: Set vm.swappiness to 10 [no change: vm.swappiness already set to 10 at runtime; /etc/sysctl.conf already up to date for vm.swappiness]
== Applied ==
ubuntu: Set vm.swappiness to 10 [no change: vm.swappiness already set to 10 at runtime; /etc/sysctl.conf already up to date for vm.swappiness]
The two halves are why the operation exists at all. Hand-editing vm.swappiness on the host leaves the file current and the runtime drifted, and the next pass repairs only the runtime; adding the line to the file by hand leaves the runtime alone and the next pass issues only a reload. That gating is invisible in the second-pass output above, where both sides already agree.
Write an ordered network tuning profile
A profile is a list of decisions, not a bag of keys: which backlog to accept, which port range to allocate from, which timeout to shorten. sysctl.conf takes the whole ordered tuple and owns one file outright — the tuple's order is the file's order, and a multi-word value such as the local port range is written verbatim. The 99- prefix sorts after every vendor drop-in, so the profile wins for the keys it declares and never fights the distribution's own files.
# sysctl_network_profile.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Write an ordered network tuning profile with ``sysctl.conf``.
The example owns ``/etc/sysctl.d/99-reemote-network.conf`` as a whole file from
one tuple of ``(key, value)`` pairs. ``sysctl.conf`` is the file-oriented
counterpart of ``setting``: it renders the entire content from the settings and
compares that text against ``SysctlFile``, so a changed write is one spool
transfer plus one elevated install, followed by a scoped ``sysctl -p``. An
unchanged file is reloaded only when a managed runtime value still differs,
which is how a reboot or a hand-edit is pulled back into line without ever
touching a key the file does not own.
The settings are a tuple, not a dict, because ``op()`` arguments must be
hashable, and their order is the order written to the file. A multi-word value
such as the local port range is written verbatim. The default ``reload`` applies
the profile on a changed write; every value here is safe on a host you are
logged into, and none of it changes routing or the address carrying the session.
Run it with::
uv run python examples/articles/sysctl/sysctl_network_profile.py
uv run python examples/articles/sysctl/sysctl_network_profile.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, sysctl
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import (
NETWORK_DROPIN,
execute,
is_ubuntu,
load_inventory,
parser,
)
NETWORK_PROFILE = (
("net.core.somaxconn", 65535),
("net.core.netdev_max_backlog", 65535),
("net.ipv4.tcp_fastopen", 3),
("net.ipv4.ip_local_port_range", "10240 65535"),
("net.ipv4.tcp_fin_timeout", 15),
("net.ipv4.tcp_window_scaling", 1),
("net.core.rmem_max", 16777216),
("net.core.wmem_max", 16777216),
)
def deploy(host):
yield op(
sysctl.conf,
name="Apply the network tuning profile",
settings=NETWORK_PROFILE,
sysctl_file=NETWORK_DROPIN,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
One request, three commands: the spool transfer, the elevated install, and the scoped reload of exactly this file — no --system, so a tuned profile never re-applies configuration it does not own:
== Applied ==
ubuntu: Apply the network tuning profile [changed: sysctl config /etc/sysctl.d/99-reemote-network.conf missing or differs from the settings]
$ scp <sysctl conf> -> /tmp/reemote-sysctl-b5ef0e99861c8662/sysctl.conf
$ sudo sh -c 'mkdir -p /etc/sysctl.d && cp /tmp/reemote-sysctl-b5ef0e99861c8662/sysctl.conf /etc/sysctl.d/99-reemote-network.conf && chmod 0644 /etc/sysctl.d/99-reemote-network.conf && rm -rf /tmp/reemote-sysctl-b5ef0e99861c8662'
$ sudo sysctl -p /etc/sysctl.d/99-reemote-network.conf
The file on disk holds the tuple in the order it was declared:
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_fastopen = 3
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_window_scaling = 1
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
A second pass reports sysctl config already up to date (/etc/sysctl.d/99-reemote-network.conf) and sends nothing — including no reload, because the runtime values the first pass applied still hold. Drift is what summons the sysctl -p back: reboot the host, or overwrite a key by hand, and the unchanged file reloads itself on the next run without rewriting a byte.
Own a hardening drop-in with sysctl_d.file
Security baselines are the other half of sysctl work: martian logging, source-route rejection, reverse-path filtering, SYN cookies. The values matter, but so does the file — reviewers want to read one deterministic drop-in and see the policy, not infer it from a pile of keyed edits. That is sysctl_d's shape, and sysctl_d.file is its workhorse: the settings tuple is the file, rendered with a management header and one sorted key = value line per setting.
# sysctl_security_profile.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Harden the kernel with one whole-file drop-in from ``sysctl_d.file``.
The example owns ``/etc/sysctl.d/99-reemote-security.conf`` through the
`sysctl_d` namespace's file-oriented operation: the settings tuple is the file.
``sysctl_d.file`` parses the existing drop-in and compares *assignments*, so a
changed comment or a reordered line never provokes a rewrite, and the rendered
content is deterministic — a ``# Managed by reemote`` header followed by the
settings sorted by key. A changed write spools the text to ``/tmp``, installs it
``0644`` in one elevated step, and follows it with a scoped ``sysctl -p`` of
exactly this file.
Anti-spoofing and ICMP-hardening parameters are safe to set on a host you are
logged into: none of them changes routing, disables a protocol, or touches the
address carrying the session. Writing under ``/etc`` and reloading need root, so
the request carries ``sudo=True``.
Run it with::
uv run python examples/articles/sysctl/sysctl_security_profile.py
uv run python examples/articles/sysctl/sysctl_security_profile.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, sysctl_d
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import (
SECURITY_DROPIN,
execute,
is_ubuntu,
load_inventory,
parser,
)
# (key, value) pairs for the hardening drop-in; ``sysctl_d.file`` sorts them and
# renders one ``key = value`` line each.
HARDENING = (
("net.ipv4.conf.all.log_martians", 1),
("net.ipv4.conf.all.accept_source_route", 0),
("net.ipv4.conf.default.accept_source_route", 0),
("net.ipv4.conf.all.rp_filter", 1),
("net.ipv4.conf.default.rp_filter", 1),
("net.ipv4.conf.all.accept_redirects", 0),
("net.ipv4.conf.default.accept_redirects", 0),
("net.ipv4.conf.all.send_redirects", 0),
("net.ipv4.conf.default.send_redirects", 0),
("net.ipv4.icmp_echo_ignore_broadcasts", 1),
("net.ipv4.tcp_syncookies", 1),
("kernel.dmesg_restrict", 1),
("kernel.kptr_restrict", 2),
)
def deploy(host):
yield op(
sysctl_d.file,
name="Apply the security hardening drop-in",
path=SECURITY_DROPIN,
settings=HARDENING,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The write family in sysctl_d spools under its own /tmp prefix, and the reason line speaks in files, not keys:
== Applied ==
ubuntu: Apply the security hardening drop-in [changed: sysctl.d file /etc/sysctl.d/99-reemote-security.conf missing or differs from the settings]
$ scp <sysctl.d conf> -> /tmp/reemote-sysctl-d-7d4c31cb53379339/sysctl.conf
$ sudo sh -c 'mkdir -p /etc/sysctl.d /etc/sysctl.d && cp /tmp/reemote-sysctl-d-7d4c31cb53379339/sysctl.conf /etc/sysctl.d/99-reemote-security.conf && chmod 0644 /etc/sysctl.d/99-reemote-security.conf && rm -rf /tmp/reemote-sysctl-d-7d4c31cb53379339'
$ sudo sysctl -p /etc/sysctl.d/99-reemote-security.conf
The input tuple mixes all. and default. variants in an arbitrary order; the installed file is sorted and annotated:
# Managed by reemote
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.send_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.tcp_syncookies = 1
Sorting is what makes the operation converge through the comparison rather than around it: because the render is a pure function of the settings, the parsed read-back of the installed file equals the desired dict, and a second pass reports sysctl.d file already up to date even though the file's bytes could legally differ in order. The same discipline is why kernel.kptr_restrict and its neighbours are each written exactly once no matter how often the deploy runs — one whole-file request cannot duplicate a key, unlike a loop of appends.
Edit assignments without owning the file
Not every drop-in is yours to render. sysctl_d.setting is the keyed counterpart: it reads the file's raw text, replaces the key's first active line (collapsing duplicates, appending when missing), and leaves every other line — comments, blank lines, foreign assignments — exactly as it found them. Two requests can share one file when each edit reads the state the previous one installed:
# sysctl_dropin_edit.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Edit single assignments inside a drop-in with ``sysctl_d.setting``.
The example manages two inotify limits in ``/etc/sysctl.d/99-reemote-fs.conf``
with the keyed counterpart of ``sysctl_d.file``. Where ``file`` owns the whole
document, ``setting`` edits one assignment and keeps everything else: a private
raw-content fact reads the file's text, the operation replaces the key's first
active line (collapsing duplicates, appending it when missing), and unrelated
lines and comments survive untouched. That is the shape an override on someone
else's file has to take — this is also exactly how the operation would edit a
single key inside the vendor-maintained ``/etc/sysctl.conf``.
Both requests reload the file after a changed edit with a scoped ``sysctl -p``,
so raising the inotify watch limit takes effect immediately for anything that
re-creates its watches; already-running watchers keep their old limit until they
restart. The requests share one file, so the second edit reads the state the
first installed and the pair converges on the next run with no commands at all.
Run it with::
uv run python examples/articles/sysctl/sysctl_dropin_edit.py
uv run python examples/articles/sysctl/sysctl_dropin_edit.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, sysctl_d
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import (
FS_DROPIN,
execute,
is_ubuntu,
load_inventory,
parser,
)
INOTIFY_LIMITS = (
("fs.inotify.max_user_watches", 524288),
("fs.inotify.max_user_instances", 1024),
)
def deploy(host):
for key, value in INOTIFY_LIMITS:
yield op(
sysctl_d.setting,
name=f"Ensure {key}",
file=FS_DROPIN,
key=key,
value=value,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The first pass runs the two edits in order, each writing the file and reloading it; the second edit sees the watches line the first installed, so both keys end up in one file rather than clobbering each other:
== Applied ==
ubuntu: Ensure fs.inotify.max_user_watches [changed: fs.inotify.max_user_watches differs in /etc/sysctl.d/99-reemote-fs.conf, will update]
$ scp <sysctl.d conf> -> /tmp/reemote-sysctl-d-fa7d801096505555/sysctl.conf
$ sudo sh -c 'mkdir -p /etc/sysctl.d /etc/sysctl.d && cp /tmp/reemote-sysctl-d-fa7d801096505555/sysctl.conf /etc/sysctl.d/99-reemote-fs.conf && chmod 0644 /etc/sysctl.d/99-reemote-fs.conf && rm -rf /tmp/reemote-sysctl-d-fa7d801096505555'
$ sudo sysctl -p /etc/sysctl.d/99-reemote-fs.conf
ubuntu: Ensure fs.inotify.max_user_instances [changed: fs.inotify.max_user_instances differs in /etc/sysctl.d/99-reemote-fs.conf, will update]
$ scp <sysctl.d conf> -> /tmp/reemote-sysctl-d-fa7d801096505555/sysctl.conf
$ sudo sh -c 'mkdir -p /etc/sysctl.d /etc/sysctl.d && cp /tmp/reemote-sysctl-d-fa7d801096505555/sysctl.conf /etc/sysctl.d/99-reemote-fs.conf && chmod 0644 /etc/sysctl.d/99-reemote-fs.conf && rm -rf /tmp/reemote-sysctl-d-fa7d801096505555'
$ sudo sysctl -p /etc/sysctl.d/99-reemote-fs.conf
== Preview ==
ubuntu: Ensure fs.inotify.max_user_watches [no change: fs.inotify.max_user_watches already present in /etc/sysctl.d/99-reemote-fs.conf]
ubuntu: Ensure fs.inotify.max_user_instances [no change: fs.inotify.max_user_instances already present in /etc/sysctl.d/99-reemote-fs.conf]
== Applied ==
ubuntu: Ensure fs.inotify.max_user_watches [no change: fs.inotify.max_user_watches already present in /etc/sysctl.d/99-reemote-fs.conf]
ubuntu: Ensure fs.inotify.max_user_instances [no change: fs.inotify.max_user_instances already present in /etc/sysctl.d/99-reemote-fs.conf]
The contrast with the previous section is the module boundary in miniature: sysctl_d.file guarantees the whole file and would rewrite a hand-added comment away, while sysctl_d.setting guarantees only its one line and keeps whatever else the file has grown. Pick by who owns the file.
Stage a profile now, activate it later
Write-heavy hosts often want their dirty-page thresholds tuned, but a fleet-wide reload at an arbitrary moment is an operational decision, not a file-format one. The modules compose for exactly this: sysctl_d.file with apply=False puts the drop-in on disk and stops there, and the activation is a separate, deliberate, stateless request.
# sysctl_staged_apply.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Stage a VM writeback profile without applying it, and apply on demand.
Databases and write-heavy hosts often want their dirty-page thresholds tuned,
but an operator may not want a fleet-wide ``sysctl -p`` in the middle of the
night. This example splits the two steps the way the modules are designed to be
composed: ``sysctl_d.file`` with ``apply=False`` writes
``/etc/sysctl.d/99-reemote-io.conf`` and nothing more, so the values arrive on
disk and take effect on the next boot (or the next explicit reload) rather than
now. The same discipline exists in the ``sysctl`` namespace as
``setting(sysctl_set=False, reload=False)`` for a single keyed line.
Pass ``--reload`` to append the second half: ``sysctl_d.reload`` is the
module's one stateless operation — it reads no fact, reports a change every
time and always yields its command, here a ``sysctl --system`` that walks the
standard directories. That is correct behaviour for an activation step and the
reason it is a separate request you schedule deliberately, not a loop body.
Run it with::
uv run python examples/articles/sysctl/sysctl_staged_apply.py
uv run python examples/articles/sysctl/sysctl_staged_apply.py --apply
uv run python examples/articles/sysctl/sysctl_staged_apply.py --reload --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, sysctl_d
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import (
IO_DROPIN,
execute,
is_ubuntu,
load_inventory,
parser,
)
IO_PROFILE = (
("vm.dirty_ratio", 40),
("vm.dirty_background_ratio", 10),
)
def build_deploy(reload_system=False):
"""Stage the drop-in; optionally follow it with an explicit system reload."""
def deploy(host):
yield op(
sysctl_d.file,
name="Stage the VM writeback profile",
path=IO_DROPIN,
settings=IO_PROFILE,
apply=False,
sudo=True,
when=is_ubuntu,
)
if reload_system:
yield op(
sysctl_d.reload,
name="Activate every sysctl configuration",
sudo=True,
when=is_ubuntu,
)
return deploy
async def main(argv=None):
cli = parser(__doc__)
cli.add_argument(
"--reload",
action="store_true",
help="append a sysctl --system activation request after the write",
)
args = cli.parse_args(argv)
await execute(
load_inventory(args.inventory),
build_deploy(args.reload),
apply_changes=args.apply,
)
if __name__ == "__main__":
asyncio.run(main())
The staged apply ends at the install — no reload command, because apply=False said so:
== Applied ==
ubuntu: Stage the VM writeback profile [changed: sysctl.d file /etc/sysctl.d/99-reemote-io.conf missing or differs from the settings]
$ scp <sysctl.d conf> -> /tmp/reemote-sysctl-d-ad36cc8f424204b4/sysctl.conf
$ sudo sh -c 'mkdir -p /etc/sysctl.d /etc/sysctl.d && cp /tmp/reemote-sysctl-d-ad36cc8f424204b4/sysctl.conf /etc/sysctl.d/99-reemote-io.conf && chmod 0644 /etc/sysctl.d/99-reemote-io.conf && rm -rf /tmp/reemote-sysctl-d-ad36cc8f424204b4'
This is the state the inspector is built to catch: the file is current, the kernel is not. When the maintenance window arrives, --reload appends the activation request — and because the reload is stateless, it reports a change and runs even though the file write beside it is a no-op:
== Preview ==
ubuntu: Stage the VM writeback profile [no change: sysctl.d file already up to date (/etc/sysctl.d/99-reemote-io.conf)]
ubuntu: Activate every sysctl configuration [changed: will reload the system sysctl configuration]
== Applied ==
ubuntu: Stage the VM writeback profile [no change: sysctl.d file already up to date (/etc/sysctl.d/99-reemote-io.conf)]
ubuntu: Activate every sysctl configuration [changed: will reload the system sysctl configuration]
$ sudo sysctl --system
sysctl --system walks the full load order — the drop-in directories, then the legacy file — which is the honest activation for a fleet: it converges every managed value, not just the one file this script wrote. A scoped sysctl_d.reload(file=...) would issue sysctl -p for a single drop-in instead.
Inspect the result
Four facts cover what is worth knowing about a host, and this script gathers all of them across the inventory in concurrent round trips. It mutates nothing, and its --check flag turns the same read into a gate that exits nonzero while any managed assignment disagrees with the running kernel.
# sysctl_inspect.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Read back runtime and persisted sysctl state, and report config/runtime drift.
This script mutates nothing. It gathers the facts both sysctl namespaces offer:
* ``Sysctl`` — the live kernel settings as a ``key -> value`` dict, with simple
values int-coerced exactly as ``sysctl -a`` prints them;
* ``SysctlEffective`` — the same live settings but kept as raw strings, the
textual counterpart that makes a direct comparison against a config file safe;
* ``SysctlFiles`` — every ``/etc/sysctl.conf`` and ``/etc/sysctl.d/*.conf`` file
the administrator manages, parsed into ``path -> {key: value}``;
* ``SysctlDropInFiles`` / ``SysctlDropInConfig`` — the drop-ins in one directory
and the assignments in a single named file.
Comparing what a file *says* against what the kernel *runs* is the whole point:
a value can be on disk but not applied (drifted, or staged with ``apply=False``),
or live but unpersisted (set by hand, lost on reboot). ``Sysctl`` and
``SysctlEffective`` read the shared runtime state; the file facts read the shared
content store, so an install or removal from the other examples shows up here
immediately. The comparison normalises whitespace tokens, because ``/proc``
prints multi-value parameters like ``net.ipv4.ip_local_port_range`` with tab
separators while the config file uses spaces — the same value, differently
spaced. Pass ``--check`` to exit nonzero while any managed drop-in disagrees
with the running kernel.
Run it with::
uv run python examples/articles/sysctl/sysctl_inspect.py
uv run python examples/articles/sysctl/sysctl_inspect.py --check
"""
import asyncio
import sys
from pathlib import Path
from reemote import (
Host,
Sysctl,
SysctlDropInConfig,
SysctlEffective,
SysctlFiles,
gather_fact,
)
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import (
MANAGED_DROPINS,
SWAPPINESS_KEY,
load_inventory,
parser,
)
async def collect(hosts):
"""Gather the runtime dump and the persisted files, then compute drift."""
typed = await gather_fact(hosts, Sysctl)
runtime = await gather_fact(hosts, SysctlEffective)
files = await gather_fact(hosts, SysctlFiles)
parsed = {}
for path in MANAGED_DROPINS:
configs = await gather_fact(hosts, SysctlDropInConfig, path)
parsed[path] = configs
rows = {}
for host in hosts:
live = runtime[host.name]
persisted = files[host.name]
managed = {
key: value
for path, per_host in parsed.items()
for key, value in per_host[host.name].items()
}
drift = {}
for key, wanted in managed.items():
current = live.get(key)
# ``/proc`` separates multi-token values with tabs; files use spaces.
if current is None or " ".join(str(current).split()) != " ".join(
str(wanted).split()
):
drift[key] = (wanted, current)
rows[host.name] = {
"files": sorted(persisted),
"managed": {
path: bool(parsed[path][host.name]) for path in MANAGED_DROPINS
},
"swappiness": typed[host.name].get(SWAPPINESS_KEY),
"drift": drift,
}
return rows
def converged(rows):
"""Whether every host has applied every managed assignment it declares."""
return all(not row["drift"] for row in rows.values())
async def main(argv=None):
cli = parser(__doc__, mutating=False)
cli.add_argument(
"--check",
action="store_true",
help="exit nonzero while any managed assignment differs at runtime",
)
args = cli.parse_args(argv)
inventory = load_inventory(args.inventory)
hosts = [Host.from_inventory(entry) for entry in inventory]
try:
rows = await collect(hosts)
finally:
await asyncio.gather(*(host.aclose() for host in hosts))
for name, row in rows.items():
print(f"== {name} ==")
print("persisted files:")
for path in row["files"]:
kind = "managed" if path in MANAGED_DROPINS else "unmanaged"
print(f" {path} [{kind}]")
print("managed drop-ins:")
for path, has_settings in row["managed"].items():
state = "has assignments" if has_settings else "absent or empty"
print(f" {path}: {state}")
print(f"{SWAPPINESS_KEY} (typed runtime fact): {row['swappiness']!r}")
if row["drift"]:
print("config/runtime drift:")
for key, (wanted, current) in sorted(row["drift"].items()):
print(f" {key}: file says {wanted!r}, kernel runs {current!r}")
else:
print("no config/runtime drift")
if args.check:
if not converged(rows):
drifting = [name for name, row in rows.items() if row["drift"]]
print(f"drift on: {', '.join(drifting)}")
raise SystemExit(1)
print("every managed assignment is live")
return rows
if __name__ == "__main__":
asyncio.run(main())
After every write example has run — including the staged one followed by its reload — the output reads as one converged picture:
== ubuntu ==
persisted files:
/etc/sysctl.conf [unmanaged]
/etc/sysctl.d/99-reemote-fs.conf [managed]
/etc/sysctl.d/99-reemote-io.conf [managed]
/etc/sysctl.d/99-reemote-network.conf [managed]
/etc/sysctl.d/99-reemote-security.conf [managed]
managed drop-ins:
/etc/sysctl.d/99-reemote-network.conf: has assignments
/etc/sysctl.d/99-reemote-security.conf: has assignments
/etc/sysctl.d/99-reemote-fs.conf: has assignments
/etc/sysctl.d/99-reemote-io.conf: has assignments
vm.swappiness (typed runtime fact): 10
no config/runtime drift
every managed assignment is live
Before the writes ran, the listing showed only the vendor's own files; between the staged apply and its reload, --check printed vm.dirty_ratio: file says '40', kernel runs '20'-style drift lines and exited 1 — the shape you want in a pipeline that must not proceed against a half-activated host. The whitespace normalisation is not theoretical: a real Ubuntu kernel prints net.ipv4.ip_local_port_range as 10240 and 65535 separated by a tab, so a byte comparison against the file's space would report permanent phantom drift. Note also what the typed fact answers: 10, an int, because Sysctl coerces exactly as the dump prints, while SysctlEffective keeps "10" for the string-safe file comparison.
Remove the managed settings
The article's state is one keyed line and four drop-ins, and teardown uses each write family's own removal mode — never a directory sweep:
# sysctl_cleanup.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Remove every persistent setting the sysctl article manages.
Teardown mirrors the two write families. The single legacy assignment is dropped
with ``sysctl.setting(present=False)``, which removes only the ``vm.swappiness``
line from ``/etc/sysctl.conf`` and leaves the file's other content (and the
running kernel value) untouched — a loaded parameter cannot be unset. The whole
drop-in files are removed with the file operations' own ``present=False`` mode:
``sysctl.conf`` uninstalls the network profile it wrote, and ``sysctl_d.file``
uninstalls the three it owns. All three reload with ``apply=False`` / removal
mode, because reloading a file that no longer exists would re-apply unrelated
configuration; the removals only change persistence, never the live kernel.
Every request is idempotent: once a line or file is gone the operation reads the
current state, sees nothing to remove, and issues no command — so a second run of
this script is a clean no-op, which is the convergence check the article runs.
Run it with::
uv run python examples/articles/sysctl/sysctl_cleanup.py
uv run python examples/articles/sysctl/sysctl_cleanup.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, sysctl, sysctl_d
sys.path.insert(0, str(Path(__file__).resolve().parent))
from sysctl_article_common import (
LEGACY_CONF,
SWAPPINESS_KEY,
execute,
is_ubuntu,
load_inventory,
parser,
)
SYSCTL_D_DROPINS = (
"/etc/sysctl.d/99-reemote-security.conf",
"/etc/sysctl.d/99-reemote-fs.conf",
"/etc/sysctl.d/99-reemote-io.conf",
)
def deploy(host):
# Drop the one keyed line, leaving /etc/sysctl.conf and its comments in place.
yield op(
sysctl.setting,
name=f"Remove {SWAPPINESS_KEY} from the legacy config",
key=SWAPPINESS_KEY,
value=0,
present=False,
sysctl_file=LEGACY_CONF,
reload=False,
sudo=True,
when=is_ubuntu,
)
# Uninstall the whole-file drop-ins this article wrote.
yield op(
sysctl.conf,
name="Remove the network tuning drop-in",
settings=(),
sysctl_file="/etc/sysctl.d/99-reemote-network.conf",
present=False,
sudo=True,
when=is_ubuntu,
)
for path in SYSCTL_D_DROPINS:
yield op(
sysctl_d.file,
name=f"Remove {path.rsplit('/', 1)[-1]}",
path=path,
settings=(),
present=False,
apply=False,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
== Applied ==
ubuntu: Remove vm.swappiness from the legacy config [changed: runtime value left unchanged (present=False); vm.swappiness present in /etc/sysctl.conf, will remove]
$ scp <sysctl conf> -> /tmp/reemote-sysctl-4bac2aa6ea0d0640/sysctl.conf
$ sudo sh -c 'mkdir -p /etc && cp /tmp/reemote-sysctl-4bac2aa6ea0d0640/sysctl.conf /etc/sysctl.conf && chmod 0644 /etc/sysctl.conf && rm -rf /tmp/reemote-sysctl-4bac2aa6ea0d0640'
ubuntu: Remove the network tuning drop-in [changed: sysctl config /etc/sysctl.d/99-reemote-network.conf present, will remove]
$ sudo rm -f /etc/sysctl.d/99-reemote-network.conf
ubuntu: Remove 99-reemote-security.conf [changed: sysctl.d file /etc/sysctl.d/99-reemote-security.conf present, will remove]
$ sudo rm -f /etc/sysctl.d/99-reemote-security.conf
ubuntu: Remove 99-reemote-fs.conf [changed: sysctl.d file /etc/sysctl.d/99-reemote-fs.conf present, will remove]
$ sudo rm -f /etc/sysctl.d/99-reemote-fs.conf
ubuntu: Remove 99-reemote-io.conf [changed: sysctl.d file /etc/sysctl.d/99-reemote-io.conf present, will remove]
$ sudo rm -f /etc/sysctl.d/99-reemote-io.conf
The line removal is still a whole-file rewrite through the same spool — the operation edits the text rather than sed-ing it in place — and every file removal is a single elevated rm -f. A second run reports no change for all five requests and sends nothing. The reason on the first line is the one to remember: the runtime values outlive their files by design, because "unset" is not a kernel concept. Leaving vm.swappiness=10 live until the next reload or reboot is correct behaviour, and saying so in the reason line is the module's way of keeping an operator honest about what teardown did and did not do.
Test the examples, then check convergence
The focused pytest suite imports every script, validates the inventory it reads, runs each deploy twice against a persistent simulated host, replays the sequences below and checks that the article's Python fences match the runnable files:
.venv/bin/python -m pytest -q tests/test_sysctl_article_examples.py
For the real Ubuntu host, preview every script first, then apply the configuration examples in this order:
uv run python examples/articles/sysctl/sysctl_hello.py --apply
uv run python examples/articles/sysctl/sysctl_one_parameter.py --apply
uv run python examples/articles/sysctl/sysctl_network_profile.py --apply
uv run python examples/articles/sysctl/sysctl_security_profile.py --apply
uv run python examples/articles/sysctl/sysctl_dropin_edit.py --apply
uv run python examples/articles/sysctl/sysctl_staged_apply.py --apply
uv run python examples/articles/sysctl/sysctl_staged_apply.py --reload --apply
uv run python examples/articles/sysctl/sysctl_inspect.py --check
Then repeat them. Every command below should report no changes and send no commands:
uv run python examples/articles/sysctl/sysctl_hello.py --apply
uv run python examples/articles/sysctl/sysctl_one_parameter.py --apply
uv run python examples/articles/sysctl/sysctl_network_profile.py --apply
uv run python examples/articles/sysctl/sysctl_security_profile.py --apply
uv run python examples/articles/sysctl/sysctl_dropin_edit.py --apply
uv run python examples/articles/sysctl/sysctl_staged_apply.py --apply
The --reload variant is deliberately absent from the second list: sysctl_d.reload is stateless, so a second pass reports a change and runs sysctl --system again, which is the correct behaviour for an activation command and the wrong thing to demonstrate as idempotence. Finish by removing the settings and proving the removal converges:
uv run python examples/articles/sysctl/sysctl_cleanup.py --apply
uv run python examples/articles/sysctl/sysctl_cleanup.py --apply
uv run python examples/articles/sysctl/sysctl_inspect.py
The second sysctl_cleanup.py pass reports no change for all five requests, and the final inspection lists the legacy /etc/sysctl.conf as unmanaged with no drop-ins under management left.
Implementation summary
Reemote's sysctl support is five facts and six operations split across two namespaces by what they treat as the resource. The sysctl module keys on the parameter: Sysctl dumps the live kernel as typed values, SysctlFile returns one file's raw text, SysctlFiles parses the administrator's whole config set, and sysctl.setting reconciles a key through two independently gated halves — sysctl -w against the runtime fact, a keyed line edit against the file fact — followed by a scoped sysctl -p; sysctl.conf owns a whole file from an ordered tuple of pairs and reloads it when an unchanged file still disagrees with the kernel. The sysctl_d module keys on the file: SysctlDropInFiles lists a directory in merge order, SysctlDropInConfig parses one drop-in's assignments, SysctlEffective keeps the runtime dump as strings, and the four operations act on files — a deterministic sorted whole-file write with parsed-content comparison, a comment-preserving keyed edit, a stateless sysctl -p/sysctl --system reload, and an allowlisted prune.
Both write families share one discipline: read-back before writing, an unprivileged spool transfer to a /tmp directory derived from the destination's hash, and one elevated shell step that installs 0644 and deletes the spool — so the only commands under sudo are the ones that must be, and an unchanged file sends nothing at all. Values converge through parsing rather than byte luck, which is why hand-edited order or comments never fight the deploy. The practical result is a sysctl workflow with no templates and no handlers: a profile is a hashable tuple in an ordinary Python function, staging and activation are two requests you schedule, removal is present=False with the runtime honestly left alone, and the preview shows the host state every decision came from. The module references list the complete API — sysctl and sysctl_d — and the examples index describes the shared real-host execution contract.
References
sysctl background
- The sysctl Command in Linux (Linuxize)
- Sysctl and kernel tuning overview (Linux Audit)
- Persistent kernel settings with /etc/sysctl.d (Gnome IT Solutions)
- Linux kernel hardening sysctl guide (NHIMG)
Reemote documentation: https://reemote.org/
Install:
pip install reemote(Python 3.13+)License: EPL-2.0
Discord: https://discord.gg/de8MqzA3E
Top comments (1)
Check mode, lockstep execution, no DSL.