27.2. Managing Local Configuration as Code
Every change an administrator makes to a running system lands somewhere in
/etc: services enabled, packages' settings adjusted, keys installed,
policies edited. Treat that tree as unmanaged state and it drifts - a
change made in an emergency survives long after the emergency, a fix
applied to one host never reaches its twin, and "what did this file look
like before?" has no answer. etckeeper turns /etc into a version
control repository: a full history of every file, with the metadata
(chmod values, owners) that Git alone does not record, committed
automatically around package operations and available for diff, blame,
and rollback. This section runs on auto1.
27.2.1. Tracking /etc Changes with etckeeper
etckeeper stores its repository in /etc/.git (Git is the default and
the one used here), keeps permission and ownership metadata in
/etc/.etckeeper, and installs APT hooks that commit before and after
every package transaction. Install it:
$ sudo apt install etckeeper
Reading package lists...
Building dependency tree...
Reading state information...
etckeeper is already the newest version (1.18.22-2).
Summary:
Upgrading: 0, Installing: 0, Removing: 0, Not Upgrading: 66
Confirm the package is in the installed state:
$ dpkg-query -W -f='${Status}\n' etckeeper
install ok installed
etckeeper subcommand |
Description |
|---|---|
init |
Create the repository in /etc/.git; the first commit is yours to make. |
commit MESSAGE |
Commit all current /etc changes, including untracked files. |
vcs GIT-ARGS |
Run git in /etc - log, diff, show, revert all work. |
vcs config KEY VALUE |
Set repository-local Git configuration. |
unclean |
Exit successfully while /etc has uncommitted changes. |
uninit |
Remove the repository and etckeeper's metadata; prompts unless -f is given. |
Initialize the repository:
$ sudo etckeeper init
Initialized empty Git repository in /etc/.git/
Git prints a hint on standard error that the default branch name master
is configurable with init.defaultBranch; it is cosmetic here, and the
repository works on the default branch. Give the repository a commit
identity so history attributes changes - one pair of commands:
$ sudo etckeeper vcs config user.name root@auto1
$ sudo etckeeper vcs config user.email root@auto1
Neither command prints anything. Now commit the initial state:
$ sudo etckeeper commit 'Initial etckeeper commit'
[master (root-commit) 5b320e4] Initial etckeeper commit
Author: john <john@auto1>
1216 files changed, 35027 insertions(+)
create mode 100755 .etckeeper
create mode 100644 .gitignore
create mode 100644 .updated
create mode 100644 X11/Xsession.d/90gpg-agent
...
create mode 100644 wgetrc
Selected output - the listing continues through all 1216 files. The
first commit records the whole tree once, so every later change is a
diff against a known baseline. Note the Author: line: etckeeper
attributes commits made through sudo to the invoking user, so the
history shows who made each change, not merely that root did. The
.etckeeper file is where permissions and ownerships live - Git records
file content only, and without that side file a
chmod 440 /etc/sudoers.d/foo would be invisible to history.
Put the mechanism to work. Here is a small configuration file in the
workspace, config/handbook-demo.conf:
# Local demonstration configuration tracked with etckeeper.
report_schedule = "15 3 * * *"
retention_days = 30
Install it into /etc - install copies and sets the mode in one step,
which is why this chapter prefers it over cp for anything destined for
/etc:
install option |
Description |
|---|---|
-m MODE |
Set the destination mode. |
-o OWNER -g GROUP |
Set the destination owner and group. |
-d DIR |
Create DIR (with -m, at that mode) instead of copying. |
-T |
Treat the destination as a regular file, never a directory. |
$ sudo install -m 0644 config/handbook-demo.conf /etc/handbook-demo.conf
The command is silent. Commit the change:
$ sudo etckeeper commit 'Track demo configuration'
[master 2ab59c9] Track demo configuration
Author: john <john@auto1>
2 files changed, 4 insertions(+)
create mode 100644 handbook-demo.conf
Two files: the new configuration and the .etckeeper metadata that
records its mode 0644. Review the history and the change itself:
$ sudo etckeeper vcs log --oneline -3
2ab59c9 Track demo configuration
5b320e4 Initial etckeeper commit
$ sudo etckeeper vcs show --stat --oneline HEAD
2ab59c9 Track demo configuration
.etckeeper | 1 +
handbook-demo.conf | 3 +++
2 files changed, 4 insertions(+)
From here on, most commits happen without you: the APT hook commits
around every package operation (/etc/apt/apt.conf.d/05etckeeper),
and a daily autocommit catches any leftover drift - through
/etc/cron.daily/etckeeper under cron, or through the
etckeeper.timer unit the package enables on systemd hosts. When an
upgrade is about to run with uncommitted changes present, the
pre-install hook commits them first with a saving uncommitted changes
in /etc message; set AVOID_COMMIT_BEFORE_INSTALL=1 in
/etc/etckeeper/etckeeper.conf to make it abort the transaction
instead, forcing a deliberate commit before anything touches your
half-finished edit.
27.2.2. Separating Secrets and Host-Specific Settings
A repository is a record, and records get read - copied to another
machine, pasted into a ticket, pushed to a shared backup. Two categories
of /etc content therefore need special treatment: secrets, which must
never enter the repository at all, and host-specific settings, which are
legitimate but must never be mistaken for a template for other machines.
Keep a secret out of the tree the same way Git ignores anything: a
.gitignore entry, set before the file's first etckeeper commit.
Create the file with the right ownership and mode from the start:
$ sudo install -m 0600 /dev/null /etc/handbook-secret.env
install with /dev/null as the source creates an empty file owned by
root with mode 0600 - installed before it holds anything, so the value
never exists in a more permissive state. Write the value into it with
your editor, or with a privileged append
(sudo sh -c 'printf "enrollment_token=Local-Only-Value\n" >>
/etc/handbook-secret.env' - the nested sh -c is needed because the
redirection itself must run as root). Check the result:
$ sudo stat -c '%a %U:%G %n' /etc/handbook-secret.env
600 root:root /etc/handbook-secret.env
Now exclude it from the repository:
$ sudo sh -c 'printf "handbook-secret.env\n" >> /etc/.gitignore'
Verify both halves of the exclusion - that Git's ignore rule matches the file, and that the file is therefore not tracked:
$ sudo etckeeper vcs check-ignore -v handbook-secret.env
.gitignore:58:handbook-secret.env handbook-secret.env
$ sudo etckeeper vcs ls-files handbook-secret.env
check-ignore -v names the rule (line 58 of /etc/.gitignore) that
matches; ls-files printing nothing is the second half of the proof:
the file exists on disk and is not in the repository. The new ignore
rule is itself an uncommitted /etc change - the disciplined move is
to commit it at once with a message of its own, and this exercise
deliberately does not, because the next section needs an
uncommitted change pending. Remember that choice when Section 27.2.4
shows what one big commit does with everything that was waiting. The
same discipline applies to anything under /etc that holds
credentials: Chapter 26 covers the file-level side
(modes, owners, backup exposure), and this section's rule is the
repository-level one - if a file's value must stay secret, its name
appears in the repository and its contents never do.
Encrypted-in-repo tools exist (git-crypt, sops), but for a per-host
/etc history the simpler boundary - keep secrets out entirely - is
stronger and easier to audit.
Host-specific settings are the other direction of the same rule. Files
like /etc/hostname, /etc/network/interfaces, host keys, and machine
IDs are per-host facts: correct on this machine, wrong on every other.
etckeeper is the right tool for tracking them on each host, and the
wrong tool for distributing them between hosts. The distribution side
belongs to a fleet system - Section 27.3 manages per-host values as
inventory variables, and Section 27.4 handles the identity files that
must be unique per machine.
27.2.3. Validating Configuration Before Atomic Replacement
The most dangerous automation failure mode is not "the new file was
wrong" - it is "the new file was wrong and the service now refuses to
start". The defense is a three-part habit: validate the candidate
before it is installed, install it by an atomic rename, and verify the
result afterwards. report.sh already demonstrated the pattern in
miniature; this section applies it to the one file family where a
syntax error can lock every administrator out: sudoers.
Here is the candidate, config/automation-sudoers - a delegation rule
in the style of Chapter 5, granting a
hypothetical automation group the right to run one specific helper as
root without a password:
Cmnd_Alias AUTOMATION_REPORT = /usr/local/bin/automation-report
%automation ALL=(root) NOPASSWD: AUTOMATION_REPORT
The fragment is safe to install even though the group does not exist
yet: a group rule matches nobody until the group has members. Check it
before anything touches /etc:
$ sudo visudo -cf config/automation-sudoers
/home/john/debian-handbook/automation/config/automation-sudoers: parsed OK
visudo -cf FILE parses the file without editing anything - the two
flags it is worth knowing:
visudo option |
Description |
|---|---|
-c |
Check mode: validate instead of editing; exit 0 when the file parses. |
-f FILE |
Check (or edit) this file rather than /etc/sudoers. |
Now the installation script,
bin/install-sudoers.sh, which stages, validates, and atomically
replaces:
#!/usr/bin/env bash
set -euo pipefail
candidate=${1:?usage: install-sudoers.sh CANDIDATE}
target=/etc/sudoers.d/automation-report
staged=$(mktemp /etc/sudoers.d/.automation-report.XXXXXX)
trap 'rm -f "$staged"' EXIT
install -o root -g root -m 0440 "$candidate" "$staged"
visudo -cf "$staged" >/dev/null
mv -f "$staged" "$target"
visudo -cf "$target" >/dev/null
printf 'installed %s\n' "$target"
Figure 27.2. The staged replacement pattern. A candidate is syntax-checked, copied to a root-owned staged file in the destination directory, checked again, and only then renamed onto the installed path. Any failure exits before the rename; the EXIT trap removes the staged copy and the installed file keeps its previous contents.
Every step earns its line: the staged file is created in
/etc/sudoers.d/ itself so the final mv is a same-filesystem rename -
atomic, never a partial file at the target path; install -o root -g
root -m 0440 fixes ownership and mode before the file can ever be
read as policy (sudoers fragments must be owned by root and be mode
0440); the second visudo -cf validates the staged copy exactly as
the target will see it; and >/dev/null on the two visudo calls is
the deliberate opposite of hiding errors - the check is silent on
success and its nonzero exit stops the script under set -e, so only a
failure is ever printed. Run it:
$ sudo bash bin/install-sudoers.sh config/automation-sudoers
installed /etc/sudoers.d/automation-report
$ sudo stat -c '%a %U:%G %n' /etc/sudoers.d/automation-report
440 root:root /etc/sudoers.d/automation-report
Now break it, the way automation actually breaks: a file that looks
plausible to a person and is not valid sudoers at all,
config/automation-sudoers.bad, containing the single line This is
not valid sudoers syntax. Record the installed file's digest first:
$ sudo sha256sum /etc/sudoers.d/automation-report
2c2557984214d0a096a92a8f1c4d6fab86391391be976b3b3645586bf2f66f5e /etc/sudoers.d/automation-report
Then attempt the bad candidate:
$ sudo bash bin/install-sudoers.sh config/automation-sudoers.bad
/etc/sudoers.d/.automation-report.WVrKtF:1:9: syntax error
This is not valid sudoers syntax
^~~
The script exits 1 with the staged file's name in the diagnostic, and
the mv on the next line never ran. Confirm what did not happen:
$ sudo sha256sum /etc/sudoers.d/automation-report
2c2557984214d0a096a92a8f1c4d6fab86391391be976b3b3645586bf2f66f5e /etc/sudoers.d/automation-report
The identical digest proves the installed policy was never touched, and
the EXIT trap removed the staged copy. That is the whole value of the
pattern: a bad file costs you an error message, not a machine whose
sudo is broken. The same three beats - candidate, validator, atomic
rename - apply to every service with a syntax check: nginx -t for
nginx (Section 27.5.3 uses exactly that), dhcpd -t for the DHCP server
(Section 27.5.8 shows its failure output), and sshd -t for OpenSSH
(Chapter 20, Section 20.4.2, reloads only after it).
27.2.4. Reviewing Changes and Preparing Rollback
A history is only worth keeping if review and rollback are easy. Simulate
a bad change: replace the demo configuration's retention with a shorter
value - this is config/handbook-demo.conf.changed:
report_schedule = "15 3 * * *"
retention_days = 7
Install it as before:
$ sudo install -m 0644 config/handbook-demo.conf.changed /etc/handbook-demo.conf
Nothing prints; the file has changed on disk but the repository does not
know it yet - etckeeper vcs diff shows pending changes like this one
before you commit them, the same review step Git users know. Commit:
$ sudo etckeeper commit 'Change report retention'
[master aadc11e] Change report retention
Author: john <john@auto1>
4 files changed, 6 insertions(+), 2 deletions(-)
create mode 100644 sudoers.d/automation-report
The commit summary holds a lesson worth reading carefully: it lists four
files, not one. etckeeper commit commits the entire current state of
/etc - the retention change, yes, but also the sudoers fragment
installed in Section 27.2.3, the .gitignore rule from Section 27.2.2
when it was still pending, and the .etckeeper metadata - because all
of them were uncommitted at this moment. The commit message describes
one of them. In production, commit promptly after each change so each
commit is one coherent unit; a message that describes a fifth of a
commit is a message that lies to whoever reads the history in a year.
Now roll the bad change back. git revert creates a new commit that is
the exact inverse of the named one, leaving both the mistake and the
recovery in history:
$ sudo etckeeper vcs revert --no-edit HEAD
[master 4544ca0] Revert "Change report retention"
Date: Mon Nov 23 20:04:37 2026 +0000
4 files changed, 2 insertions(+), 6 deletions(-)
delete mode 100644 sudoers.d/automation-report
Read the file as an ordinary user - it is mode 0644, so no privileges are needed:
$ cat /etc/handbook-demo.conf
# Local demonstration configuration tracked with etckeeper.
report_schedule = "15 3 * * *"
retention_days = 30
The retention is back to 30. The revert's scope is the mirror of the
commit's scope: it undid all four bundled changes, which here suits the
exercise - the demo configuration is restored, the practice sudoers
fragment is gone, and nothing in the running services depended on them.
Two consequences follow from the same fact. First, reverting a commit
that bundled several unrelated changes reverts all of them - the
argument for focused commits again, now with teeth. Second, the revert
also restored /etc/.gitignore to its pre-commit state, so the
secret's ignore entry is gone while /etc/handbook-secret.env itself
is still on disk, untracked and no longer excluded. Before the next
etckeeper pass - the APT hook or the daily cron job - re-add the entry
and commit it, or the next automatic commit will happily track the
secret you excluded; etckeeper vcs check-ignore -v
handbook-secret.env prints nothing until the rule is back.
Prefer revert over the alternatives when the change is already
committed: git checkout COMMIT -- FILE copies an old version forward
but records nothing about why, and reset-style history rewriting destroys
the record that makes the repository useful during an incident. For the
un-committed case - a change gone wrong minutes ago - etckeeper vcs
checkout -- /etc/handbook-demo.conf restores the committed version
directly. Finally, a local repository on each host is the baseline, not
the ceiling: etckeeper vcs remote add plus a push hook (99push in
/etc/etckeeper/commit.d/) replicates each host's history to a shared
server, giving you off-host recovery of exactly the tree that was lost.
Keep the destination access-controlled: the repository history contains
every /etc file, which is precisely why Section 27.2.2 keeps secrets
out of it.