Guest User

Untitled

a guest
Nov 16th, 2017
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #!/usr/bin/env bash
  2.  
  3. # Backup MySQL databases to S3
  4.  
  5. # Follow the installation instructions listed on the user guid doc:
  6. # http://docs.aws.amazon.com/cli/latest/userguide/installing.html
  7.  
  8. # Note backups will be deleted after 90 days. This is setup in the management tab:
  9. # https://s3.console.aws.amazon.com/s3/buckets/backups.databases/?tab=management
  10.  
  11. # DB details
  12. DB_USER=""
  13. DB_PASSWORD=""
  14. DB_HOST=""
  15. DB_IGNORED=(Database mysql information_schema performance_schema cond_instances)
  16.  
  17. # S3 details
  18. S3_BUCKET=backups.databases
  19. S3_FOLDER=backups/databases
  20.  
  21. # Temp storage location
  22. TMP_DIR=/tmp
  23.  
  24. # Check if dependencies exist
  25. dependencies=(aws mysql mysqldump tar rm echo)
  26. for dependency in "${dependencies[@]}"
  27. do
  28. if [[ $(command -v "$dependency") = "" ]]
  29. then
  30. # Tell the user that the dependency is not installed, then exit the script
  31. $(which echo) "Dependency $dependency isn't installed. Install this dependency to continue."
  32. exit 0
  33. fi
  34. done
  35.  
  36. DB_DATABASES=($($(which echo) "show databases;" | $(which mysql) -h ${DB_HOST} -p${DB_PASSWORD} -u ${DB_USER} 2> /dev/null))
  37.  
  38. # Filename for the backups
  39. time=$($(which date) +%b-%d-%y-%H%M)
  40. filename="backup-$time.tar.gz"
  41.  
  42. for database in "${DB_DATABASES[@]}"
  43. do
  44. # Skip ignored databases
  45. if [[ "${DB_IGNORED[@]}" =~ "$database" ]]
  46. then
  47. continue
  48. fi
  49.  
  50. # Dump database SQL schema to an SQL file stored in the temp directory
  51. $(which echo) "Backing up $database..."
  52. $(which mysqldump) -h ${DB_HOST} -u ${DB_USER} -p${DB_PASSWORD} ${database} > "$TMP_DIR/$database.sql" 2> /dev/null
  53. $(which tar) -cpzf "$TMP_DIR/$database-$filename" "$TMP_DIR/$database.sql" 2> /dev/null
  54.  
  55. # Upload the exported SQL file to S3
  56. $(which echo) "Uploading to S3..."
  57. $(which aws) s3 cp "$TMP_DIR/$database-$filename" "s3://$S3_BUCKET/$S3_FOLDER/$database-$filename"
  58. $(which echo) "Database $database uploaded to S3"
  59.  
  60. # Remove the temporary files
  61. $(which echo) "Cleaning up..."
  62. $(which rm) -f "$TMP_DIR/$database-$filename"
  63. $(which rm) -f "$TMP_DIR/$database.sql"
  64. done
Add Comment
Please, Sign In to add comment