Pular para o conteúdo

Vagrant

Guia abrangente de comandos e fluxos de trabalho do HashiCorp Vagrant para gerenciamento de ambientes de desenvolvimento e provisionamento de máquinas virtuais.

Instalação e Configuração

ComandoDescrição
vagrant versionMostrar versão do Vagrant
vagrant -hMostrar informações de ajuda
vagrant initInicializar novo Vagrantfile
vagrant init ubuntu/jammy64Inicializar com caixa específica

Gerenciamento de Boxes

Operações de Box

ComandoDescrição
vagrant box listListar caixas instaladas
vagrant box add ubuntu/jammy64Adicionar caixa
vagrant box add --name mybox /path/to/box.boxAdicionar caixa local
vagrant box remove ubuntu/jammy64Remover caixa
vagrant box updateAtualizar todas as caixas
vagrant box update --box ubuntu/jammy64Atualizar caixa específica

Informações de Box

ComandoDescrição
vagrant box outdatedVerificar caixas desatualizadas
vagrant box pruneRemover versões antigas de box
vagrant box repackage ubuntu/jammy64Reembalar caixa

Gerenciamento do Ciclo de Vida da VM

Operações Básicas

ComandoDescrição
vagrant upIniciar e provisionar VM
vagrant haltDesligar VM
vagrant reloadReiniciar VM
vagrant destroyDestruir VM
vagrant suspendSuspender VM
vagrant resumeRetomar VM suspensa

Status e Informações da VM

ComandoDescrição
vagrant statusMostrar status da VM
vagrant global-statusMostrar status de todas as VMs
vagrant global-status --pruneLimpar entradas inválidas

SSH e Acesso

Operações de SSH

ComandoDescrição
vagrant sshSSH no VM
vagrant ssh-configMostrar configuração SSH
vagrant ssh -- -L 8080:localhost:80SSH com encaminhamento de porta

Provisionamento

Comandos de Provisionamento

ComandoDescrição
vagrant provisionExecutar provisionadores
vagrant provision --provision-with shellExecutar provisionador específico
vagrant up --provisionIniciar e provisionar
vagrant reload --provisionReiniciar e provisionar

Ambientes Multi-Máquina

Comandos Multi-Máquina

ComandoDescrição
vagrant up webIniciar máquina específica
vagrant ssh webSSH para máquina específica
vagrant halt dbParar máquina específica
vagrant destroy --forceDestruir todos sem confirmação

Snapshots

Gerenciamento de Snapshots

ComandoDescrição
vagrant snapshot save snapshot_nameSalvar snapshot
vagrant snapshot listListar snapshots
vagrant snapshot restore snapshot_nameRestaurar snapshot
vagrant snapshot delete snapshot_nameExcluir snapshot

Gerenciamento de Plugins

Operações de Plugin

ComandoDescrição
vagrant plugin listListar plugins instalados
vagrant plugin install vagrant-vbguestInstalar plugin
vagrant plugin uninstall vagrant-vbguestDesinstalar plugin
vagrant plugin updateAtualizar todos os plugins

Exemplos de Vagrantfile

Vagrantfile Básico

Vagrant.configure("2") do|config|
  config.vm.box = "ubuntu/jammy64"
  config.vm.hostname = "myserver"

  # Network configuration
  config.vm.network "private_network", ip: "192.168.56.10"
  config.vm.network "forwarded_port", guest: 80, host: 8080

  # Provider configuration
  config.vm.provider "virtualbox" do|vb|
    vb.memory = "2048"
    vb.cpus = 2
    vb.name = "MyVM"
  end

  # Provisioning
  config.vm.provision "shell", inline: <<-SHELL
    apt-get update
    apt-get install -y nginx
    systemctl enable nginx
    systemctl start nginx
  SHELL
end

Configuração Multi-Máquina

