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-dynamix/wiki/1.1.0/02.-Пример-работы.md

6.7 KiB

Данный раздел предназначен для тех, кто хорошо знаком с инструментом Terraform, а также имеет представление об основных понятиях и способах авторизации в облачной платформе DYNAMIX.

Ниже приведён подробно откомментированный пример, показывающий, как создать виртуальный сервер (aka compute на базе системы виртуализации KVM x86) в облачной платформе DYNAMIX с помощью соответствующего Terraform провайдера. Сервер будет создан в новой ресурсной группе, к нему будет подключён один предварительно созданный диск, у сервера будет прямое сетевое подключение во внешнюю сеть.

Идентификатор образа операционной системы, на базе которого должен быть создан виртуальный сервер, считывается из облачной платформы с помощью data source функции dynamix_image.

Далее мы с помощью resource функции dynamix_resgroup создаём новую ресурсную группу, в которую будет помещён этот виртуальный сервер. В качестве альтернативы, для получения информации об уже имеющейся ресурсной группе можно использовать data source функцию с таким же названием.

Затем с помощью resource функции dynamix_disk создаётся диск, который будет подключён к виртуальному серверу в качестве дополнительного. Помимо этого дополнительного диска у сервера будет также и загрузочный диск, на который в процессе создания сервера клонируется выбранный образ операционной системы.

Виртуальный сервер - в данном примере на базе системы виртуализации KVM x86 - создаётся посредством resource функции dynamix_kvmvm.

Только авторизованные в контроллере облачной платформы пользователи могут управлять облачными ресурсами. Подробнее о способах авторизации см. Обзор облачной платформы DYNAMIX.

# 1. Initialize DYNAMIX plugin and connection to DYNAMIX cloud controller
# NOTE: in this example credentials are expected to come from 
# DYNAMIX_APP_ID and DYNAMIX_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 "dynamix" {
   authenticator = "decs3o"
   controller_url = "<<DYNAMIX_CONTROLLER_URL>>" # specify correct DYNAMIX controller URL, e.g. "https://ds1.digitalenergy.online"
   oauth2_url = "<<DYNAMIX_OAUTH2_URL>>" # specify corresponding DYNAMIX OAUTH2 URL, e.g. "https://sso.digitalenergy.online"
   app_id = "<<DYNAMIX_APP_ID>>" # application secret to access DYNAMIX cloud API in 'decs3o' and 'bvs' authentication mode, e.g. "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu"
   app_secret = "<<DYNAMIX_APP_SECRET>>" # application ID to access DYNAMIX 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 "dynamix_account" "my_account" {
   account_id = <ACCOUNT_ID> # Specify account ID
}

# 3. Load OS image to use for VM deployment
data "dynamix_image" "os_image" {
  image_id = <OS_IMAGE_ID> # Specify OS image id, e.g. 1234. You can get accessible image id from data source "dynamix_image_list"
}

# 4. Create new Resource Group in the selected account, new VM will be created in this RG
resource "dynamix_resgroup" "my_rg" {
  name = "NewRgByTF"
  account_id = data.dynamix_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 "dynamix_disk" "extra_disk" {
   disk_name = "extra-disk-for-vm"
   account_id = data.dynamix_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.dynamix_image.os_image.sep_id # use the same SEP ID as the OS image
   pool = "<<DATA_POOL_NAME>>" # consult your DYNAMIX 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 "dynamix_kvmvm" "my_new_vm" {
   name = "tf-managed-vm"
   driver = "KVM_X86" # Compute virtualization driver
   rg_id = dynamix_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.dynamix_image.os_image.image_id
   description = "Test KVM VM Compute managed by Terraform"
   extra_disks = [ dynamix_disk.extra_disk.id ]
   
   network {
      net_type = "EXTNET"
      net_id = <<EXT_NET_ID>> # specify external network ID to use, consult your DYNAMIX platform admin for correct IDs
      # ip_address = "<<SOME VALID AND FREE IP ADDRESS>>" # you may optionally request a specific IP address
   }
}