Day 13: Dotfiles and a new Mac
Goal: Your configuration is versioned in chezmoi, and a new Mac is ready for work in an hour. · Duration: approx. 120 min · Prerequisite: Day 12
Briefing
- chezmoi manages dotfiles in a source directory (Git
repo) and writes them into your home with
apply. Templates know the machine: work or private, hostname, architecture. - Secrets never land in the repo. Templates fetch them at runtime from
1Password (
op) or the macOS keychain. - A Brewfile +
brew bundledescribes all packages, a defaults script the macOS settings, and a bootstrap script ties everything together. - All drills run in
~/term-lab/cz. Today you don’t touch your real~/.local/share/chezmoior your real home.
Git repo (source) chezmoi apply Home (target)
dot_zshrc ───────────────────────► ~/.zshrc
dot_gitconfig.tmpl ── template + data ─────► ~/.gitconfig
Brewfile ── run_onchange script ─► brew bundle
Drill 1: A practice ground for chezmoi
chezmoi has flags for source, destination, config, state and cache. A
function cz redirects all five into the sandbox. First
start the practice shell with ~/term-lab/lab.
mkdir -p ~/term-lab/cz/{src,home,cfg}
cat > ~/term-lab/config/zsh/cz-lab.zsh <<'EOF'
# chezmoi on the practice ground: the real ~/.local/share/chezmoi stays untouched
CZ_LAB="$LAB/cz"
cz() {
chezmoi --source "$CZ_LAB/src" --destination "$CZ_LAB/home" \
--config "$CZ_LAB/cfg/chezmoi.toml" \
--persistent-state "$CZ_LAB/cfg/state.boltdb" \
--cache "$CZ_LAB/cfg/cache" "$@"
}
EOF
source ~/term-lab/config/zsh/cz-lab.zsh
cz init
cz source-path
ls -a ~/term-lab/cz/srcExpected:
/Users/<du>/term-lab/cz/src
. .. .git
Warning: Without the flags,
chezmoiworks on~/.local/share/chezmoiand your real home. Today, always typecz, neverchezmoi.
Save your progress? Sign up for free
Drill 2: Taking over files – add, edit, diff, apply
Create a mini home and take over three files. add copies
into the source directory; the target stays unchanged.
H=~/term-lab/cz/home
mkdir -p $H/.config/zsh
printf 'export EDITOR=nvim\nsource ~/.config/zsh/aliases.zsh\n' > $H/.zshrc
printf "alias ll='eza -l'\n" > $H/.config/zsh/aliases.zsh
cz add $H/.zshrc $H/.config/zsh/aliases.zsh
find ~/term-lab/cz/src -path '*/.git' -prune -o -type f -print
cz managedExpected:
/Users/<du>/term-lab/cz/src/dot_zshrc
/Users/<du>/term-lab/cz/src/dot_config/zsh/aliases.zsh
.config
.config/zsh
.config/zsh/aliases.zsh
.zshrc
Why? Prefixes in the file name carry the metadata: dot_
becomes .; later private_,
executable_ and the .tmpl extension come
along.
Now you change the source, check the difference and
roll it out. In everyday use,
cz edit $H/.config/zsh/aliases.zsh opens your
$EDITOR. Here it works without an editor.
echo "alias k=kubectl" >> "$(cz source-path $H/.config/zsh/aliases.zsh)"
cz status
cz diff --no-pager
cz apply -v --no-pager >/dev/null
cat $H/.config/zsh/aliases.zshExpected:
M .config/zsh/aliases.zsh
diff --git a/.config/zsh/aliases.zsh b/.config/zsh/aliases.zsh
@@ -1 +1,2 @@
alias ll='eza -l'
+alias k=kubectl
alias ll='eza -l'
alias k=kubectl
The reverse direction: someone (you) changes the target directly.
status then shows MM, and re-add
brings the change back into the source.
echo "export PAGER=less" >> $H/.zshrc
cz status
cz re-add && cz status && echo "sauber"Expected:
MM .zshrc
sauber
| Command | Effect | Mnemonic |
|---|---|---|
cz add <ziel> |
copy target → source | take in |
cz edit <ziel> |
open the source in the editor | never edit the target |
cz diff / cz status |
source vs. target | look first |
cz apply |
write source → target | then write |
cz re-add |
bring changed targets back | collect drift |
Save your progress? Sign up for free
Drill 3: Templates per machine – work or private
A .chezmoi.toml.tmpl file in the source directory
generates the configuration on init.
promptChoiceOnce only asks the first time and remembers the
answer.
S=~/term-lab/cz/src
cat > $S/.chezmoi.toml.tmpl <<'EOF2'
{{- $hosttype := promptChoiceOnce . "hosttype" "Rechnerart" (list "work" "privat") -}}
{{- $email := promptStringOnce . "email" "Git-E-Mail" -}}
[data]
hosttype = {{ $hosttype | quote }}
email = {{ $email | quote }}
EOF2
cz init --promptChoice Rechnerart=work \
--promptString [email protected]
cat ~/term-lab/cz/cfg/chezmoi.tomlExpected:
[data]
hosttype = "work"
email = "[email protected]"
Why the flags? Interactively, cz init simply asks.
--promptChoice and --promptString answer the
questions in advance – the key is the prompt text, not
the variable name.
Now the template for the Git configuration. On the work machine, a proxy is added.
cat > $S/dot_gitconfig.tmpl <<'EOF2'
[user]
name = Thomas Zachmann
email = {{ .email }}
{{- if eq .hosttype "work" }}
[http]
proxy = http://proxy.kunde.example:3128
{{- end }}
[core]
pager = delta
EOF2
cz execute-template \
'{{ .chezmoi.os }}/{{ .chezmoi.arch }} {{ .chezmoi.hostname }} {{ .hosttype }}'
echo; cz cat $H/.gitconfigExpected:
darwin/arm64 tzachmann-mbair work
[user]
name = Thomas Zachmann
email = [email protected]
[http]
proxy = http://proxy.kunde.example:3128
[core]
pager = delta
Repurposing a machine: first roll out the work version, then
--prompt forces the questions again and diff
immediately shows the consequences.
cz apply
cz init --prompt --promptChoice Rechnerart=privat \
--promptString [email protected]
cz diff --no-pager | grep '^[-+] '
cz apply && cz git -- add -A && cz git -- commit -qm "Dotfiles: erste Version"
cz git -- log --onelineExpected:
- email = [email protected]
- proxy = http://proxy.kunde.example:3128
+ email = [email protected]
65802bc Dotfiles: erste Version
A cz git works in the source directory;
GIT_CONFIG_GLOBAL from Day 10 still applies.
Tip:
cz datashows all variables that templates see. For typos in templates,cz execute-template < datei.tmplis the fastest test.
Save your progress? Sign up for free
Drill 4: Secrets – 1Password and keychain
A secret never belongs in the repo; it’s fetched on
apply. The private_ prefix sets the
permissions to 0600. lookPath makes the
template robust if op is missing.
mkdir -p $S/dot_config/termlab
cat > $S/dot_config/termlab/private_secrets.env.tmpl <<'EOF2'
# Erzeugt von chezmoi - nicht einchecken, nicht von Hand ändern.
{{- if lookPath "op" }}
export GITHUB_TOKEN={{ onepasswordRead "op://Private/GitHub/token" | quote }}
{{- else }}
# 1Password-CLI (op) fehlt - kein Token gesetzt.
{{- end }}
EOF2
cz apply
ls -l $H/.config/termlab
cat $H/.config/termlab/secrets.envExpected (without the 1Password CLI installed):
total 8
-rw-------@ 1 <du> staff 115 10 Okt 08:35 secrets.env
# Erzeugt von chezmoi - nicht einchecken, nicht von Hand ändern.
# 1Password-CLI (op) fehlt - kein Token gesetzt.
Without protection, the template aborts hard – and that’s good, because an empty token would be worse:
cz execute-template '{{ onepasswordRead "op://Private/GitHub/token" }}'Expected:
chezmoi: template: arg1:1:3: executing "arg1" at <onepasswordRead
"op://Private/GitHub/token">: error calling onepasswordRead: op signin --raw:
exec: "op": executable file not found in $PATH
The keychain variant without extra tools (don’t run it – it reads your real login keychain):
# store once in the terminal (prompts for the secret, lands in the Keychain):
# security add-generic-password -s termlab-github -a "$USER" -w
# in the template:
export GITHUB_TOKEN={{ keyring "termlab-github" .chezmoi.username | quote }}
Security:
cz diffandcz catshow rendered secrets in plain text. Don’t use them in shared terminals or screencasts.
Save your progress? Sign up for free
Drill 5: Ignoring and scripts – run_onchange
.chezmoiignore is itself a template: client
configuration only lands on the work machine. Scripts under
.chezmoiscripts/ run on apply.
run_onchange_ means: only when the rendered content changes
– the Brewfile hash in the comment ensures exactly that.
cp $BUCH/brew/Brewfile $S/Brewfile
cat > $S/.chezmoiignore <<'EOF2'
Brewfile
{{- if ne .hosttype "work" }}
.config/kunde/**
{{- end }}
EOF2
mkdir -p $S/dot_config/kunde $S/.chezmoiscripts
echo 'proxy=on' > $S/dot_config/kunde/env
cat > $S/.chezmoiscripts/run_onchange_before_10-brew.sh.tmpl <<'EOF2'
#!/bin/bash
# Läuft nur, wenn sich der Brewfile ändert.
# Brewfile-Hash: {{ include "Brewfile" | sha256sum }}
set -euo pipefail
brew bundle --file={{ joinPath .chezmoi.sourceDir "Brewfile" | quote }}
EOF2
cz ignored
cz statusExpected (machine type privat):
.config/kunde
Brewfile
R .chezmoiscripts/10-brew.sh
R means: the script would run. In the lab it should
not – you only look at it rendered and roll out without
scripts:
cz execute-template \
< $S/.chezmoiscripts/run_onchange_before_10-brew.sh.tmpl | sed "s#$HOME#~#"
cz apply --exclude=scripts && cz statusExpected:
#!/bin/bash
# Läuft nur, wenn sich der Brewfile ändert.
# Brewfile-Hash: 5faf7d56a71b…
set -euo pipefail
brew bundle --file="~/term-lab/cz/src/Brewfile"
R .chezmoiscripts/10-brew.sh
Warning:
cz applywithout--exclude=scriptswould startbrew bundlehere and install packages. On a real new Mac, that’s exactly what you want.
Save your progress? Sign up for free
Drill 6: Brewfile – check, generate, clean up
You know the Brewfile from Day 0. Today you turn the direction around: what’s installed on the Mac, what’s missing, what’s too much? None of the three commands changes anything on the system.
brew bundle check --verbose --no-upgrade --file=$BUCH/brew/Brewfile
brew bundle dump --file=~/term-lab/cz/Brewfile.ist
awk '{print $1}' ~/term-lab/cz/Brewfile.ist | sort | uniq -c
brew bundle cleanup --file=$BUCH/brew/Brewfile | head -4Expected (shortened, depends on your Mac):
brew bundle can't satisfy your Brewfile's dependencies.
→ Cask ghostty needs to be installed.
→ Formula just needs to be installed.
Satisfy missing dependencies with `brew bundle install`.
107 #
95 brew
14 cask
3 tap
Would uninstall casks:
bitwarden
dropbox
…
Why? dump adds each package’s description as a
# comment. cleanup without
--force is a dry run and shows what is not
in the Brewfile. --no-upgrade ignores outdated versions –
otherwise check also reports packages that just need an
update.
| Command | Effect | Mnemonic |
|---|---|---|
brew bundle check |
Brewfile satisfied? | target = actual? |
brew bundle dump |
actual state → Brewfile | inventory |
brew bundle cleanup |
shows extras | first without --force |
brew bundle --file=… |
installs what’s missing | only on a new Mac |
Tip: Maintain one Brewfile in the chezmoi repo. Separate machine-specific things (client VPN, private apps) with a
Brewfile.tmpltemplate and{{ if eq .hosttype "work" }}.
Save your progress? Sign up for free
Drill 7: macOS settings as code – defaults
Reading is always allowed. If a key is missing, the factory default
applies – defaults then reports an error.
defaults read com.apple.finder AppleShowAllFiles
defaults read com.apple.dock autohide
defaults read-type com.apple.finder AppleShowAllFilesExpected (depends on your Mac):
true
2026-10-10 08:40:11.463 defaults[93305:4051029]
The domain/default pair of (com.apple.dock, autohide) does not exist
Type is string
You practice writing in a domain of your own. Afterwards it’s deleted completely.
defaults write com.example.termlab KeyRepeat -int 2
defaults write com.example.termlab autohide -bool true
defaults read com.example.termlab
defaults delete com.example.termlab
defaults read com.example.termlab 2>&1 | tail -1Expected:
{
KeyRepeat = 2;
autohide = 1;
}
Domain com.example.termlab does not exist
The script $BUCH/bootstrap/macos-defaults.sh collects
the settings. Without APPLY=1 it’s a dry run;
LAB_DOMAIN redirects all writes into the practice
domain.
$BUCH/bootstrap/macos-defaults.sh | head -3
APPLY=1 LAB_DOMAIN=com.example.termlab $BUCH/bootstrap/macos-defaults.sh | tail -2
defaults read com.example.termlab | wc -l
defaults delete com.example.termlabExpected:
DRY: defaults write NSGlobalDomain KeyRepeat -int 2
DRY: defaults write NSGlobalDomain InitialKeyRepeat -int 15
DRY: defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
✔ com.example.termlab location = /Users/<du>/Screenshots
✔ com.example.termlab disable-shadow = true
12
The core is a function set_default domain key typ wert –
a single place for the dry run and the redirection. Look at it with
bat $BUCH/bootstrap/macos-defaults.sh.
Tip: Which key is behind a checkbox in System Settings?
defaults read > vorher.txt, check the box,defaults read > nachher.txt,diff vorher.txt nachher.txt. Only read, write nothing.
Save your progress? Sign up for free
Drill 8: Bootstrap script – dry run
$BUCH/bootstrap/bootstrap.sh turns a fresh Mac into your
Mac in six steps. Without --apply it only checks and shows
what it would do. It’s idempotent: a second run skips what’s done.
shellcheck $BUCH/bootstrap/*.sh && echo "✔ shellcheck"
$BUCH/bootstrap/bootstrap.sh 2>&1 | grep -E '^(==>|✔|DRY|…)'Expected (shortened, depends on your Mac):
✔ shellcheck
==> 1/6 Xcode Command Line Tools
✔ vorhanden
==> 2/6 Homebrew
✔ Homebrew 7.0.9
==> 3/6 chezmoi + Dotfiles
✔ Quellverzeichnis existiert schon -> nur update
DRY: chezmoi update
==> 4/6 Pakete aus dem Brewfile
… Brewfile oder brew fehlt: /Users/<du>/.local/share/chezmoi/Brewfile
==> 5/6 macOS-Einstellungen
DRY: defaults write NSGlobalDomain KeyRepeat -int 2
…
==> 6/6 SSH-Key
✔ Key vorhanden
==> Fertig. Nächste Schritte: Checkliste in Tag 13.
The scaffolding – set -euo pipefail,
trap … ERR, run() for the dry run – is covered
in depth on Day 14.
On the new Mac, one line is then enough – provided the dotfiles repo is reachable:
DOTFILES_REPO=https://github.com/DEIN-USER/dotfiles.git ./bootstrap.sh --applyWhy HTTPS? On the fresh Mac there’s no SSH key at GitHub yet – step 6
creates it. You clone a private repo via gh auth login or a
token. chezmoi init --apply <repo> clones the repo to
~/.local/share/chezmoi, asks for hosttype and
email, writes all files and starts the run_onchange script
with brew bundle.
Save your progress? Sign up for free
Drill 9: For real – adopting your actual configuration
Up to here, everything ran in the lab. When you’re ready, you deliberately carry your lab configuration over into your real home. Read through the steps first – they change your system.
# 1. Back up the real files (tar reports missing files, that's ok)
cd ~ && tar czf ~/dotfiles-backup-$(date +%F).tgz \
.zshrc .zshenv .zprofile .gitconfig .tmux.conf .config/nvim .config/starship.toml
# 2. Copy the lab state into the real home (lab folder config/zsh -> ~/.config/zsh)
mkdir -p ~/.config/zsh && cp ~/term-lab/config/zsh/*.zsh ~/.config/zsh/
# 3. Create the real chezmoi and take over the files (add doesn't change the target)
chezmoi init
chezmoi add ~/.zshrc ~/.gitconfig ~/.tmux.conf ~/.config/zsh ~/.config/nvim
chezmoi diff # must be empty
# 4. Create the remote and push
chezmoi cd && gh repo create dotfiles --private --source=. --pushWarning: Before pushing, check with
chezmoi git -- grep -nIE 'token|password|secret'that no secret sits in plain text in the source. Whatever you find moves into a template withonepasswordReadorkeyring.
Save your progress? Sign up for free
Checklist: a new Mac in one hour
| Minute | Step | Command / location |
|---|---|---|
| 0–10 | Apple Account, FileVault, updates | System Settings |
| 10–15 | Xcode Command Line Tools | xcode-select --install |
| 15–20 | fetch and review bootstrap | curl -fsSLO …/bootstrap.sh + read it |
| 20–45 | Homebrew, chezmoi, packages | ./bootstrap.sh --apply |
| 45–50 | sign in: 1Password, gh auth login |
then chezmoi apply |
| 50–55 | register SSH key at GitHub/GitLab | gh ssh-key add ~/.ssh/id_ed25519.pub |
| 55–60 | log out/log in, measure startup time | hyperfine 'zsh -i -c exit' |
Checkpoint
#!/usr/bin/env zsh
source ~/term-lab/config/zsh/cz-lab.zsh
ok() { echo "✔ $1"; }; nok() { echo "✘ $1"; }
H=$LAB/cz/home
cz managed | grep -qx .gitconfig \
&& ok "gitconfig verwaltet" || nok "gitconfig verwaltet"
cz data --format=json | jq -e '.hosttype' >/dev/null \
&& ok "hosttype gesetzt" || nok "hosttype gesetzt"
[[ $(stat -f %Lp $H/.config/termlab/secrets.env) == 600 ]] \
&& ok "secrets.env ist 0600" || nok "secrets.env ist 0600"
cz status | grep -q '^.M' && nok "Drift zwischen Quelle und Ziel" || ok "keine Drift"
cz git -- log --oneline | grep -q . \
&& ok "Quelle versioniert" || nok "Quelle versioniert"
defaults read com.example.termlab >/dev/null 2>&1 \
&& nok "Übungsdomain noch da" || ok "Übungsdomain gelöscht"
shellcheck $BUCH/bootstrap/*.sh && ok "Skripte shellcheck-sauber" || nok "shellcheck"Expected:
✔ gitconfig verwaltet
✔ hosttype gesetzt
✔ secrets.env ist 0600
✔ keine Drift
✔ Quelle versioniert
✔ Übungsdomain gelöscht
✔ Skripte shellcheck-sauber
Challenge
Turn .zshrc into a template: only on a work
machine does it additionally load ~/.config/kunde/kunde.zsh
with the client proxy. Check both machine types with
cz cat.
Hint: cz chattr +template <ziel>
appends .tmpl to the source file.
Solution
H=$LAB/cz/home S=$LAB/cz/src
cz chattr +template $H/.zshrc
cat >> "$(cz source-path $H/.zshrc)" <<'EOF2'
{{- if eq .hosttype "work" }}
source ~/.config/kunde/kunde.zsh
{{- end }}
EOF2
echo 'export HTTPS_PROXY=http://proxy.kunde.example:3128' \
> $S/dot_config/kunde/kunde.zsh
cz init --prompt --promptChoice Rechnerart=work \
--promptString [email protected]
cz cat $H/.zshrc | tail -1
cz init --prompt --promptChoice Rechnerart=privat \
--promptString [email protected]
cz cat $H/.zshrc | tail -1Expected:
source ~/.config/kunde/kunde.zsh
export PAGER=less
Why does ~/.config/kunde stay on the private machine
after an earlier apply? Ignoring only means “don’t manage”.
To delete it, you add the path to .chezmoiremove.
Clean up after the day: rm -rf ~/term-lab/cz and
defaults delete com.example.termlab 2>/dev/null.
Save your progress? Sign up for free
Enterprise Note
- Company machines are often managed via MDM (Jamf, Intune): profiles
overwrite
defaults, and Homebrew may need an approved path or proxy. Clarify with IT beforehand. - Keep the dotfiles repo private, but maintain it as if it were
public: secrets only via
onepasswordRead,keyringor age encryption (chezmoi add --encrypt). - Separate client-specific things (proxy, CA certificates, internal
registries) via
hosttypeor your own data such as.kunde. At the end of the project, roll them out with.chezmoiremove. - Share the Brewfile in the team: a common base Brewfile in the platform repo, personal additions in your own dotfiles repo.
- Test the bootstrap regularly in a fresh VM. CI can run
shellcheckandchezmoi execute-templateon every commit.