Vagrant.configure("2") do|config|
  # Web server
  config.vm.define "web" do|web|
    web.vm.box = "ubuntu/jammy64"
    web.vm.hostname = "web"
    web.vm.network "private_network", ip: "192.168.56.10"

    web.vm.provider "virtualbox" do|vb|
      vb.memory = "1024"
      vb.cpus = 1
    end

    web.vm.provision "shell", inline: <<-SHELL
      apt-get update
      apt-get install -y nginx
    SHELL
  end

  # Database server
  config.vm.define "db" do|db|
    db.vm.box = "ubuntu/jammy64"
    db.vm.hostname = "database"
    db.vm.network "private_network", ip: "192.168.56.11"

    db.vm.provider "virtualbox" do|vb|
      vb.memory = "2048"
      vb.cpus = 2
    end

    db.vm.provision "shell", inline: <<-SHELL
      apt-get update
      apt-get install -y mysql-server
    SHELL
  end
end

Configuração Avançada

Vagrant.configure("2") do|config|
  config.vm.box = "ubuntu/jammy64"
  config.vm.box_version = "20230607.0.0"

  # Synced folders
  config.vm.synced_folder ".", "/vagrant", disabled: true
  config.vm.synced_folder "./app", "/var/www/html",
    owner: "www-data", group: "www-data"

  # Network configuration
  config.vm.network "private_network",
    ip: "192.168.56.10",
    netmask: "255.255.255.0"

  config.vm.network "public_network",
    bridge: "en0: Wi-Fi (AirPort)"

  # Port forwarding
  config.vm.network "forwarded_port", guest: 80, host: 8080
  config.vm.network "forwarded_port", guest: 443, host: 8443

  # Provider-specific configuration
  config.vm.provider "virtualbox" do|vb|
    vb.gui = false
    vb.memory = "4096"
    vb.cpus = 4
    vb.name = "Development Server"

    # VirtualBox specific settings
    vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
    vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
  end

  # Multiple provisioners
  config.vm.provision "shell", inline: <<-SHELL
    apt-get update
    apt-get upgrade -y
  SHELL

  config.vm.provision "file",
    source: "./configs/nginx.conf",
    destination: "/tmp/nginx.conf"

  config.vm.provision "shell", path: "scripts/setup.sh"

  config.vm.provision "ansible" do|ansible|
    ansible.playbook = "playbook.yml"
    ansible.inventory_path = "inventory"
  end
end

Métodos de Provisionamento

Provisionamento Shell

# Inline shell commands
config.vm.provision "shell", inline: <<-SHELL
  apt-get update
  apt-get install -y docker.io
  usermod -aG docker vagrant
SHELL

# External script
config.vm.provision "shell", path: "scripts/bootstrap.sh"

# Privileged and non-privileged
config.vm.provision "shell", privileged: false, inline: <<-SHELL
  echo "Running as vagrant user"
SHELL

# Environment variables
config.vm.provision "shell", env: \\\\{"DEBIAN_FRONTEND" => "noninteractive"\\\\}, inline: <<-SHELL
  apt-get install -y mysql-server
SHELL

Provisionamento de Arquivo

config.vm.provision "file",
  source: "~/.ssh/id_rsa.pub",
  destination: "~/.ssh/authorized_keys"

config.vm.provision "file",
  source: "./configs/",
  destination: "/tmp/configs"

Provisionamento Ansible

config.vm.provision "ansible" do|ansible|
  ansible.playbook = "site.yml"
  ansible.inventory_path = "inventory/vagrant"
  ansible.limit = "all"
  ansible.verbose = "v"

  ansible.extra_vars = \\\\{
    nginx_port: 80,
    database_name: "myapp"
  \\\\}
end

Provisionamento Docker

config.vm.provision "docker" do|d|
  d.pull_images "nginx"
  d.pull_images "mysql:8.0"

  d.run "nginx",
    args: "-p 80:80 -v /vagrant/html:/usr/share/nginx/html"

  d.run "mysql",
    args: "-e MYSQL_ROOT_PASSWORD=secret -p 3306:3306"
