Quick Deploy vm ESXi amb Terraform

Hola a tots, em dic Ivan i sóc administrador del sistema d'alcoholèmia (OPS).

M'agradaria explicar-vos com implemento màquines virtuals a ESXi sense vCenter utilitzant Terraform.

Molt sovint, heu de desplegar/recrear màquines virtuals per provar aquesta o aquella aplicació. A causa de la mandra, vaig pensar en automatitzar el procés. La meva recerca em va portar a un producte meravellós de l'empresa hashicorp, terraform.

Crec que molta gent sap què és Terraform, i qui no ho sap, es tracta d'una aplicació per gestionar qualsevol núvol, infraestructura o servei utilitzant el concepte IasC (Infraestructura com a codi).

Utilitzo ESXi com a entorn de virtualització. Bastant senzill, còmode i fiable.
anticipo una pregunta.

Per què terraform quan podeu utilitzar vCenter Server?

Pots, és clar, però. En primer lloc, aquesta és una llicència addicional, en segon lloc, aquest producte consumeix molt recursos i simplement no encaixa al meu servidor domèstic i, en tercer lloc, la possibilitat d'actualitzar les habilitats.

La plataforma Intel NUC actua com a servidor:

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.)

I per tant, primer és el primer.

De moment, configurem esxi, és a dir, obriu el port VNC a la configuració del tallafoc.

Per defecte, el fitxer està protegit contra escriptura. Realitzem les següents manipulacions:

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

afegiu el bloc següent al final del fitxer:

<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>

Sortir, guardar. Torneu a canviar els drets i reinicieu el servei:

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

Actual fins que es reinicia l'amfitrió. Després d'això, aquesta manipulació s'haurà de repetir.

A més, realitzaré tot el treball en una màquina virtual al mateix servidor.

Especificacions del producte:

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

A continuació, necessitem embalador, també un producte de HashiCorp.

És necessari per muntar automàticament la imatge "daurada". que utilitzarem en el futur.

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

En moviment versió envasadora es pot produir un error, ja que basat en RedHat pot contenir un paquet amb el mateix nom.

which -a packer
/usr/sbin/packer

Per a la solució, podeu crear un enllaç simbòlic o utilitzar un camí absolut /usr/bin/packer.

Ara necessitem ovftool enllaç de descàrrega. Descarrega, posa al servidor i instal·la:

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.

Seguim endavant.

A la gith he preparat tot el que necessiteu.

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

A la carpeta iso cal posar el kit de distribució del sistema operatiu. En el meu cas, això és centos 7.

També heu d'editar el fitxer. centos-7-base.json:

variables: указать свои данные для подключения
iso_urls: указать актуальный
iso_checksum: чексумма вашего образа 

Després de tots els canvis, executeu el muntatge:

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

Si tot està configurat i especificat correctament, veureu una imatge de la instal·lació automàtica del sistema operatiu. Aquest procés em porta entre 7 i 8 minuts.

Després de completar correctament a la carpeta output-packer-centos7-x86_64 es localitzarà el fitxer ova.

Instal·leu 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

Com que Terraform no té un proveïdor per a ESXi, n'heu de crear-ne un.

Posem anar:

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ó, recollim el proveïdor:

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

Estem a la meta. Anem a desplegar la nostra imatge.

Anem a la carpeta:

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

Primer de tot, editeu el fitxer variables.tf. Heu d'especificar una connexió al servidor ESXi.

A l'arxiu network_config.cfg conté la configuració de xarxa de la futura màquina virtual. Canvieu a les vostres necessitats i executeu la línia única:

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

Bé, a l'arxiu principal.tf canvieu el camí al fitxer ova pel vostre, si és diferent.

El moment de la veritat.

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.

Acabat:

terraform apply

Si tot es fa correctament, en 2-3 minuts es desplegarà una nova màquina virtual a partir de la imatge feta anteriorment.

Els usos de tot això només estan limitats per la vostra imaginació.

Només volia compartir les millors pràctiques i mostrar els punts principals quan es treballa amb aquests productes.

Gràcies per la vostra atenció!

PD: Estaré encantat de les crítiques constructives.

Font: www.habr.com

Afegeix comentari