You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
terraform-provider-decort/wiki/4.6.2/02.-Пример-работы.md

93 lines
6.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

Данный раздел предназначен для тех, кто хорошо знаком с инструментом Terraform, а также имеет представление об основных понятиях и способах авторизации в облачной платформе DECORT.
Ниже приведён подробно откомментированный пример, показывающий, как создать виртуальный сервер (aka _compute_ на базе системы виртуализации KVM x86) в облачной платформе DECORT с помощью соответствующего Terraform провайдера. Сервер будет создан в новой ресурсной группе, к нему будет подключён один предварительно созданный диск, у сервера будет прямое сетевое подключение во внешнюю сеть.
Идентификатор образа операционной системы, на базе которого должен быть создан виртуальный сервер, считывается из облачной платформы с помощью _data source_ функции `decort_image`.
Далее мы с помощью _resource_ функции `decort_resgroup` создаём новую ресурсную группу, в которую будет помещён этот виртуальный сервер. В качестве альтернативы, для получения информации об уже имеющейся ресурсной группе можно использовать _data source_ функцию с таким же названием.
Затем с помощью _resource_ функции `decort_disk` создаётся диск, который будет подключён к виртуальному серверу в качестве дополнительного. Помимо этого дополнительного диска у сервера будет также и загрузочный диск, на который в процессе создания сервера клонируется выбранный образ операционной системы.
Виртуальный сервер - в данном примере на базе системы виртуализации KVM x86 - создаётся посредством _resource_ функции `decort_kvmvm`.
Только авторизованные в контроллере облачной платформы пользователи могут управлять облачными ресурсами. Подробнее о способах авторизации см. [Обзор облачной платформы DECORT](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.2/03.-Обзор-облачной-платформы-DECORT.md).
```terraform
# 1. Initialize DECORT plugin and connection to DECORT cloud controller
# NOTE: in this example credentials are expected to come from
# DECORT_APP_ID and DECORT_APP_SECRET environmental variables - set them
# in the shell before calling terraform.
# Alternatively you may define plugin parameters app_id and app_secret in
# the TF file, however, this may not be secure if you plan to share this TF
# file with others.
provider "decort" {
authenticator = "decs3o"
controller_url = "<<DECORT_CONTROLLER_URL>>" # specify correct DECORT controller URL, e.g. "https://ds1.digitalenergy.online"
oauth2_url = "<<DECORT_OAUTH2_URL>>" # specify corresponding DECORT OAUTH2 URL, e.g. "https://sso.digitalenergy.online"
app_id = "<<DECORT_APP_ID>>" # application secret to access DECORT cloud API in 'decs3o' and 'bvs' authentication mode, e.g. "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
app_secret = "<<DECORT_APP_SECRET>>" # application ID to access DECORT cloud API in 'decs3o' and 'bvs' authentication mode, e.g. "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
# allow_unverified_ssl = true
}
# 2. Load account to use - new VM will belong to this account
data "decort_account" "my_account" {
account_id = <ACCOUNT_ID> # Specify account ID
}
# 3. Load OS image to use for VM deployment
data "decort_image" "os_image" {
image_id = <OS_IMAGE_ID> # Specify OS image id, e.g. 1234. You can get accessible image id from data source "decort_image_list"
}
# 4. Create new Resource Group in the selected account, new VM will be created in this RG
resource "decort_resgroup" "my_rg" {
name = "NewRgByTF"
account_id = data.decort_account.my_account.account_id
gid = <GRID_ID> # Grid (platform) ID
# if you want to set resource quota on this Resource Group, uncomment
# the following code fragment
# quota {
# cpu = 8 # CPU limit
# ram = 8912 # RAM limit in MB
# disk = 96 # disk volume limit in GB
#}
}
# 5. Create extra disk, which will be attached to the new VM.
# This step is optional - if you do not want extra disks on your VM, skip it
# and comment out extra_disks parameter when creating VM below.
resource "decort_disk" "extra_disk" {
disk_name = "extra-disk-for-vm"
account_id = data.decort_account.my_account.account_id
gid = <GRID_ID> # Grid (platform) ID
size_max = 5 # disk size in GB
type = "D" # disk type, always use "D" for extra disks
sep_id = data.decort_image.os_image.sep_id # use the same SEP ID as the OS image
pool = "<<DATA_POOL_NAME>>" # consult your DECORT platform admin for configured storage pool names
}
# 6. Create virtual machine (a compute of type KVM VM x86 in this example)
# Now that we have all necessary components at hand, we may create a virtual machine.
# This VM will be based on the previsouly obtained OS image, located in the specified
# Resource Group, directly connected to an external network, have a boot disk of
# specified size and one extra disk attached.
resource "decort_kvmvm" "my_new_vm" {
name = "tf-managed-vm"
driver = "KVM_X86" # Compute virtualization driver
rg_id = decort_resgroup.my_rg.id
cpu = 1 # CPU count
ram = 1024 # RAM size in MB, must be even number, ideally a power of 2
boot_disk_size = 10 # Boot disk size in GB
image_id = data.decort_image.os_image.image_id
description = "Test KVM VM Compute managed by Terraform"
extra_disks = [ decort_disk.extra_disk.id ]
network {
net_type = "EXTNET"
net_id = <<EXT_NET_ID>> # specify external network ID to use, consult your DECORT platform admin for correct IDs
# ip_address = "<<SOME VALID AND FREE IP ADDRESS>>" # you may optionally request a specific IP address
}
}
```