#!/usr/bin/env bash set -euo pipefail source /etc/restic/restic.env # Metrics file for node_exporter METRICS_DIR="/var/lib/node_exporter/textfile_collector" METRICS_FILE="${METRICS_DIR}/restic_backup.prom" mkdir -p "${METRICS_DIR}" # Temporary file for atomic writes TEMP_FILE=$(mktemp) # Start backup START_TIME=$(date +%s) if restic backup \ {% for path in restic_backup_paths %} {{ path }} \ {% endfor %} {% for pattern in restic_exclude_patterns %} --exclude '{{ pattern }}' \ {% endfor %} --host {{ ansible_facts["hostname"] }}; then # Backup succeeded STATUS=1 echo "# HELP restic_backup_success Whether the last backup succeeded (1=success, 0=failure)" > "${TEMP_FILE}" echo "# TYPE restic_backup_success gauge" >> "${TEMP_FILE}" echo "restic_backup_success ${STATUS}" >> "${TEMP_FILE}" echo "# HELP restic_backup_timestamp_seconds Timestamp of last backup completion" >> "${TEMP_FILE}" echo "# TYPE restic_backup_timestamp_seconds gauge" >> "${TEMP_FILE}" echo "restic_backup_timestamp_seconds $(date +%s)" >> "${TEMP_FILE}" echo "# HELP restic_backup_duration_seconds Duration of last backup in seconds" >> "${TEMP_FILE}" echo "# TYPE restic_backup_duration_seconds gauge" >> "${TEMP_FILE}" echo "restic_backup_duration_seconds $(($(date +%s) - START_TIME))" >> "${TEMP_FILE}" # Move temp file to final location atomically mv "${TEMP_FILE}" "${METRICS_FILE}" exit 0 else # Backup failed STATUS=0 echo "# HELP restic_backup_success Whether the last backup succeeded (1=success, 0=failure)" > "${TEMP_FILE}" echo "# TYPE restic_backup_success gauge" >> "${TEMP_FILE}" echo "restic_backup_success ${STATUS}" >> "${TEMP_FILE}" echo "# HELP restic_backup_timestamp_seconds Timestamp of last backup attempt" >> "${TEMP_FILE}" echo "# TYPE restic_backup_timestamp_seconds gauge" >> "${TEMP_FILE}" echo "restic_backup_timestamp_seconds $(date +%s)" >> "${TEMP_FILE}" # Move temp file to final location atomically mv "${TEMP_FILE}" "${METRICS_FILE}" exit 1 fi