Skip to content

Instantly share code, notes, and snippets.

@EmranAhmed
Last active April 3, 2018 18:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save EmranAhmed/10682844 to your computer and use it in GitHub Desktop.
Save EmranAhmed/10682844 to your computer and use it in GitHub Desktop.
vagrant SHELL Provision for LAMP, mysql backup, mysql dump database ex: https://github.com/fideloper/Vaprobash https://gist.github.com/tleish/1c6e788c84f59200446b

Shell Script to Dump all MySQL Databases Into Separate Files


#! /bin/bash
TIMESTAMP=$(date +"%F-%H-%M-%S")
BACKUP_DIR="/full/path/to/directory"
MYSQL_USER="username"
MYSQL=/Applications/MAMP/Library/bin/mysql
MYSQL_PASSWORD="password"
MYSQLDUMP=/Applications/MAMP/Library/bin/mysqldump
$MYSQL -s -r -u $MYSQL_USER -p$MYSQL_PASSWORD -e 'show databases' |
while read db; do
$MYSQLDUMP -u $MYSQL_USER -p$MYSQL_PASSWORD $db > $BACKUP_DIR/$TIMESTAMP-${db}.sql;
done

Update the variables at the top with your own, particularly the paths to mysql and mysqldump.

Don’t forget to make it executable!

cd /path/to/script/directory
chmod +x mysqlbackup.sh

You can then run it as normal with:

./mysqlbackup.sh

Another One


#!/bin/bash
################################################
#
# Backup all MySQL databases in separate files and compress those.
# Furthermore the script will create a folder with the current time stamp
# @author: Per Lasse Baasch (http://skycube.net)
# @Version: 2014-06-13
# NOTE: MySQL and gzip installed on the system
# and you will need write permissions in the directory where you executing this script
#
################################################
# MySQL User
USER='root'
# MySQL Password
PASSWORD='password'
# Backup Directory - NO TAILING SLASH!
OUTPUT="."
 
##### And 
TIMESTAMP=`date +%Y%m%d_%H%M%S`;
mkdir $OUTPUT/$TIMESTAMP;
cd $OUTPUT/$TIMESTAMP;
echo "Starting MySQL Backup";
echo `date`;
databases=`mysql --user=$USER --password=$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`
for db in $databases; do
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "mysql" ]]  && [[ "$db" != "performance_schema" ]] ; then
        echo "Dumping database: $db"
        mysqldump --force --opt --user=$USER --password=$PASSWORD --databases $db > $OUTPUT/dbbackup-$TIMESTAMP-$db.sql
	    gzip $OUTPUT/dbbackup-$TIMESTAMP-$db.sql
    fi
done
echo "Finished MySQL Backup";
echo `date`;

Which One I used Successfully :D

#! /bin/bash
TIMESTAMP=$(date +"%F-%H-%M-%S")
BACKUP_DIR="/Users/emran/Desktop/all_sql_bkk/databases"
MYSQL_USER="root"
MYSQL=/Applications/mampstack/mysql/bin/mysql
MYSQL_PASSWORD="123"
MYSQLDUMP=/Applications/mampstack/mysql/bin/mysqldump
databases=`$MYSQL --user=$MYSQL_USER --password=$MYSQL_PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`
for db in $databases; do
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "mysql" ]]  && [[ "$db" != "performance_schema" ]] ; then
        echo "Dumping database: $db"
        $MYSQLDUMP --force --opt --user=$MYSQL_USER --password=$MYSQL_PASSWORD --databases $db > $BACKUP_DIR/${db}.sql;
    fi
