DEV Community

Cover image for Stop Partitioning Disks by Hand: Practical systemd-repart on Linux
Lyra
Lyra

Posted on

Stop Partitioning Disks by Hand: Practical systemd-repart on Linux

Every hand-built Linux image eventually grows the same wart: a shell script that pipes commands into sfdisk, calls partprobe, runs resize2fs, and hopes the device really was /dev/sda.

It works exactly once. Change the disk, add a partition, or boot the same image on a board that enumerates storage differently, and the script either fails halfway or, worse, succeeds against the wrong device. The deeper problem is that the script encodes positions. What you actually mean is "this disk should have a swap partition and a root partition that fills the rest."

systemd-repart is the declarative version of that idea. You write small .conf files describing the partitions that should exist, and the tool makes the partition table match. It is incremental by design: existing partitions are matched by type, missing ones are appended, and when the table already matches the configuration it does nothing at all. It is used to build OS images, and it can run from the initrd to adapt a minimal image to whatever disk it landed on.

This is the practical guide: the mental model, three working configurations, and the failure modes that cost people data.

What it will not do

Start with the boundaries, because they explain most of the confusing behaviour:

  • GPT only. MBR/DOS partition tables are not supported at all.
  • No shrinking, moving, or deleting. The one exception is a partition explicitly marked FactoryReset=yes running in factory-reset mode. Otherwise existing partitions and their numbering are left alone.
  • No filesystem growth by itself. systemd-repart changes the partition table. Growing the filesystem inside is a separate step (systemd-growfs, resize2fs, btrfs filesystem resize, or the x-systemd.growfs mount option).
  • No content migration. It is not a partition editor for a disk that already holds data you care about. Back up the table first.

If you need to shrink a partition, this is the wrong tool. For creating and growing partitions on an image or a fresh disk, it is the right one.

The matching rule that explains everything

Definitions live in *.conf files read from:

  • /etc/repart.d/
  • /run/repart.d/
  • /usr/local/lib/repart.d/
  • /usr/lib/repart.d/

Files are sorted by filename, ignoring the directory prefix. That sort order is the whole configuration language for "which partition is which", so the numeric prefixes (10-, 20-, 50-) are not cosmetic.

Matching then works like this:

  1. The existing partition table is read.
  2. Definition files are walked in filename order and matched against existing partitions by GPT partition type UUID, not by label, UUID, or position. The first existing partition of a given type gets the first definition declaring that type; the second gets the second, and so on.
  3. Existing partitions with no matching definition are "foreign" and left untouched.
  4. Definitions with no matching partition are requests to create new partitions. They are appended using the first free partition-table slot above the highest index in use.

That has a concrete consequence for A/B root setups: two files with Type=root, named 10-root-a.conf and 20-root-b.conf, will bind to the first and second root partitions respectively. Rename 20-root-b.conf to 05-root-b.conf and you have silently swapped which physical partition each definition controls.

New partitions are not necessarily written in table order on disk. The allocator places each one in the smallest free area large enough to satisfy its constraints, so a late-numbered partition can end up physically before an earlier one. Partition numbers stay stable; offsets do not have to be monotonic.

How space is actually assigned

This is where most surprises come from. The allocator takes the free space and distributes it according to three settings:

  • SizeMinBytes= / SizeMaxBytes= are hard bounds, in bytes with K, M, G, T suffixes (base 1024).
  • Weight= (default 1000, range 0 to 1000000) distributes leftover space elastically. Weight 2000 gets twice the space of weight 1000.
  • PaddingWeight= (default 0) does the same for deliberate empty space after a partition.

The default is a minimum of 10M and no maximum. That single default explains the most common question: "why did my root partition take the entire disk?" Because you said it could.

Two more rules that bite:

  • If SizeMinBytes= equals SizeMaxBytes=, the size is fixed and Weight= becomes irrelevant.
  • Sizes are rounded up (for minimums) or down (for maximums) to multiples of 4096 bytes. A request for 1000M is not exactly 1000 MiB on disk.

There is also an automatic floor: with Format= set, the minimum is raised to the minimum size of that filesystem. ESP and XBOOTLDR partitions get bumped to 100M on 512-byte-sector images and 260M on 4K-sector images, even if you asked for less.

The dry-run default is the first trap

systemd-repart defaults to --dry-run=yes. Running it bare does not write anything; it prints what it would do. That is a good default and a terrible surprise when you think you just resized a disk.

# Preview changes to the running system's root disk (no writes)
systemd-repart --dry-run=yes --pretty=yes

# Actually write
sudo systemd-repart --dry-run=no
Enter fullscreen mode Exit fullscreen mode

