IaaC Terraform автоматизація legacy/baremetal environment

З чого починається будь-який масштабний проект в інтернеті, з серверів та іншого устаткування, а так як тепер важливо 100% можливість відтворити всю інфраструктуру з коду то й використання terraform для побудови такої інфраструктури буде ідеальним рішенням, так як використання git як source of truth є логічним і правильним і коли у нас є велика кількість providers для того ж terraform ( libvirt, xen та інших ) також можливо розробити свого провайдера котрий для прикладу налаштує маршрутизатор чи коммутатор.

Розглянемо простоту конфігурації для libvirt( kvm ) віртуалізації :

  1. Створимо файл main.tf з наступним контентом :
terraform {
  required_providers {
    libvirt = {
      source = "dmacvicar/libvirt"
    }
  }
}

provider "libvirt" {
    uri = "qemu:///system"
}

resource "libvirt_domain" "terraform_test" {
  name = "terraform_test"
}

2. далі нам потрібно запустити terraform init

3. після запускаємо terraform plan

у данному прикладі ми створюємо віртуальну машину terraform_test

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # libvirt_domain.terraform_test will be created
  + resource "libvirt_domain" "terraform_test" {
      + arch        = (known after apply)
      + emulator    = (known after apply)
      + fw_cfg_name = "opt/com.coreos/config"
      + id          = (known after apply)
      + machine     = (known after apply)
      + memory      = 512
      + name        = "terraform_test"
      + qemu_agent  = false
      + running     = true
      + vcpu        = 1
    }

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

4. далі створюємо віртуальну машину за допомогою terraform давши команду terraform apply:

terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # libvirt_domain.terraform_test will be created
  + resource "libvirt_domain" "terraform_test" {
      + arch        = (known after apply)
      + emulator    = (known after apply)
      + fw_cfg_name = "opt/com.coreos/config"
      + id          = (known after apply)
      + machine     = (known after apply)
      + memory      = 512
      + name        = "terraform_test"
      + qemu_agent  = false
      + running     = true
      + vcpu        = 1
    }

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

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

libvirt_domain.terraform_test: Creating...
libvirt_domain.terraform_test: Creation complete after 1s [id=cd2f61a8-cf03-432b-b5f5-d4d623be374b]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

5. переконаємось що віртуальну машину було створено за допомогою команди virsh list :

virsh list
 Id    Name                           State
----------------------------------------------------
 2     terraform_test                 running

Як ми побачили створилась віртуальна машина, тепер заберемо цю віртуальну машину за допомогою terraform destroy :

terraform destroy

libvirt_domain.terraform_test: Refreshing state... [id=cd2f61a8-cf03-432b-b5f5-d4d623be374b]

Note: Objects have changed outside of Terraform

Terraform detected the following changes made outside of Terraform since the last "terraform apply":

  # libvirt_domain.terraform_test has been changed
  ~ resource "libvirt_domain" "terraform_test" {
      + cmdline     = []
        id          = "cd2f61a8-cf03-432b-b5f5-d4d623be374b"
        name        = "terraform_test"
        # (8 unchanged attributes hidden)
    }

Unless you have made equivalent changes to your configuration, or ignored the relevant attributes using ignore_changes, the following plan may include
actions to undo or respond to these changes.

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # libvirt_domain.terraform_test will be destroyed
  - resource "libvirt_domain" "terraform_test" {
      - arch        = "x86_64" -> null
      - cmdline     = [] -> null
      - emulator    = "/usr/libexec/qemu-kvm" -> null
      - fw_cfg_name = "opt/com.coreos/config" -> null
      - id          = "cd2f61a8-cf03-432b-b5f5-d4d623be374b" -> null
      - machine     = "pc" -> null
      - memory      = 512 -> null
      - name        = "terraform_test" -> null
      - qemu_agent  = false -> null
      - running     = true -> null
      - vcpu        = 1 -> null
    }

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

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

Все це доволі просто, а запитання як змінити параметри ? – ви їх бачите в конфігурації ( name,memory,vcpu,cmdline etc.) для прикладу ви можете вказати більшу кількість пам’яті чи створити декілька віртуальних машин, чи взагалі змінити ім’я цієї машини і таке інше, можливостей купа

Залишити відповідь

Ваша e-mail адреса не оприлюднюватиметься. Обов’язкові поля позначені *