done
echo "Finished MySQL Backup";
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://atlas.hashicorp.com/search.
config.vm.box = "chef/debian-7.7"
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
config.vm.box_check_update = true
# Create a hostname, don't forget to put it to the `hosts` file
# This will point to the server's default virtual host
# TO DO: Make this work with virtualhost along-side xip.io URL
config.vm.hostname = "sites.dev"
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# config.vm.network "forwarded_port", guest: 80, host: 8080
# Create a private network, which allows host-only access to the machine
# using a specific IP.
config.vm.network "private_network", ip: "222.222.22.2"
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network "public_network", ip: "192.168.1.230"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "./www", "/var/www", :owner => "www-data", group: 'www-data', :mount_options => [ "dmode=755", "fmode=644" ], create: true, type: "nfs"
# config.vm.synced_folder "./www", "/var/www", type: "nfs"
# Use NFS for the shared folder
config.vm.synced_folder "./www", "/var/www",
id: "core",
:nfs => true,
:mount_options => ['nolock,vers=3,udp,noatime,actimeo=2']
# config.vm.synced_folder "./www", "/var/www", :owner => "www-data", group: 'www-data'
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
# vb.gui = true
vb.name = "Sites.dev"
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ["modifyvm", :id, "--cpus", "2"]
#vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
#vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
#
end
#
# View the documentation for the provider you are using for more
# information on available options.
# Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
# such as FTP and Heroku are also available. See the documentation at
# https://docs.vagrantup.com/v2/push/atlas.html for more information.
# config.push.define "atlas" do |push|
# push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
# end
# Enable provisioning with a shell script. Additional provisioners such as
# Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
# documentation for more information about their specific syntax and use.
# config.vm.provision "shell", inline: <<-SHELL
# sudo apt-get update
# sudo apt-get install -y apache2
# SHELL
end
  • open cd /etc/apache2/sites-enabled
  • touch vboxes.conf
  • Write
<VirtualHost *:80>
  ServerName projectname.dev

  ## Vhost docroot
  DocumentRoot "/var/www/projectname"

  ## Directories, there should at least be a declaration for /var/www/projectname

  <Directory "/var/www/projectname">
    Options Indexes FollowSymlinks MultiViews
    AllowOverride All
    Require all granted
  </Directory>

  ## Load additional static includes


  ## Logging
  ErrorLog "/var/log/apache2/projectname.log"
  ServerSignature Off
  CustomLog "/var/log/apache2/projectname.log" combined


  ## Server aliases
  ServerAlias www.projectname.dev

  ## SetEnv/SetEnvIf for environment variables
  SetEnv APP_ENV dev

  ## Custom fragment

  ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi:///var/www/projectname/$1
  
</VirtualHost>
  • and
<VirtualHost *:80>
  ServerName projectname2.dev

  ## Vhost docroot
  DocumentRoot "/var/www/projectname2"

  ## Directories, there should at least be a declaration for /var/www/projectname2

  <Directory "/var/www/projectname2">
    Options Indexes FollowSymlinks MultiViews
    AllowOverride All
    Require all granted
  </Directory>

  ## Load additional static includes


  ## Logging
  ErrorLog "/var/log/apache2/projectname2.log"
  ServerSignature Off
  CustomLog "/var/log/apache2/projectname2.log" combined


  ## Server aliases
  ServerAlias www.projectname2.dev

  ## SetEnv/SetEnvIf for environment variables
  SetEnv APP_ENV dev

  ## Custom fragment

  ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi:///var/www/projectname2/$1
  
</VirtualHost>
  • then a2ensite vboxes