With no positional argument, the tool operates on the block device backing the root filesystem. Inside the initrd it operates on the device backing /sysroot/ instead. --list-devices shows candidate devices, and passing - as the device makes it print the minimum image size for the configuration without touching anything.

--pretty=yes gives you a human-readable table plus a graphic of the proposed layout. --json=short or --json=pretty gives machine-readable output, including the verity root hash when relevant.

Example 1: grow root to fill the disk

The classic first-boot adaptation. On a system where the root partition is the last one and there is unused space after it:

sudo install -d /etc/repart.d
sudo tee /etc/repart.d/50-root.conf >/dev/null <<'EOF'
[Partition]
Type=root
GrowFileSystem=yes
EOF
Enter fullscreen mode Exit fullscreen mode

Preview against the running disk:

sudo systemd-repart --dry-run=yes --pretty=yes
Enter fullscreen mode Exit fullscreen mode

Then apply and grow the filesystem:

sudo systemd-repart --dry-run=no

# ext4
sudo resize2fs /dev/nvme0n1p2

# or btrfs, while mounted
sudo btrfs filesystem resize max /
Enter fullscreen mode Exit fullscreen mode

GrowFileSystem=yes sets bit 59 of the GPT partition entry flags (the Discoverable Partitions Specification "grow file system" flag). systemd-growfs@.service and the x-systemd.growfs fstab option honour that flag, and systemd-growfs grows a mounted filesystem to the full size of its block device. On partition types that support the flag it defaults to on, so the line is documentation as much as configuration.

Two caveats. First, a partition can only grow into free space immediately after it; if another partition sits behind it, the allocator cannot move things to help. Second, if your root filesystem lives on LVM, md RAID, or another stacked device, there is no GPT "root" partition to match. The packaged unit lists exit code 76 ("can't find the root block device") as a success for exactly this reason.

Example 2: add a swap partition on first boot

Same mechanism, different type. Fixed 4 GiB swap, formatted as swap:

sudo tee /etc/repart.d/20-swap.conf >/dev/null <<'EOF'
[Partition]
Type=swap
Format=swap
SizeMinBytes=4G
SizeMaxBytes=4G
EOF
Enter fullscreen mode Exit fullscreen mode
sudo systemd-repart --dry-run=yes --pretty=yes
sudo systemd-repart --dry-run=no
Enter fullscreen mode Exit fullscreen mode

Format=swap writes a swap signature; the label is derived from the partition label, which in turn is derived from the partition type when unset. Confirm what you got before wiring it up:

lsblk -o NAME,SIZE,PARTLABEL,LABEL,FSTYPE
Enter fullscreen mode Exit fullscreen mode

Then reference it by label in /etc/fstab:

echo 'LABEL=swap none swap sw 0 0' | sudo tee -a /etc/fstab
sudo systemctl daemon-reload
sudo swapon -a
Enter fullscreen mode Exit fullscreen mode

Note that Format= only applies when the partition is newly created. It has no effect on an existing partition, which is why re-running the tool is safe but also why it will never reformat something you already have.

Example 3: build a reproducible image from scratch

This is the workflow that replaces image-building shell scripts. Two definitions:

mkdir -p /tmp/defs /tmp/rootfs/etc
printf 'demo\n' > /tmp/rootfs/etc/hostname

cat >/tmp/defs/10-esp.conf <<'EOF'
[Partition]
Type=esp
Format=vfat
SizeMinBytes=512M
SizeMaxBytes=512M
EOF

cat >/tmp/defs/20-root.conf <<'EOF'
[Partition]
Type=root
Format=ext4
SizeMinBytes=1G
SizeMaxBytes=4G
CopyFiles=/etc
EOF
Enter fullscreen mode Exit fullscreen mode

Build a minimal image file, populating the root filesystem from a staging directory:

systemd-repart \
  --definitions=/tmp/defs \
  --copy-source=/tmp/rootfs \
  --empty=create --size=auto \
  --offline=yes --dry-run=no \
  /tmp/disk.raw
Enter fullscreen mode Exit fullscreen mode

What each flag does:

  • --empty=create creates the target as a regular file instead of refusing an unpartitioned device.
  • --size=auto sums the minimum sizes of all configured partitions (plus metadata) to produce a minimal image. It does not compact pre-existing gaps.
  • --offline=yes builds without loop devices, which is what makes unprivileged image builds possible. The default is auto, which uses loop devices when available and falls back otherwise.
  • --copy-source= makes CopyFiles= paths relative to a staging tree instead of the host root.

