---
- name: Ubuntu Data Backup Automation by Ansible
hosts: source_servers
become: yes
vars:
source_dir: "/path/to/source" # Change to the actual folder to back up
dest_dir: "/path/to/destination" # Change to the actual backup location on DESTINATION server
destination_server: "destination_user@destination_server_ip"
ssh_key: "~/.ssh/id_rsa" # Change to the correct SSH key
max_copy_size: "500G" # Maximum data copy per transfer
check_interval: "1h" # Interval between checks
log_file: "/var/log/backup.log"
tasks:
- name: Install required packages
apt:
name: rsync
state: present
- name: Ensure SSH key exists for passwordless authentication
ansible.builtin.copy:
src: "{{ ssh_key }}.pub"
dest: "/home/{{ ansible_user }}/.ssh/authorized_keys"
remote_src: yes
- name: Create backup script
copy:
dest: "/usr/local/bin/backup_script.sh"
mode: "0755"
content: |
#!/bin/bash
LOGFILE={{ log_file }}
echo "Backup process started at $(date)" >> $LOGFILE
# Check if jobs are running on the cluster
JOBS_RUNNING=$(some_command_to_check_jobs) # Replace with actual job-checking command
if [[ "$JOBS_RUNNING" == "0" ]]; then
echo "No jobs running, starting backup..." >> $LOGFILE
rsync -az --progress --max-size={{ max_copy_size }} -e 'ssh -i {{ ssh_key }}' {{ source_dir }}/ {{ destination_server }}:{{ dest_dir }}/ >> $LOGFILE 2>&1
echo "Backup completed at $(date)" >> $LOGFILE
else
echo "Jobs running, skipping backup." >> $LOGFILE
fi
- name: Create cron job for periodic backup
ansible.builtin.cron:
name: "Automated Cluster Data Backup"
job: "/usr/local/bin/backup_script.sh"
minute: "0"
hour: "*/1" # Runs every hour