Escenario Vagrant 1E: Cluster de servidores web

De MediaWiki
Revisión del 20:37 14 ene 2026 de Joselv (discusión | contribuciones) (→‎Introdución)
(dif) ← Revisión anterior | Revisión actual (dif) | Revisión siguiente → (dif)
Ir a la navegación Ir a la búsqueda

Introdución

Aproveitándonos do feito de que o Vagrantfile está baseado en Ruby, nunha contorna onde haxa varias máquinas virtuais de configuracións similares é posible crear un bucle para definilas.

Fig. Cluster web

Vagrantfile

Supoñendo que a nosa contorna correspóndese coa figura, unha posible solución sería:

~/Vagrant$ mkdir cluster
~/Vagrant$ cd cluster/
~/Vagrant/cluster$ vagrant init --minimal
~/Vagrant/cluster$ nano Vagrantfile
Vagrant.configure("2") do |config|
  config.vm.box = "bento/ubuntu-22.04"

# WEB
  (1..3).each do |i|
    config.vm.define "web0#{i}" do |node|
        node.vm.hostname = "web0#{i}"
        node.vm.network "private_network", ip: "192.168.56.5#{i}", netmask: "255.255.255.0"
        node.vm.synced_folder "./web0#{i}", "/var/www/html", owner: "root", group: "root", mount_options: ["dmode=755,fmode=644"]
        node.vm.provision "shell", path: "apache.sh"
        node.vm.provider "virtualbox" do |vb|
            vb.name = "web0#{i}"
            # vb.gui = true
            vb.memory = "1024"
            vb.cpus = 1
            vb.linked_clone = true
            vb.customize ["modifyvm", :id, "--groups", "/Cluster"]
        end
    end
  end
end

Temos:

  • (1..3).each do |i| define un bucle con tres iteracións.
  • #{i} permite ir personalizando a configuración das distintas máquinas do bucle:
  • Nome das máquinas: web01, web02 e web03.
  • Direccións IP: 192.168.56.51, 192.168.56.52 e 192.168.56.53.
  • Cartafoles compartidos: ./web01, ./web02 y ./web03.

Descargamos o script de aprovisionamento apache.sh, creamos os cartafoles e facemos o vagrant up:

~/Vagrant/cluster$ mkdir web0{1..3}
~/Vagrant/cluster$ ls -lhF 
total 20K
-rw-rw-r-- 1 manuel manuel 2,4K sep 28 11:46 lamp.sh
-rw-rw-r-- 1 manuel manuel  642 sep 29 01:55 Vagrantfile
drwxrwxr-x 2 manuel manuel 4,0K oct  3 00:30 web01/
drwxrwxr-x 2 manuel manuel 4,0K oct  3 00:30 web02/
drwxrwxr-x 2 manuel manuel 4,0K oct  3 00:30 web03/

vagrantup

~/Vagrant/cluster$ vagrant up
Vagrant-cluster-servers.png
~/Vagrant/cluster$ vagrant status
Current machine states:

web01                     running (virtualbox)
web02                     running (virtualbox)
web03                     running (virtualbox)