- name: Configure local backup for LNBits from remote hosts: lapy gather_facts: no vars_files: - ../../infra_vars.yml - ./lnbits_vars.yml vars: remote_data_path: "{{ lnbits_data_dir }}" remote_lnbits_dir: "{{ lnbits_dir }}/lnbits" gpg_recipient: "{{ hostvars['localhost']['gpg_recipient'] | default('') }}" gpg_key_id: "{{ hostvars['localhost']['gpg_key_id'] | default('') }}" tasks: - name: Debug remote backup vars debug: msg: - "remote_host={{ remote_host }}" - "remote_user={{ remote_user }}" - "remote_data_path='{{ remote_data_path }}'" - "local_backup_dir={{ local_backup_dir }}" - "gpg_recipient={{ gpg_recipient }}" - "gpg_key_id={{ gpg_key_id }}" - name: Ensure local backup directory exists file: path: "{{ local_backup_dir }}" state: directory mode: '0755' - name: Ensure ~/.local/bin exists file: path: "{{ lookup('env', 'HOME') }}/.local/bin" state: directory mode: '0755' - name: Create backup script copy: dest: "{{ backup_script_path }}" mode: '0750' content: | #!/bin/bash set -euo pipefail TIMESTAMP=$(date +'%Y-%m-%d') ENCRYPTED_BACKUP="{{ local_backup_dir }}/lnbits-backup-$TIMESTAMP.tar.gz.gpg" {% if remote_key_file %} SSH_CMD="ssh -i {{ remote_key_file }} -p {{ hostvars[remote_host]['ansible_port'] | default(22) }}" {% else %} SSH_CMD="ssh -p {{ hostvars[remote_host]['ansible_port'] | default(22) }}" {% endif %} # Stop LNBits service before backup echo "Stopping LNBits service..." $SSH_CMD {{ remote_user }}@{{ remote_host }} "sudo systemctl stop lnbits.service" # Create encrypted backup on the fly # First, create a tar archive of the data directory and pipe it through gpg echo "Creating backup..." $SSH_CMD {{ remote_user }}@{{ remote_host }} "cd {{ remote_data_path }} && tar -czf - ." | \ gpg --batch --yes --encrypt --recipient "{{ gpg_recipient }}" --output "$ENCRYPTED_BACKUP" # Also backup the .env file separately (smaller, might need quick access) $SSH_CMD {{ remote_user }}@{{ remote_host }} "cat {{ remote_lnbits_dir }}/.env" | \ gpg --batch --yes --encrypt --recipient "{{ gpg_recipient }}" --output "{{ local_backup_dir }}/lnbits-env-$TIMESTAMP.gpg" # Start LNBits service after backup echo "Starting LNBits service..." $SSH_CMD {{ remote_user }}@{{ remote_host }} "sudo systemctl start lnbits.service" # Rotate old encrypted backups (keep 14 days) find "{{ local_backup_dir }}" -name "lnbits-backup-*.tar.gz.gpg" -mtime +13 -delete find "{{ local_backup_dir }}" -name "lnbits-env-*.gpg" -mtime +13 -delete echo "Backup completed successfully" - name: Ensure cronjob for backup exists cron: name: "LNBits backup" user: "{{ lookup('env', 'USER') }}" job: "{{ backup_script_path }}" minute: 5 hour: "9,12,15,18" - name: Run the backup script to make the first backup command: "{{ backup_script_path }}"