Implementación rápida de vm ESXi con Terraform

Hola a todos, mi nombre es Ivan y soy administrador del sistema alcohólico (OPS).

Me gustaría decirle cómo implementar máquinas virtuales en ESXi sin vCenter usando Terraform.

Muy a menudo, debe implementar / recrear máquinas virtuales para probar esta o aquella aplicación. Debido a la pereza, pensé en automatizar el proceso. Mis búsquedas me llevaron a un maravilloso producto de hashicorp , terraform .

Creo que mucha gente sabe qué es Terraform, y quién no sabe, esta es una aplicación para administrar cualquier nube, infraestructura o servicio utilizando el concepto de IasC ( Infraestructura como código ).

Como entorno de virtualización, uso ESXi. Bastante simple, conveniente y confiable.
Preveo una pregunta.
¿Por qué terraform si puede usar vCenter Server?
Puedes, por supuesto, pero. En primer lugar, esta es una licencia adicional, en segundo lugar, este producto requiere muchos recursos y simplemente no cabe en el servidor de mi hogar, y en tercer lugar, la capacidad de actualizar habilidades.

El servidor es la plataforma Intel NUC:

CPU: 2 CPUs x Intel(R) Core(TM) i3-4010U CPU @ 1.70GHz
RAM: 8Gb
HDD: 500Gb
ESXi version: ESXi-6.5.0-4564106-standard (VMware, Inc.)

Y así, lo primero es lo primero.

Por ahora, configuremos esxi, es decir, abra el puerto VNC en la configuración del firewall.

Por defecto, el archivo está protegido contra escritura. Realizamos las siguientes manipulaciones:

chmod 644 /etc/vmware/firewall/service.xml
chmod +t /etc/vmware/firewall/service.xml
vi /etc/vmware/firewall/service.xml

agregue el siguiente bloque al final del archivo:

<service id="1000">
  <id>packer-vnc</id>
  <rule id="0000">
    <direction>inbound</direction>
    <protocol>tcp</protocol>
    <porttype>dst</porttype>
    <port>
      <begin>5900</begin>
      <end>6000</end>
    </port>
  </rule>
  <enabled>true</enabled>
  <required>true</required>
</service>

Salir, guardar. Cambiamos los derechos y reiniciamos el servicio:

chmod 444 /etc/vmware/firewall/service.xml
esxcli network firewall refresh

En este caso, se necesita VNC para conectarse a la máquina virtual y especificar la ruta al archivo kickstart.

En realidad antes de reiniciar el host. Después de eso, esta manipulación tendrá que repetirse.

Además, realizaré todo el trabajo en una máquina virtual en el mismo servidor.

Características:

OS: Centos 7 x86_64 minimal
RAM: 1GB
HDD: 20GB
Selinux: disable
firewalld: disable

A continuación necesitamos empaquetador , también un producto de HashiCorp.

Es necesario para el ensamblaje automático de la imagen "dorada". Que usaremos en el futuro.

yum install unzip git -y
curl -O https://releases.hashicorp.com/packer/1.5.5/packer_1.5.5_linux_amd64.zip
unzip packer_1.5.5_linux_amd64.zip -d /usr/bin && rm -rf packer_1.5.5_linux_amd64.zip
packer version
Packer v1.5.5

Se puede producir un error en el paso de versión del empaquetador , ya que un paquete con el mismo nombre puede estar basado en RedHat.

which -a packer
/usr/sbin/packer

Para resolverlo, puede crear un enlace simbólico o usar la ruta absoluta / usr / bin / packer.

Ahora necesitamos el enlace de descarga de ovftool . Descargar, poner en el servidor e instalar:

chmod +x VMware-ovftool-4.4.0-15722219-lin.x86_64.bundle
./VMware-ovftool-4.4.0-15722219-lin.x86_64.bundle
Extracting VMware Installer...done.
You must accept the VMware OVF Tool component for Linux End User
License Agreement to continue.  Press Enter to proceed.
VMWARE END USER LICENSE AGREEMENT
Do you agree? [yes/no]:yes
The product is ready to be installed.  Press Enter to begin
installation or Ctrl-C to cancel. 
Installing VMware OVF Tool component for Linux 4.4.0
    Configuring...