# -*- mode: ruby -*-
# vi: set ft=ruby :
# HOST MANAGER: https://github.com/smdahlen/vagrant-hostmanager
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "debian7"
config.vm.network "private_network", ip: "222.222.22.2"
# Use NFS for shared folders for better performance ( https://stefanwrobel.com/how-to-make-vagrant-performance-not-suck )
config.vm.synced_folder ".", "/var/www", :owner => "www-data", :mount_options => [ "dmode=775", "fmode=774" ], create: true, type: "nfs"
# config.vm.synced_folder "mysql", "/var/lib/mysql", :mount_options => [ "dmode=777", "fmode=777" ]
# Use NFS for shared folders for better performance
config.vm.synced_folder "sqlbackup", "/home/vagrant", :mount_options => [ "dmode=777", "fmode=777" ], create: true, type: "nfs"
config.vm.provider "virtualbox" do |vb|
host = RbConfig::CONFIG['host_os']
# Give VM 1/4 system memory & access to all cpu cores on the host
# Use all CPU cores and 1/4 system memory
if host =~ /darwin/
cpus = `sysctl -n hw.ncpu`.to_i
# sysctl returns Bytes and we need to convert to MB
mem = `sysctl -n hw.memsize`.to_i / 1024 / 1024 / 4
elsif host =~ /linux/
cpus = `nproc`.to_i
# meminfo shows KB and we need to convert to MB
mem = `grep 'MemTotal' /proc/meminfo | sed -e 's/MemTotal://' -e 's/ kB//'`.to_i / 1024 / 4
else # sorry Windows folks, I can't help you
cpus = 2
mem = 1024
end
vb.customize ["modifyvm", :id, "--memory", mem]
vb.customize ["modifyvm", :id, "--cpus", cpus]
# allocate max 30% CPU
# vb.customize ["modifyvm", :id, "--cpuexecutioncap", "30"]
# vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
# vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
end
end
# vagrant halt
# vagrant up
# vagrant reload
# vagrant global-status
# vagrant status
# vagrant box add debian75 debian-7.5-x86_64-v1.2-virtualbox.box
# vagrant box list
# vagrant ssh
# ==================================================================================================
## Export
cd ~/
##### /
mysqldump -u root -p[root_password] [database_name] > database_name.sql
## Import
mysql -u root -p[root_password] [database_name] < database_name.sql
sudo apt-get update -y
sudo apt-get upgrade -y
sudo apt-get install curl vim build-essential python-software-properties software-properties-common git-core -y
sudo apt-get install apache2 -y
# PHP 5.5
sudo nano /etc/apt/sources.list
deb http://packages.dotdeb.org wheezy all
deb-src http://packages.dotdeb.org wheezy all
deb http://packages.dotdeb.org wheezy-php55 all
deb-src http://packages.dotdeb.org wheezy-php55 all
wget http://www.dotdeb.org/dotdeb.gpg
sudo apt-key add dotdeb.gpg
rm dotdeb.gpg
sudo apt-get update
sudo apt-get install -y build-essential software-properties-common vim curl wget tmux
sudo apt-get update
# End PHP 5.5
sudo apt-get install mysql-server mysql-client -y
sudo mysql_secure_installation
sudo /usr/bin/mysql_secure_installation
sudo apt-get install php5 php5-common php5-curl php5-gd php5-xmlrpc php-pear php5-mysql libapache2-mod-php5 php5-mcrypt php5-json git-core -y
# For new MySQL 5.6 family you need to install php5-mysqlnd, not php5-mysql.
# If you install php5-mysql remove it by: sudo apt-get remove php5-mysql and install by: sudo apt-get install php5-mysqlnd
# Finding php extensions
#### apt-cache search php5-
#### Enabling/Installing Intl Extension PHP From Terminal: sudo apt-get install php5-intl, restart php / apache2.
#### check available extension installed php -m
sudo apt-get install phpmyadmin -y
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo apt-get install nodejs nodejs-legacy
sudo nano /etc/php5/apache2/php.ini
# upload_max_filesize = 100M
# post_max_size = 512M
# memory_limit = 256M
# error_reporting = E_ALL
# display_errors = On
sudo nano /etc/apache2/sites-available/default
# And Add
# <Directory /var/www/>
# Options Indexes FollowSymLinks MultiViews
# AllowOverride All
# Order allow,deny
# allow from all
# </Directory>
sudo nano /etc/php5/mods-available/xdebug.ini
# xdebug.scream=1
# xdebug.cli_color=1
# xdebug.show_local_vars=1
sudo usermod -a -G vagrant www-data
sudo apt-get purge libapache2-mod-php5
sudo apt-get install libapache2-mod-php5
sudo a2enmod rewrite
sudo a2enmod php5
sudo service apache2 restart
sudo service mysql restart
# On a Debian 7 box I also needed to
# sudo apt-get install ruby1.9.3-dev
# sudo apt-get sqlite3 libsqlite3-dev
sudo apt-get install -y build-essential libsqlite3-dev ruby1.9.3
sudo gem install mailcatcher
echo "/usr/bin/env $(which catchmail) -f admin@sites.dev" # Copy it
sudo nano /etc/php5/apache2/php.ini
# => smtp_port = 1025
# => sendmail_path = "/usr/bin/env /usr/local/bin/catchmail -f admin@sites.dev"
# ps ax | grep mailcatcher STOP ALREADY RUNNED MAILCATCHAR
sudo service apache2 restart
mailcatcher --foreground --http-ip=0.0.0.0 # For temporary
sudo mailcatcher --http-ip=0.0.0.0 # Direct
# mailcatcher Web UI IS: http://sites.dev:1080
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install -y build-essential
sudo apt-get install -y python-software-properties
sudo add-apt-repository ppa:ondrej/php5
sudo apt-get update
sudo apt-get install php5 php5-common php5-curl php5-gd php5-cli php5-xmlrpc php-pear php5-mysql apache2 libapache2-mod-php5 php5-mcrypt php5-json git-core php5-ldap php5-xdebug php5-mysql mysql-server -y
sudo a2enmod rewrite
sudo debconf-set-selections <<< 'mysql-server \
mysql-server/root-password password root'
sudo debconf-set-selections <<< 'mysql-server \
mysql-server/root_password_again password root'
sudo service mysql restart
sudo service apache2 restart
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

