Commencer avec vagabond
Projet LAMP
Dans cet exemple, un environnement de développement de projet LAMP personnalisé est créé avec Vagrant.
Tout d’abord, vous devrez installer [Virtual Box][1] et [Vagrant][2].
Ensuite, créez un dossier vagrant
dans votre répertoire personnel, ouvrez votre terminal et changez le répertoire actuel pour le nouveau répertoire vagrant
. Maintenant, exécutez vagrant init
. Un fichier Vagrantfile
sera créé à l’intérieur et ressemblera à ceci :
# -*- 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 = "base"
# 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 = false
# 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: "192.168.33.10"
# 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"
# 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 "../data", "/vagrant_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
#
# # Customize the amount of memory on the VM:
# vb.memory = "1024"
# 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
Ajoutez ou décommentez les lignes suivantes en éditant le fichier ci-dessus :
config.vm.box = "hashicorp/precise64"
config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.network :private_network, ip: "192.168.33.10"
config.ssh.forward_agent = true
if Vagrant::Util::Platform.windows?
config.vm.synced_folder "./", "/vagrant"
else
config.vm.synced_folder "./", "/vagrant", type: "nfs"
end
# https://stefanwrobel.com/how-to-make-vagrant-performance-not-suck
config.vm.provider "virtualbox" do |v|
host = RbConfig::CONFIG['host_os']
# Give VM 1/4 system memory & access to all cpu cores on the host
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
v.customize ["modifyvm", :id, "--memory", mem]
v.customize ["modifyvm", :id, "--cpus", cpus]
end
Modifiez votre fichier “hosts” pour rediriger le domaine souhaité vers la machine virtuelle vagabonde. Pour Linux, il s’agit de /etc/hosts
, pour Windows C:\Windows\System32\Drivers\etc\hosts
; et ajoutez cette ligne :
192.168.33.10 vagrantServer.com
Bien sûr, vous pouvez remplacer vagrantServer.com
par n’importe quel nom.
Il est maintenant temps de créer le fichier bootstrap.sh
(dans le répertoire vagrant
). Ce script sera exécuté à chaque fois que la VM sera générée à partir de zéro. Lisez bien les commentaires :
#!/usr/bin/env bash
# .ssh/authorized_keys (you will need to create a `.ssh` directory inside the `vagrant` one and add a file named `authorized_keys` with the public keys of the users who have access to the repository and may use this environment).
# You also will have to grant access to those public keys from the Github account, Bitbucket, or whatever you're using.
cat /vagrant/config/authorized_keys >> /home/vagrant/.ssh/authorized_keys
if ! [ -d /root/.ssh ]; then
mkdir /root/.ssh
fi
cp /vagrant/config/authorized_keys /root/.ssh
chmod 600 /root/.ssh/authorized_keys
# Install packages
apt-get update
apt-get install -y python-software-properties
add-apt-repository ppa:ondrej/php5 -y
apt-get update
apt-get install -y curl nano apache2 php5 php5-mysql php5-curl php5-gd php5-intl php5-mcrypt git
# Apache2 run with user vagrant
APACHEUSR=`grep -c 'APACHE_RUN_USER=www-data' /etc/apache2/envvars`
APACHEGRP=`grep -c 'APACHE_RUN_GROUP=www-data' /etc/apache2/envvars`
if [ APACHEUSR ]; then
sed -i 's/APACHE_RUN_USER=www-data/APACHE_RUN_USER=vagrant/' /etc/apache2/envvars
fi
if [ APACHEGRP ]; then
sed -i 's/APACHE_RUN_GROUP=www-data/APACHE_RUN_GROUP=vagrant/' /etc/apache2/envvars
fi
sudo chown -R vagrant:www-data /var/lock/apache2
# Set user/password to mysql previously to installation
# Replace rootMysqlPassword with your desired MySQL root password
debconf-set-selections <<< 'mysql-server mysql-server/root_password password rootMysqlPassword'
debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password rootMysqlPassword'
# Install mysql
apt-get update
apt-get install -y mysql-server mysql-client
# Link /vagrant (sync_folder) to apache directory (/var/www)
if ! [ -L /var/www ]; then
rm -rf /var/www
ln -fs /vagrant /var/www
fi
# Install composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
# Composer example. Uncoment to istall phpunit
#composer global require "phpunit/phpunit=3.7.*" --prefer-source
# Create mysql database (replace "vagrantDB" with any desired database name, and "rootMysqlPassword" with the password set above)
mysql -u root -prootMysqlPassword -v -e "CREATE USER 'developer'@'%' IDENTIFIED BY 'dev';
CREATE SCHEMA vagrantDB;
GRANT ALL ON vagrantDB TO 'developer'@'%';"
# Uncomment to set default database fixtures based on `/vagrant/config/vagrantDBFixtures.sql` file.
#mysql -u root -prootMysqlPassword -v vagrantDB < /vagrant/config/vagrantDBFixtures.sql
###################################################
################ THIS IS OPTIONAL #################
###################################################
# Install nodejs
curl -sL https://deb.nodesource.com/setup | sudo bash -
apt-get install -y nodejs
# Install npm packages
npm install -g npm
npm install -g bower
npm install -g forever
npm install -g gulp
# Set accepted license before install java
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
# Install java7
apt-get install -y oracle-java7-installer oracle-java7-set-default
###################################################
################### END OPTIONAL ##################
###################################################
# Generate ssh key without passphrase
ssh-keygen -f /root/.ssh/id_rsa -t rsa -N ""
# Add bitbucket and github to known hosts
touch /root/.ssh/known_hosts
ssh-keyscan -H bitbucket.org >> /root/.ssh/known_hosts
ssh-keyscan -H github.com >> /root/.ssh/known_hosts
# Source: https://gist.github.com/winhamwr/7122947
# Sleep until we can successfully SSH into Bitbucket.
# Uses doublinng backoff while waiting
# with_backoff() adapted from http://stackoverflow.com/a/8351489
# Retries a command a configurable number of times with backoff.
#
# The retry count is given by ATTEMPTS (default 5), the initial backoff
# timeout is given by TIMEOUT in seconds (default 1.)
#
# Successive backoffs double the timeout.
#generatedKey="`cat /root/.ssh/id_rsa.pub`"
echo -n "Generate a SSH key (https://help.github.com/articles/generating-ssh-keys/)
and add it to your Bitbucket account (Profile -> SHH keys) to continue. "
with_backoff() {
local max_attempts=${ATTEMPTS-5}
local timeout=${TIMEOUT-1}
local attempt=0
local exitCode=0
while [ $attempt -lt $max_attempts ]
do
set +e
"$@"
exitCode=$?
set -e
if [ $exitCode -eq 0 ]
then
break
fi
echo "Failure! Retrying in $timeout.." 1>&2
sleep $timeout
attempt=$(( attempt + 1 ))
timeout=$(( timeout * 2 ))
done
if [ $exitCode -ne 0 ]
then
echo "You've failed me for the last time! ($@)" 1>&2
fi
return $exitCode
}
ATTEMPTS=${ATTEMPTS:-5}
export ATTEMPTS
with_backoff ssh -T [email protected];
# Clone repositories (replace "yourProjectName" and "yourProjectRepository" with your project data)
cd /var/www
rm -rf yourProjectName/
git clone yourProjectRepository
# Add server names to /etc/hosts (replace "vagrantServer.com" with the domain set above)
echo -e '\n127.0.0.1 vagrantServer.com' >> /etc/hosts
# Enable apache modes
a2enmod rewrite
# Copy sites-available file (you need to add the Apache configuration file for the desired domain in `config/sites-available`. Replace "vagrantServer.conf" with the desired name)
cp /vagrant/config/sites-available/vagrantServer.conf /etc/apache2/sites-available/
# Remove html from document root
sed -i 's/\/var\/www\/html/\/var\/www/g' /etc/apache2/sites-available/*
service apache2 restart
# Enable sites (replace "vagrantServer.conf" with the above file name)
a2ensite vagrantServer.conf
# Install ruby, compass and sass (Optional)
apt-get install -y rubygems
gem install compass
npm install -g sass
# Pull the repo
cd /var/www/yourProjectName
git pull --all
Une fois vérifié et enregistré le fichier ci-dessus, accédez à nouveau à votre terminal, changez le répertoire actuel en celui de vagrant
que vous avez créé auparavant et tapez vagrant up
. La machine virtuelle sera créée et le fichier boostrap exécuté à partir de la machine virtuelle, de sorte que tous les éléments nécessaires seront copiés/installés. Une fois terminé, vous pouvez ouvrir votre navigateur et aller sur vagrantServer.com
(ou quel que soit le nom que vous lui avez donné) et vous devriez voir le contenu servi à partir de la machine virtuelle vagrant.
Vous pourrez également modifier vos fichiers de projet via le répertoire vagrant/yourProjectName
et tous les fichiers du répertoire vagrant
seront partagés et synchronisés entre votre hôte et la machine virtuelle vagrant.
[1] : https://www.virtualbox.org/ [2] : https://www.vagrantup.com/downloads.html
Télécharger l’image Vagrant Box sur Amazon AWS AMI
Vous avez une boîte de vagabond locale que vous souhaitez télécharger sur Amazon AWS. Tout d’abord, vous devez créer un fichier .box
:
vagrant package --base my-virtual-machine
This step should take a while depending on the size of your image. Then, you need to get the .vmdk
image from the .box
file:
gunzip -S .box package.box
paquet tar xf
After this step, you should have 4 new files: package
, box-disk1.vmdk
, Vagrantfile
, and box.ovf
. Now, to upload to AWS. Assuming you have a AWS account , create an S3 bucket to store the image on Amazon’s servers. You’re going to need Amazon’s EC2 CLI for the next step (as you can’t do this through the console as far as I can tell):
ec2-import-instance box-disk1_1.vmdk -f VMDK -t t2.micro -a x86_64 -b <S3-bucket-name> -o $AWS_ACCESS_KEY -w $AWS_SECRET_KEY -p Linux
Le résultat de cette commande devrait prendre un certain temps - il télécharge le gros fichier image sur S3, mais la commande elle-même revient plus rapidement. Vous pouvez vérifier la progression de l’importation à l’aide de la commande ec2-describe-conversion-tasks
.
Une fois cette opération terminée, vous verrez une instance de votre boîte s’exécuter dans la console AWS. Cependant, vous ne pourrez peut-être pas y accéder car il n’a pas d’adresse IP publique et/ou n’a pas de fichier .pem
associé. Ainsi, l’étape suivante consiste à créer une AMI à partir de l’instance. Pour créer une AMI, arrêtez l’instance (ne la résiliez pas !) et faites un clic droit sur l’instance et allez dans Image
->Create Image
. Cela devrait également prendre un certain temps. Vous pouvez vérifier la progression dans la vue AMI de la console. Une fois qu’il est terminé, lancez une instance à l’aide de l’AMI en y attachant un fichier de clé “.pem”, puis vous pouvez “ssh” et vous êtes prêt à partir.
Installation pour Windows avec prise en charge de VirtualBox et SSH
Pour utiliser Vagrant sur la plate-forme Windows, vous devez d’abord installer un logiciel de virtualisation et un outil de ligne de commande ssh. Cet exemple utilisera les logiciels gratuits VirtualBox et Cygwin.
Installer VirtualBox
Téléchargez la dernière version de VirtualBox depuis la [page de téléchargement officielle][1] et exécutez le fichier téléchargé. Notez que pendant l’installation, vous perdrez temporairement la connexion réseau. [![Avertissement : Interfaces réseau][2]][2]
Vous devez également laisser Oracle installer des pilotes supplémentaires.
Installer Cygwin
Obtenez-le sur [cygwin.com][3] et exécutez la configuration jusqu’à ce que vous obteniez la page “Sélectionner les packages”.
Nous avons seulement besoin de ssh bin-s à partir d’ici : [![Packages Cygwin SSH][4]][4]
Ajouter Cygwin au CHEMIN
Vous devez également ajouter le dossier C:\cygwin64\bin
à la variable d’environnement Windows PATH. Ainsi, vous pouvez appeler la commande ssh
de n’importe où.
Installez Vagrant lui-même
Téléchargez Vagrant depuis [vagrantup.com][5] et suivez simplement le guide d’installation pour l’installer. Vous devez redémarrer votre ordinateur après cela.
Essai
La technologie de virtualisation VTx/VTd doit être activée. (Vous pouvez trouver cela dans le BIOS dans les options de sécurité)
Pour tester si tout est correctement installé, créez un dossier vide quelque part sur le disque dur, ouvrez la ligne de commande et déplacez-vous vers le dossier que vous venez de créer :
cd c:/path/to/your/folder
puis entrez
vagrant init hashicorp/precise64
vagrant up
Cela créera et lancera la VirtualBox exécutant Ubuntu 12.04 LTS 64 bits. Pour lancer la version 32 bits, utilisez vagrant init hashicorp/precise32
. Si vous avez besoin d’une autre boîte, vous pouvez en trouver plus sur le [site Web de hashicorp][6].
De plus, la commande vagrant init
créera un fichier de configuration Vagrantfile
dans le dossier actuel. Maintenant, vous pouvez simplement l’envoyer à quelqu’un d’autre et lorsque cette personne appelle “vagabond”, la même machine virtuelle exacte sera créée sur son PC.
Pour tester ssh après l’exécution réussie de ces deux commandes, exécutez cette commande dans le même dossier :
vagrant ssh
Si tout s’est bien passé, vous vous retrouverez dans la machine virtuelle connectée en tant qu’utilisateur “vagabond”.
Prochaines étapes
Vous pouvez arrêter la VM avec
vagrant halt
ou supprimez-le avec
vagrant destroy
Plus de boîtes avec les instructions pour les installer peuvent être trouvées sur la page [vagrantbox.es][7].
[1] : https://www.virtualbox.org/wiki/Downloads [2] : http://i.stack.imgur.com/6Y3NP.png [3] : http://cygwin.com/install.html [4] : http://i.stack.imgur.com/ei8Le.png [5] : https://www.vagrantup.com/downloads.html [6] : https://atlas.hashicorp.com/boxes/search [7] : http://www.vagrantbox.es/
Le moyen le plus simple d’avoir un Linux virtuel en quelques minutes (en 3 étapes)
Étape 1.
Dans votre machine hôte (Windows/Linux/OSX), créez un répertoire vide my_project
.
Étape 2.
Créez un fichier nommé “Vagrantfile” avec ceci :
Vagrant.configure("2") do |config|
config.vm.box = "gbarbieru/xenial" #An Ubuntu 16.04 based image
config.vm.hostname = "my_project"
config.vm.network :private_network, ip: "172.16.123.10"
end
Étape 3.
Exécutez votre machine :
host$ vagrant up
host$ vagrant ssh
virtual$ cd /vagrant
Fait!
Remarques:
- Peut-être souhaitez-vous attribuer une autre adresse IP.
- Si votre hôte est Windows, vous voudrez peut-être utiliser
ssh
à partir deputty
. Vous pouvez le faire en ssh-ing au nom d’hôte127.0.0.1
et le port ‘2222’. Le nom d’utilisateur est “vagrant” et le mot de passe est “vagrant”.
synchronisation de tous les dossiers
Pour synchroniser tous les dossiers dans les deux sens, insérez ceci dans votre Vagrantfile
config.vm.synced_folder "my-project1", "/home/vagrant/my-project1"
synchroniser les dossiers mais exclure certains dossiers
Pour synchroniser tous les dossiers dans les deux sens, insérez ceci dans votre Vagrantfile :
config.vm.synced_folder "my-project1", "/home/vagrant/my-project1", type: "rsync",
:rsync__exclude => ['my-project1/mini_project2/target,my-project1/mini_project2/target,my-project1/mini_project3/target']
Tous les dossiers cibles sont exclus de la synchronisation.
La synchronisation ne se produit que sur vagrant up
et sur vagrant reload
.
Pour synchroniser chaque modification de votre hôte à l’invité, vous devez utiliser :
vagrant rsync-auto