LF
October 23
S3E01
UPD: доделки
Пока не хватает главного, создания ресурса, в конфиге есть только настройки провайдеров,terraform initподтверждает установку плагинов, аNo changesбез ресурсов не доказывает ни подключение к стендам, ни возможность что-то создать в облаке.
С твоими алиасами в блоке ресурса надо явно выбирать провайдер черезprovider = libvirt.storage,provider = libvirt.thinилиprovider = clo.cloud, смотря где создаёшь ресурс. Без этого терраформ возьмёт пустой конфиг по умолчанию, а не один из настроенных алиасов.
Для зачета покажи создание одного небольшого тестового ресурса у выбранного провайдера. Пришли его.tfбез секретов, выводterraform validateиterraform apply, подтверждение что ресурс появился в облаке или на нужном стенде и повторныйterraform planбез изменений. Если уже создавал, заново создавать не надо, хватит конфига и результатов.
Создаю пулы для образов на стендиках.
[lgc@localhost lf]$ cat project.tf
resource "libvirt_pool" "storage-pool" {
provider = libvirt.storage
name = "lf-pool"
type = "dir"
target = {
path = "/data/tf/lf/"
}
}
resource "libvirt_pool" "thin-pool" {
provider = libvirt.thin
name = "lf-pool"
type = "dir"
target = {
path = "/data/tf/lf/"
}
}
[lgc@localhost lf]$На стендиках на обоих примонтированы диски в /data/, все будет унифицировано. Далее это перейдет в переменные. Появились мысли, что неплохо бы это в зависимости от провайдера подставлять. В бэклог.
╷
│ Error: Unable to Connect to Libvirt
│
│ with provider["registry.terraform.io/dmacvicar/libvirt"].storage,
│ on provider.tf line 15, in provider "libvirt":
│ 15: provider "libvirt" {
│
│ An error occurred while connecting to libvirt.
│
│ URI: qemu:///system
│ Error: failed to connect to libvirt: аутентификация недоступна: нет
│ доступного агента polkit для аутентификации действия
│ «org.libvirt.unix.manage»
╵
╷
│ Error: Unable to Connect to Libvirt
│
│ with provider["registry.terraform.io/dmacvicar/libvirt"].thin,
│ on provider.tf line 21, in provider "libvirt":
│ 21: provider "libvirt" {
│
│ An error occurred while connecting to libvirt.
│
│ URI: qemu+ssh://root@192.168.1.12/system
│ Error: failed to dial libvirt: ssh: handshake failed: knownhosts: key
│ mismatchДля подключения по URI qemu:///system потребовалось добавить юзера в группу libvirt - [lgc@localhost lf]$ sudo usermod -aG libvirt lgc
Ну и ssh ключики для подключения ко второму стендику...
URI: qemu+ssh://root@192.168.1.12/system │ Error: failed to dial libvirt: ssh: handshake failed: knownhosts: key │ mismatch
И немного почистить known_host и заново подключиться по ssh.
[lgc@localhost lf]$ terraform plan
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_pool.storage-pool will be created
+ resource "libvirt_pool" "storage-pool" {
+ allocation = (known after apply)
+ available = (known after apply)
+ capacity = (known after apply)
+ id = (known after apply)
+ name = "lf-pool"
+ target = {
+ path = "/data/tf/lf/"
}
+ type = "dir"
+ uuid = (known after apply)
}
# libvirt_pool.thin-pool will be created
+ resource "libvirt_pool" "thin-pool" {
+ allocation = (known after apply)
+ available = (known after apply)
+ capacity = (known after apply)
+ id = (known after apply)
+ name = "lf-pool"
+ target = {
+ path = "/data/tf/lf/"
}
+ type = "dir"
+ uuid = (known after apply)
}
Plan: 2 to add, 0 to change, 0 to destroy.
─────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.
[lgc@localhost lf]$[lgc@localhost lf]$ 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_pool.storage-pool will be created
+ resource "libvirt_pool" "storage-pool" {
+ allocation = (known after apply)
+ available = (known after apply)
+ capacity = (known after apply)
+ id = (known after apply)
+ name = "lf-pool"
+ target = {
+ path = "/data/tf/lf/"
}
+ type = "dir"
+ uuid = (known after apply)
}
# libvirt_pool.thin-pool will be created
+ resource "libvirt_pool" "thin-pool" {
+ allocation = (known after apply)
+ available = (known after apply)
+ capacity = (known after apply)
+ id = (known after apply)
+ name = "lf-pool"
+ target = {
+ path = "/data/tf/lf/"
}
+ type = "dir"
+ uuid = (known after apply)
}
Plan: 2 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_pool.storage-pool: Creating...
libvirt_pool.thin-pool: Creating...
libvirt_pool.storage-pool: Creation complete after 1s [id=ec0483f2-d7d2-4bd0-9c49-5bec892d8188]
libvirt_pool.thin-pool: Creation complete after 1s [id=dcb0c1d5-404f-47b2-ad7b-b5f412ee064c]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
[lgc@localhost lf]$ДЗ:
- Повторил почти все. Провайдеры завелись.
Почти все потому, что некоторые моменты, как я понял, связаны только с Selectel.
В доке clo.ru я не нашел инструкции, как создавать проект. - Я выбрал дополнительно к облачному еще локальный провайдер. Более того, я его попытался сделать для двух серверов, использовав альясы и разные строки подключения:
1. Стендик, на котором терраформ
2. Стендик рядом - Задача со звездочкой: токен я сгенерировал для провайдера clo.
Если необходимо строго следовать урокам, то я заведу аккаунт на Selectel.
Детали:
Terraform 1.16.4 - https://mirror.selectel.ru/3rd-party/hashicorp-releases/terraform/
Подключение и инициализация
Для провайдера clo.ru пользовался его же доками по настройке провайдера и созданию токена
[lgc@localhost lf]$ cat provider.tf
terraform {
required_providers {
clo = {
version = "2.8.0"
source = "clo-ru/clo"
}
libvirt = {
version = ">=0.8.3"
source = "dmacvicar/libvirt"
}
}
}
# Подключение к storage
provider "libvirt" {
alias = "storage"
uri = "qemu:///system" # URI подключения к libvirt локально
}
# Подключение к thin
provider "libvirt" {
alias = "thin"
# uri = "qemu+ssh://${var.ssh_user}@${var.server2_ip}/system"
uri = "qemu+ssh://root@192.168.1.12/system"
}
# Подключение к CLO
provider "clo" {
alias = "cloud"
auth_url = "https://api.clo.ru"
token = "совершенно секретно"
}
[lgc@localhost lf]$[lgc@localhost lf]$ terraform init Initializing the backend... Initializing provider plugins... - Finding clo-ru/clo versions matching "2.8.0"... - Finding dmacvicar/libvirt versions matching ">= 0.8.3"... - Installing clo-ru/clo v2.8.0... - Installed clo-ru/clo v2.8.0 (unauthenticated) - Installing dmacvicar/libvirt v0.9.9... - Installed dmacvicar/libvirt v0.9.9 (unauthenticated) Terraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. Include this file in your version control repository so that Terraform can guarantee to make the same selections by default when you run "terraform init" in the future. ╷ │ Warning: Incomplete lock file information for providers │ │ Due to your customized provider installation methods, Terraform was forced │ to calculate lock file checksums locally for the following providers: │ - clo-ru/clo │ - dmacvicar/libvirt │ │ The current .terraform.lock.hcl file only includes checksums for │ linux_amd64, so Terraform running on another platform will fail to install │ these providers. │ │ To calculate additional checksums for another platform, run: │ terraform providers lock -platform=linux_amd64 │ (where linux_amd64 is the platform to generate) ╵ 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. [lgc@localhost lf]$
Да, все это заработало только после создания файла .terraformrc в домашке
[lgc@localhost lf]$ cat ~/.terraformrc
provider_installation {
network_mirror {
url = "https://terraform-mirror.yandexcloud.net/"
include = ["registry.terraform.io/*/*"]
}
network_mirror {
url = "https://nm.tf.org.ru/"
include = ["registry.terraform.io/*/*"]
}
direct {
exclude = ["registry.terraform.io/*/*"]
}
}
[lgc@localhost lf]$Проверочка.
[lgc@localhost lf]$ terraform plan No changes. Your infrastructure matches the configuration. Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed. [lgc@localhost lf]$