vagrant init => Create Vagrentfile

vagrant up => start settingup vagrent

Adding Box from local

cd ~/Sites/ubuntu

vagrant box add BOXNAME BOXFILE.box => Add custom box / from local

add BOXNAME on Vagrentfile

cd ~/Sites/ubuntu

vagrant ssh => ssh connect

vagrant box list => list of added box

vagrant repackage

the repackage command creates a distributable box file from the unpacked box in your ~/.vagrant.d/boxes directory.

Let's say you vagrant box add a box named centos.box from an URL vagrant will extract centos.box in your vagrant home folder (the box format is just a tar file) in my case ~/.vagrant.d/boxes/chef-VAGRANTSLASH-debian-7.7/1.0.0/virtualbox

In that folder you will see files like : [root@goll tmp]# ls ~/.vagrant.d/boxes/chef-VAGRANTSLASH-debian-7.7/1.0.0/virtualbox box-disk1.vmdk box.ovf metadata.json Vagrantfile

see that you deleted this centos_x86_64.box, and no longer have it. check it from vagrant box list When you run vagrant box repackage chef/debian-7.7 virtualbox 1.0.0 vagrant will create a new tar file in the current directory named package.box containing those 3 files.

New Vagrant Box

  • login to vagrant vagrant ssh
  • sudo apt-get clean
  • Then, “zero out” the drive (this is for Ubuntu):
  • sudo dd if=/dev/zero of=/EMPTY bs=1M
  • sudo rm -f /EMPTY
  • clear the Bash History and exit the VM:
  • cat /dev/null > ~/.bash_history && history -c && exit
  • vagrant package --output YOUR_BOX_NAME-ubuntu64.box or vagrant package --base YOUR_BOX_NAME-ubuntu64
  • using:
  • vagrant box add YOUR_BOX_NAME-ubuntu64 YOUR_BOX_NAME-ubuntu64.box
  • vagrant init YOUR_BOX_NAME-ubuntu64
  • vagrant up
  • If you get /opt/vagrant/embedded/gems/gems/vagrant-1.7.4/lib/vagrant/pre-rubygems.rb:31: warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777 or /opt/vagrant/embedded/gems/gems/bundler-1.10.5/lib/bundler/shared_helpers.rb:78: warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777 then use
  • sudo chmod go-w /usr/local/bin on your mac
Resources
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "hashicorp/precise64"
config.vm.network "private_network", ip: "192.168.0.210"
config.vm.synced_folder "./dev", "/var/www", create: true
config.vm.provision "shell", path: "https://gist.githubusercontent.com/EmranAhmed/10682844/raw/13d127a5982fa47331aa019ac2d27b9c08f86229/vagrant-provision.sh"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment