nix-config/scripts/truenas-staging-clone.sh

35 lines
1.4 KiB
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
# This script creates a ZFS snapshot of a production dataset and clones it for a staging environment.
# Required environment variables:
# TRUENAS_IP: The IP address of the TrueNAS scale instance
# TRUENAS_API_KEY: The API token for TrueNAS
# POOL_NAME: The name of the ZFS pool (e.g., "tank")
# SOURCE_DATASET: The name of the production dataset (e.g., "apps/jellyfin")
# PR_NUMBER: The Pull Request number
if [[ -z "${TRUENAS_IP:-}" || -z "${TRUENAS_API_KEY:-}" || -z "${POOL_NAME:-}" || -z "${SOURCE_DATASET:-}" || -z "${PR_NUMBER:-}" ]]; then
echo "Error: Missing required environment variables."
exit 1
fi
BASE_URL="http://${TRUENAS_IP}/api/v2.0"
HEADERS=(
"-H" "Authorization: Bearer ${TRUENAS_API_KEY}"
"-H" "Content-Type: application/json"
)
DATASET_ID="${POOL_NAME}/${SOURCE_DATASET}"
SNAPSHOT_NAME="pr-${PR_NUMBER}-base"
CLONE_DATASET_NAME="${SOURCE_DATASET}-pr-${PR_NUMBER}"
echo "1. Creating snapshot of ${DATASET_ID} @ ${SNAPSHOT_NAME}..."
curl -s -X POST "${BASE_URL}/zfs/snapshot" "${HEADERS[@]}" \
-d "{\"dataset\": \"${DATASET_ID}\", \"name\": \"${SNAPSHOT_NAME}\"}" > /dev/null
echo "2. Cloning snapshot to ${POOL_NAME}/${CLONE_DATASET_NAME}..."
curl -s -X POST "${BASE_URL}/zfs/snapshot/clone" "${HEADERS[@]}" \
-d "{\"snapshot\": \"${DATASET_ID}@${SNAPSHOT_NAME}\", \"dataset_dst\": \"${CLONE_DATASET_NAME}\"}" > /dev/null
echo "Staging dataset cloned successfully."