tfstated/doc/Example-Backup-With-Borg.md
Julien Dessaux 34fbde1f81
All checks were successful
main / main (push) Successful in 1m48s
main / deploy (push) Has been skipped
main / publish (push) Has been skipped
doc(tfstated): import documentation file from the forgejo wiki
2025-04-23 09:36:29 +02:00

2.3 KiB

Example Backup with Borg

Here is a complete example of how to backup a /var/lib/tfstated/tfstated.db SQLite database file using borg on a Debian 12 bookworm server using a bash script, a systemd service and a systemd timer.

Script

The /etc/borg/tfstated.sh script should belong to root:root with 0500 permissions (r-x------):

#!/usr/bin/env bash
set -euo pipefail

archiveSuffix=".failed"

# Run borg init if the repo doesn't exist yet
if ! borg list > /dev/null; then
    borg init --encryption none
fi

archiveName="tfstated-sqlite3-$(date +%Y-%m-%dT%H:%M:%S)"
rm -f /tmp/tfstated.db; umask 077; printf '%s' "VACUUM INTO '/tmp/tfstated.db'" \
   | sqlite3 /srv/tfstated/sqlite.db
borg create \
     --compression auto,zstd \
     "::${archiveName}${archiveSuffix}" \
     /tmp/tfstated.db
rm -f /tmp/tfstated.db
borg rename "::${archiveName}${archiveSuffix}" "${archiveName}"
borg prune \
     --keep-daily=14 --keep-monthly=3 --keep-weekly=4 \
     --glob-archives '*-tfstated-sqlite3-*'

borg compact

Please change the destination hostname and retention options to your liking. You can also encrypt your borg backups for additional security, but remember that your OpenTofu/terraform states are already encrypted at rest in the SQLite database.

Systemd service

The /etc/systemd/system/borg-job-tfstated.service systemd service file should belong to root:root with 0444 permissions (r--r--r--):

[Unit]
Description=BorgBackup job tfstated

[Service]
Environment="BORG_REPO=ssh://borg@myth.adyxax.org/srv/borg/tfstated"
Environment="BORG_RSH=ssh -i /etc/borg/tfstated.key -o StrictHostKeyChecking=accept-new"
CPUSchedulingPolicy=idle
ExecStart=/etc/borg/tfstated.sh
Group=root
IOSchedulingClass=idle
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/root/.cache/borg
ReadWritePaths=/root/.config/borg
User=root

This service file uses environment variables to pass information about the BORG_REPO and the BORG_RSH command to use. Change them to your liking.

Systemd timer

The /etc/systemd/system/borg-job-tfstated.timer systemd timer file should belong to root:root with 0444 permissions (r--r--r--):

[Unit]
Description=BorgBackup job tfstated timer

[Timer]
FixedRandomDelay=true
OnCalendar=daily
Persistent=true
RandomizedDelaySec=3600

[Install]
WantedBy=timers.target