CopyFiles= takes source[:target[:options]] and implies Format= if you did not set one (vfat for ESP/XBOOTLDR, ext4 otherwise). Copying stops at filesystem limitations: symlinks, FIFOs, sockets, and device nodes are skipped on vfat with a log message, and UIDs/GIDs are preserved as-is.

Verify the result without mounting it:

sfdisk -d /tmp/disk.raw
systemd-dissect --json=pretty /tmp/disk.raw
Enter fullscreen mode Exit fullscreen mode

Then write it to the target medium with dd or your usual flasher, boot it, and let the on-disk configuration take over.

A note on determinism

Partition UUIDs and the disk UUID are derived by hashing a seed, which by default is the machine ID read from --root=. Images built from the same tree therefore get the same UUIDs. Pass --seed=random when you want them randomized, or an explicit UUID when you need byte-identical rebuilds. This matters for dm-verity and for anything that pins a root hash.

Encryption is one setting

Encrypt= wraps the partition in LUKS2 before Format= or CopyBlocks= runs, so the filesystem is created inside the encrypted mapping:

cat >/tmp/defs/30-data.conf <<'EOF'
[Partition]
Type=linux-generic
Label=data
Format=ext4
Encrypt=tpm2
SizeMinBytes=2G
SizeMaxBytes=8G
EOF

sudo systemd-repart --definitions=/tmp/defs --empty=create --size=8G \
  --dry-run=no --tpm2-device=auto --tpm2-pcrs=7 /tmp/disk.raw
Enter fullscreen mode Exit fullscreen mode

Encrypt= accepts off, key-file, tpm2, and key-file+tpm2. The LUKS2 UUID is derived from the partition UUID, and the LUKS label defaults to the partition label prefixed with luks- (override with VolumeLabel=, systemd 259+).

One trap: with Encrypt=key-file and no --key-file=, the empty key is used. That is intentional for provisioning flows where a real passphrase is enrolled later, but it is not what you want on a finished image.

Factory reset, done declaratively

A partition marked FactoryReset=yes is deleted and recreated empty when the tool runs in factory-reset mode. That mode is triggered by --factory-reset=yes, by systemd.factory_reset=yes on the kernel command line, or by the FactoryResetRequest EFI variable. --can-factory-reset checks whether any partition is marked, exiting zero if so and non-zero otherwise, which is convenient for installer UIs.

Because it deletes data, treat this as a deliberate feature with a test plan, not something to enable because it sounds tidy.

The settings worth memorising

Setting What it controls
Type= GPT type UUID or identifier (root, esp, swap, home, var, srv, tmp, linux-generic, root-x86-64, ...)
SizeMinBytes=, SizeMaxBytes= Hard size bounds; equal values fix the size
Weight= Share of leftover free space (default 1000)
PaddingWeight= Share of free space deliberately left empty after the partition
Format= Create a filesystem (ext4, btrfs, xfs, vfat, erofs, squashfs, swap, or empty)
CopyFiles= Populate a new filesystem from host paths
CopyBlocks= Copy raw blocks (including auto for self-replicating installers)
Encrypt= LUKS2 wrap before formatting
GrowFileSystem= Set the grow-filesystem GPT flag
FactoryReset= Mark for deletion in factory-reset mode
MountPoint= Emit an fstab entry with --generate-fstab= (systemd 256+)
Minimize= Trim a copied filesystem to its contents (best is read-only-fs and btrfs only)

Safety checklist

Run these in order the first time you use the tool on real hardware:

# 1. Back up the partition table (cheap, restorable)
sudo sfdisk -d /dev/nvme0n1 | sudo tee /root/parttable-backup.txt

# 2. Confirm which disk actually backs /
findmnt -no SOURCE /

# 3. Dry run, and read the output
sudo systemd-repart --dry-run=yes --pretty=yes

# 4. Apply
sudo systemd-repart --dry-run=no
Enter fullscreen mode Exit fullscreen mode

To restore the table: sudo sfdisk /dev/nvme0n1 < /root/parttable-backup.txt. This restores the partition entries, not filesystem contents, so it is a safety net for table mistakes, not a backup strategy.

Never point --empty=force at a disk you like. It creates a fresh table unconditionally, which in practice means erasing everything.

When not to use it

  • The disk uses MBR. Convert first, or use parted.
  • You need to shrink, move, or reorder existing partitions.
  • The layout is managed by LVM or ZFS and does not correspond to GPT partitions.
  • The machine is a normal desktop you occasionally repartition by hand. gparted is fine; declarative tooling pays off for images and fleets, not one-off edits.

For everything else, the payoff is real: the same configuration builds your image, adapts it on first boot, and can be re-run at any time without changing anything. That idempotence is the part shell scripts never quite deliver.

Sources

Top comments (0)