end

Configuração de Rede

Redes Privadas

# Static IP
config.vm.network "private_network", ip: "192.168.56.10"

# DHCP
config.vm.network "private_network", type: "dhcp"

# Multiple interfaces
config.vm.network "private_network", ip: "192.168.56.10"
config.vm.network "private_network", ip: "10.0.0.10"

Redes Públicas

Would you like me to continue with the remaining translations or placeholders for the empty sections?```ruby

Bridge to default interface

config.vm.network “public_network”

Bridge to specific interface

config.vm.network “public_network”, bridge: “en0: Wi-Fi (AirPort)“

Static IP on public network

config.vm.network “public_network”, ip: “192.168.1.100”


### Port Forwarding
```ruby
# Basic port forwarding
config.vm.network "forwarded_port", guest: 80, host: 8080

# Multiple ports
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.network "forwarded_port", guest: 443, host: 8443
config.vm.network "forwarded_port", guest: 3306, host: 3306

# Auto-correct port conflicts
config.vm.network "forwarded_port", guest: 80, host: 8080, auto_correct: true

Provider Configuration

VirtualBox Provider

config.vm.provider "virtualbox" do|vb|
  vb.gui = true
  vb.memory = "4096"
  vb.cpus = 4
  vb.name = "MyVM"

  # Advanced settings
  vb.customize ["modifyvm", :id, "--vram", "128"]
  vb.customize ["modifyvm", :id, "--accelerate3d", "on"]
  vb.customize ["modifyvm", :id, "--clipboard", "bidirectional"]
end

VMware Provider

config.vm.provider "vmware_desktop" do|vmware|
  vmware.vmx["memsize"] = "4096"
  vmware.vmx["numvcpus"] = "4"
  vmware.vmx["displayName"] = "MyVM"
end

Hyper-V Provider

config.vm.provider "hyperv" do|hv|
  hv.memory = 4096
  hv.cpus = 4
  hv.vmname = "MyVM"
end

Synced Folders

Basic Synced Folders

# Default synced folder (disabled)
config.vm.synced_folder ".", "/vagrant", disabled: true

# Custom synced folder
config.vm.synced_folder "./src", "/var/www/html"

# With options
config.vm.synced_folder "./app", "/var/www/html",
  owner: "www-data",
  group: "www-data",
  mount_options: ["dmode=775,fmode=664"]

NFS Synced Folders

config.vm.synced_folder "./", "/vagrant",
  type: "nfs",
  nfs_udp: false,
  nfs_version: 4

SMB Synced Folders (Windows)

config.vm.synced_folder "./", "/vagrant",
  type: "smb",
  smb_username: "username",
  smb_password: "password"

Best Practices

Performance Optimization

  1. Resource Allocation: Allocate appropriate CPU and memory
  2. Synced Folders: Use NFS for better performance on macOS/Linux
  3. Box Selection: Choose minimal base boxes
  4. Snapshot Management: Use snapshots for quick rollbacks
  5. Provider Optimization: Configure provider-specific optimizations

Security

  1. SSH Keys: Use SSH keys instead of passwords
  2. Network Isolation: Use private networks when possible
  3. Firewall: Configure appropriate firewall rules
  4. Updates: Keep boxes and Vagrant updated
  5. Secrets: Don’t commit secrets to version control

Development Workflow

  1. Version Control: Include Vagrantfile in version control
  2. Documentation: Document setup and usage
  3. Consistency: Use same environment across team
  4. Testing: Test provisioning scripts
  5. Cleanup: Regularly clean up unused VMs and boxes

Troubleshooting

  1. Logs: Check Vagrant and provider logs
  2. SSH: Use vagrant ssh-config for debugging
  3. Networking: Test network connectivity
  4. Provisioning: Test provisioning scripts separately
  5. Resources: Monitor host system resources