create_db.sh 870 B

123456789101112131415161718192021222324
  1. #!/bin/bash -xe
  2. # Create new DB in dockernized sql db
  3. [ $# -eq 0 ] && { echo "Usage: $0 <database_name>"; exit 1; }
  4. # Remove special characters and make db / username lower case
  5. DB_NAME=`echo $1 | tr -dc '[:alnum:]\n\r' | tr '[:upper:]' '[:lower:]'`
  6. # Source db root pass
  7. source /opt/docker/db/.env
  8. # Generate password for the new db
  9. NEW_DB_PASS=`pwgen --ambiguous 32 1`
  10. # Create db, corresponding user and grant privileges
  11. docker exec db mysql -p$MYSQL_ROOT_PASSWORD --execute "CREATE DATABASE $DB_NAME; \
  12. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX ON $DB_NAME.* TO \"$DB_NAME\"@\"%\" IDENTIFIED BY \"$NEW_DB_PASS\"; \
  13. FLUSH PRIVILEGES;"
  14. # Create conf file to be source by other scripts
  15. echo "DB_FOR=$1" >> $1__db.conf
  16. echo "DB_NAME=$DB_NAME" >> $1__db.conf
  17. echo "DB_USER=$DB_NAME" >> $1__db.conf
  18. echo "DB_PASS=$NEW_DB_PASS" >> $1__db.conf