[######################################################################] 100%
Installation was successful.

Hacia adelante.

En un gita, preparé todo lo que necesitaba.

git clone https://github.com/letnab/create-and-deploy-esxi.git && cd create-and-deploy-esxi

En la carpeta iso necesitas poner la distribución del sistema operativo. En mi caso es centos 7.

También es necesario editar el archivo centos-7-base.json :

variables:     
iso_urls:  
iso_checksum:    

Después de todos los cambios, ejecute el ensamblaje:

/usr/bin/packer build centos-7-base.json

Si todo está configurado y especificado correctamente, verá una imagen de la instalación automática del sistema operativo.
packer-centos7-x86_64 output will be in this color.

==> packer-centos7-x86_64: Retrieving ISO
    packer-centos7-x86_64: Using file in-place: file:///root/create-and-deploy-esxi/iso/CentOS-7-x86_64-Minimal-1908.iso
==> packer-centos7-x86_64: Remote cache was verified skipping remote upload...
==> packer-centos7-x86_64: Creating required virtual machine disks
==> packer-centos7-x86_64: Building and writing VMX file
==> packer-centos7-x86_64: Starting HTTP server on port 8494
==> packer-centos7-x86_64: Registering remote VM...
==> packer-centos7-x86_64: Starting virtual machine...
    packer-centos7-x86_64: The VM will be run headless, without a GUI. If you want to
    packer-centos7-x86_64: view the screen of the VM, connect via VNC with the password "" to
    packer-centos7-x86_64: vnc://10.10.10.10:5900
==> packer-centos7-x86_64: Waiting 7s for boot...
==> packer-centos7-x86_64: Connecting to VM via VNC (10.10.10.10:5900)
==> packer-centos7-x86_64: Typing the boot command over VNC...
==> packer-centos7-x86_64: Waiting for SSH to become available...



Este proceso lleva de 7 a 8 minutos.

Después de completar con éxito, el archivo ova se ubicará en la carpeta output-packer-centos7-x86_64 .

Instalar Terraform:

curl -O https://releases.hashicorp.com/terraform/0.12.24/terraform_0.12.24_linux_amd64.zip
unzip terraform_0.12.24_linux_amd64.zip -d /usr/bin/ && rm -rf terraform_0.12.24_linux_amd64.zip
terraform version
Terraform v0.12.24

Dado que Terraform no tiene un proveedor para ESXi, debe crearlo.

Poner ir:

cd /tmp
curl -O https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.14.2.linux-amd64.tar.gz && rm -rf go1.14.2.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
go version
go version go1.14.2 linux/amd64

A continuación, recopilamos el proveedor:

go get -u -v golang.org/x/crypto/ssh
go get -u -v github.com/hashicorp/terraform
go get -u -v github.com/josenk/terraform-provider-esxi
export GOPATH="$HOME/go"
cd $GOPATH/src/github.com/josenk/terraform-provider-esxi
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -ldflags '-w -extldflags "-static"' -o terraform-provider-esxi_`cat version`
cp terraform-provider-esxi_`cat version` /usr/bin

Estamos en la meta. Vamos a desplegar nuestra imagen.

Ve a la carpeta:

cd /root/create-and-deploy-esxi/centos7

En primer lugar, edite el archivo variables.tf . Debe especificar una conexión al servidor ESXi.

El archivo network_config.cfg contiene la configuración de red de la futura máquina virtual. Cambiamos a nuestras necesidades y ejecutamos una línea:

sed -i -e '2d' -e '3i "network": "'$(gzip < network_config.cfg| base64 | tr -d '\n')'",' metadata.json

Bueno, en el archivo main.tf, cambie la ruta al archivo ova a la suya, si es diferente.

El momento de la verdad.

terraform init
Initializing the backend...

Initializing provider plugins...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.esxi: version = "~> 1.6"
* provider.template: version = "~> 2.1"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

data.template_file.Default: Refreshing state...
data.template_file.network_config: Refreshing state...

------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # esxi_guest.Default will be created
  + resource "esxi_guest" "Default" {
      + boot_disk_size         = (known after apply)
      + disk_store             = "datastore1"
      + guest_name             = "centos7-test"
      + guest_shutdown_timeout = (known after apply)
      + guest_startup_timeout  = (known after apply)
      + guestinfo              = {
          + "metadata"          = "base64text"
          + "metadata.encoding" = "gzip+base64"
          + "userdata"          = "base64text"
          + "userdata.encoding" = "gzip+base64"
        }
      + guestos                = (known after apply)
      + id                     = (known after apply)
      + ip_address             = (known after apply)
      + memsize                = "1024"
      + notes                  = (known after apply)
      + numvcpus               = (known after apply)
      + ovf_properties_timer   = (known after apply)
      + ovf_source             = "/root/create-and-deploy-esxi/output-packer-centos7-x86_64/packer-centos7-x86_64.ova"
      + power                  = "on"
      + resource_pool_name     = (known after apply)
      + virthwver              = (known after apply)

      + network_interfaces {
          + mac_address     = (known after apply)
          + nic_type        = (known after apply)
          + virtual_network = "VM Network"
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

El final:

terraform apply

Si todo se hace correctamente, luego de 2-3 minutos se desplegará una nueva máquina virtual a partir de la imagen realizada anteriormente.

Las opciones para usar todo esto están limitadas solo por la imaginación.

Solo quería compartir las mejores prácticas y mostrar los puntos principales al trabajar con estos productos.

¡Gracias por su atención!

PD: Estaré encantado de criticar constructivamente.

All Articles