Compare commits

..

2 Commits
4.8.0 ... 4.7.5

Author SHA1 Message Date
7546634d05 4.7.5 2025-07-23 12:15:51 +03:00
d6caa7e214 4.7.4 2025-05-21 14:20:55 +03:00
663 changed files with 34501 additions and 2554 deletions

3
.gitignore vendored
View File

@@ -4,5 +4,4 @@ url_scrapping/
terraform-provider-decort*
.vscode/
.DS_Store
vendor/
.idea/

View File

@@ -1,54 +1,8 @@
## Version 4.8.0
## Version 4.7.5
### Добавлено
#### extnet
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-656 | Вычисляемое поле `account_id` в блоке `reservations` в resource `decort_cb_extnet` и data sources `decort_extnet, decort_cb_extnet` в cloudapi/extnet и cloudbroker/extnet |
| BATF-658 | Data sources `decort_extnet_reserved_ip_list, decort_cb_extnet_reserved_ip_list` в cloudapi/extnet и cloudbroker/extnet |
| BATF-658 | Опциональный блок `reserved_ip`в resource `decort_cb_extnet` в cloudbroker/extnet |
#### image
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-667 | Вычисляемое поле `snapshot_id` в resources `decort_cb_image, decort_cb_image_from_blank_compute, decort_cb_image_from_platform_disk, decort_cb_virtual_image, decort_cb_cdrom_image` и data sources `decort_cb_image, decort_cb_image_list` в cloudbroker/image |
#### grid
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-669 | Обязательно поле `file_path` в data source `decort_cb_grid_post_diagnosis` в cloudbroker/grid |
### Исправлено
#### kvmvm
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-656 | Вычисляемое поле `vnc_password` в resources `decort_kvmvm, decort_cb_kvmvm` и data sources `decort_kvmvm, decort_cb_kvmvm` в cloudapi/kvmvm и cloudbroker/kvmvm |
| BATF-656 | Опциональное поле `cd_image_id`в data_source `decort_cb_kvmvm_list` в cloudbroker/kvmvm |
| BATF-666 | Опциональное поле `auto_start_w_node`в resources `decort_kvmvm, decort_cb_kvmvm` в cloudapi/kvmvm и cloudbroker/kvmvm |
| BATF-666 | Вычисляемое поле `auto_start_w_node`в data_sources `decort_kvmvm, decort_kvmvm_list, decort_kvmvm_list_deleted, decort_cb_kvmvm, decort_cb_kvmvm_list, decort_cb_kvmvm_list_deleted ` в cloudapi/kvmvm и cloudbroker/kvmvm |
#### node
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-663 | Вычисляемый блок `net_addr` в data source `decort_cb_node` в cloudbroker/node |
#### vins
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-656 | Вычисляемое поле `vnc_password` в блоке `vnf_dev` в resources `decort_vins, decort_cb_vins` и data sources `decort_vins, decort_cb_vins` в cloudapi/vins и cloudbroker/vins |
| BATF-656 | Вычисляемое поле `account_id` в блоке `reservations` в resource `decort_vins` и data source `decort_vins` в cloudapi/vins |
### Удалено
#### grid
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-669 | Data source `decort_cb_grid_post_diagnosis` в cloudbroker/grid |
| BATF-669 | Вычисляемое поле `diagnosis` в data source `decort_cb_grid_get_diagnosis` в cloudbroker/grid |
#### vins
| Идентификатор<br>задачи | Описание |
| --- | --- |
| BATF-656 | Вычисляемые поля `client_type, description, domain_name, hostname` в блоке `reservations` в resources `decort_vins, decort_cb_vins` и data sources `decort_vins, decort_cb_vins` в cloudapi/vins и cloudbroker/vins |
| BATF-656 | Опциональное поле `compute_ids` в resources `decort_vins_static_route, decort_cb_vins_static_route` в cloudapi/vins и cloudbroker/vins |
| BATF-1008 | Баг при изменении полей `ram` и `cpu` в resources `decort_kvmvm` и `decort_cb_kvmvm` в cloudapi/kvmvm и в cloudbroker/kvmvm |

View File

@@ -7,7 +7,7 @@ ZIPDIR = ./zip
BINARY=${NAME}
WORKPATH= ./examples/terraform.d/plugins/${HOSTNAME}/${NAMESPACE}/${NAMESPACE}/${VERSION}/${OS_ARCH}
MAINPATH = ./cmd/decort/
VERSION=4.8.0
VERSION=4.7.5
OS_ARCH=$(shell go env GOHOSTOS)_$(shell go env GOHOSTARCH)
FILES = ${BINARY}_${VERSION}_darwin_amd64\

View File

@@ -6,7 +6,6 @@ Terraform provider для платформы Digital Energy Cloud Orchestration
| Версия DECORT API | Версия провайдера Terraform |
| ------ | ------ |
| 4.2.0 | 4.8.x |
| 4.1.0 | 4.7.x |
| 4.0.0 | 4.6.x |
| 3.8.9 | 4.5.x |

View File

@@ -93,7 +93,6 @@ Read-Only:
Read-Only:
- `account_id` (Number)
- `client_type` (String)
- `desc` (String)
- `domain_name` (String)

View File

@@ -1,61 +0,0 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "decort_cb_extnet_reserved_ip_list Data Source - terraform-provider-decort"
subcategory: ""
description: |-
---
# decort_cb_extnet_reserved_ip_list (Data Source)
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `account_id` (Number)
### Optional
- `extnet_id` (Number)
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
### Read-Only
- `id` (String) The ID of this resource.
- `items` (List of Object) (see [below for nested schema](#nestedatt--items))
<a id="nestedblock--timeouts"></a>
### Nested Schema for `timeouts`
Optional:
- `default` (String)
- `read` (String)
<a id="nestedatt--items"></a>
### Nested Schema for `items`
Read-Only:
- `extnet_id` (Number)
- `reservations` (List of Object) (see [below for nested schema](#nestedobjatt--items--reservations))
<a id="nestedobjatt--items--reservations"></a>
### Nested Schema for `items.reservations`
Read-Only:
- `account_id` (Number)
- `client_type` (String)
- `domain_name` (String)
- `hostname` (String)
- `ip` (String)
- `mac` (String)
- `type` (String)
- `vm_id` (Number)

View File

@@ -17,7 +17,6 @@ description: |-
### Required
- `file_path` (String)
- `gid` (Number)
### Optional
@@ -26,6 +25,7 @@ description: |-
### Read-Only
- `diagnosis` (String)
- `id` (String) The ID of this resource.
<a id="nestedblock--timeouts"></a>

View File

@@ -0,0 +1,37 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "decort_cb_grid_post_diagnosis Data Source - terraform-provider-decort"
subcategory: ""
description: |-
---
# decort_cb_grid_post_diagnosis (Data Source)
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `gid` (Number)
### Optional
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
### Read-Only
- `diagnosis` (String)
- `id` (String) The ID of this resource.
<a id="nestedblock--timeouts"></a>
### Nested Schema for `timeouts`
Optional:
- `default` (String)
- `read` (String)

View File

@@ -59,7 +59,6 @@ description: |-
- `rescuecd` (Boolean)
- `sep_id` (Number) storage endpoint provider ID
- `size` (Number) image size
- `snapshot_id` (String) snapshot id
- `status` (String) status
- `tech_status` (String) tech atatus
- `unc_path` (String) unc path

View File

@@ -89,7 +89,6 @@ Read-Only:
- `sep_id` (Number)
- `shared_with` (List of Number)
- `size` (Number)
- `snapshot_id` (String)
- `status` (String)
- `tech_status` (String)
- `unc_path` (String)

View File

@@ -33,7 +33,6 @@ description: |-
- `affinity_weight` (Number)
- `anti_affinity_rules` (List of Object) (see [below for nested schema](#nestedatt--anti_affinity_rules))
- `arch` (String)
- `auto_start_w_node` (Boolean)
- `boot_disk_id` (Number)
- `boot_disk_size` (Number)
- `boot_order` (List of String)
@@ -98,10 +97,9 @@ description: |-
- `updated_time` (Number)
- `user_data` (String)
- `user_managed` (Boolean)
- `vgpus` (List of Number)
- `vgpus` (List of Object) (see [below for nested schema](#nestedatt--vgpus))
- `virtual_image_id` (Number)
- `virtual_image_name` (String)
- `vnc_password` (String)
<a id="nestedblock--timeouts"></a>
### Nested Schema for `timeouts`
@@ -331,3 +329,29 @@ Read-Only:
- `key` (String)
- `val` (String)
<a id="nestedatt--vgpus"></a>
### Nested Schema for `vgpus`
Read-Only:
- `account_id` (Number)
- `bus_number` (Number)
- `created_time` (Number)
- `deleted_time` (Number)
- `gid` (Number)
- `guid` (Number)
- `id` (Number)
- `last_claimed_by` (Number)
- `last_update_time` (Number)
- `mode` (String)
- `pci_slot` (Number)
- `pgpuid` (Number)
- `profile_id` (Number)
- `ram` (Number)
- `reference_id` (String)
- `rg_id` (Number)
- `status` (String)
- `type` (String)
- `vmid` (Number)

View File

@@ -19,7 +19,6 @@ description: |-
- `account_id` (Number) Find by AccountID
- `by_id` (Number) Find by ID
- `cd_image_id` (Number) Find by CD image ID
- `extnet_id` (Number) Find by Extnet ID
- `extnet_name` (String) Find by Extnet name
- `ignore_k8s` (Boolean) If set to true, ignores any VMs associated with any k8s cluster
@@ -65,7 +64,6 @@ Read-Only:
- `affinity_weight` (Number)
- `anti_affinity_rules` (List of Object) (see [below for nested schema](#nestedobjatt--items--anti_affinity_rules))
- `arch` (String)
- `auto_start_w_node` (Boolean)
- `boot_order` (List of String)
- `bootdisk_size` (Number)
- `cd_image_id` (Number)
@@ -120,7 +118,7 @@ Read-Only:
- `updated_time` (Number)
- `user_data` (String)
- `user_managed` (Boolean)
- `vgpus` (List of Number)
- `vgpus` (List of Object) (see [below for nested schema](#nestedobjatt--items--vgpus))
- `vins_connected` (Number)
- `virtual_image_id` (Number)
@@ -256,3 +254,29 @@ Read-Only:
- `key` (String)
- `val` (String)
<a id="nestedobjatt--items--vgpus"></a>
### Nested Schema for `items.vgpus`
Read-Only:
- `account_id` (Number)
- `bus_number` (Number)
- `created_time` (Number)
- `deleted_time` (Number)
- `gid` (Number)
- `guid` (Number)
- `id` (Number)
- `last_claimed_by` (Number)
- `last_update_time` (Number)
- `mode` (String)
- `pci_slot` (Number)
- `pgpuid` (Number)
- `profile_id` (Number)
- `ram` (Number)
- `reference_id` (String)
- `rg_id` (Number)
- `status` (String)
- `type` (String)
- `vmid` (Number)

View File

@@ -60,7 +60,6 @@ Read-Only:
- `affinity_weight` (Number)
- `anti_affinity_rules` (List of Object) (see [below for nested schema](#nestedobjatt--items--anti_affinity_rules))
- `arch` (String)
- `auto_start_w_node` (Boolean)
- `boot_order` (List of String)
- `bootdisk_size` (Number)
- `cd_image_id` (Number)

View File

@@ -34,7 +34,6 @@ description: |-
- `isolated_cpus` (List of String)
- `name` (String)
- `need_reboot` (Boolean)
- `net_addr` (List of Object) (see [below for nested schema](#nestedatt--net_addr))
- `nic_info` (List of Object) (see [below for nested schema](#nestedatt--nic_info))
- `numa_topology` (List of Object) (see [below for nested schema](#nestedatt--numa_topology))
- `reserved_cpus` (List of String)
@@ -110,15 +109,6 @@ Read-Only:
- `phys_count` (Number)
<a id="nestedatt--net_addr"></a>
### Nested Schema for `net_addr`
Read-Only:
- `ip` (List of String)
- `name` (String)
<a id="nestedatt--nic_info"></a>
### Nested Schema for `nic_info`

View File

@@ -101,7 +101,6 @@ Read-Only:
- `tech_status` (String)
- `type` (String)
- `vins` (List of Number)
- `vnc_password` (String)
<a id="nestedobjatt--vnf_dev--config"></a>
### Nested Schema for `vnf_dev.config`

View File

@@ -90,7 +90,6 @@ Read-Only:
Read-Only:
- `account_id` (Number)
- `client_type` (String)
- `desc` (String)
- `domainname` (String)

View File

@@ -1,61 +0,0 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "decort_extnet_reserved_ip_list Data Source - terraform-provider-decort"
subcategory: ""
description: |-
---
# decort_extnet_reserved_ip_list (Data Source)
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `account_id` (Number)
### Optional
- `extnet_id` (Number)
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
### Read-Only
- `id` (String) The ID of this resource.
- `items` (List of Object) (see [below for nested schema](#nestedatt--items))
<a id="nestedblock--timeouts"></a>
### Nested Schema for `timeouts`
Optional:
- `default` (String)
- `read` (String)
<a id="nestedatt--items"></a>
### Nested Schema for `items`
Read-Only:
- `extnet_id` (Number)
- `reservations` (List of Object) (see [below for nested schema](#nestedobjatt--items--reservations))
<a id="nestedobjatt--items--reservations"></a>
### Nested Schema for `items.reservations`
Read-Only:
- `account_id` (Number)
- `client_type` (String)
- `domain_name` (String)
- `hostname` (String)
- `ip` (String)
- `mac` (String)
- `type` (String)
- `vm_id` (Number)

View File

@@ -33,7 +33,6 @@ description: |-
- `affinity_weight` (Number)
- `anti_affinity_rules` (List of Object) (see [below for nested schema](#nestedatt--anti_affinity_rules))
- `arch` (String)
- `auto_start_w_node` (Boolean)
- `boot_order` (List of String)
- `bootdisk_size` (Number)
- `cd_image_id` (Number)
@@ -92,10 +91,9 @@ description: |-
- `updated_time` (Number)
- `user_managed` (Boolean)
- `userdata` (String)
- `vgpus` (List of Number)
- `vgpus` (List of Object) (see [below for nested schema](#nestedatt--vgpus))
- `virtual_image_id` (Number)
- `virtual_image_name` (String)
- `vnc_password` (String)
<a id="nestedblock--timeouts"></a>
### Nested Schema for `timeouts`
@@ -351,3 +349,28 @@ Read-Only:
- `guid` (String)
- `label` (String)
- `timestamp` (Number)
<a id="nestedatt--vgpus"></a>
### Nested Schema for `vgpus`
Read-Only:
- `account_id` (Number)
- `created_time` (Number)
- `deleted_time` (Number)
- `gid` (Number)
- `guid` (Number)
- `id` (Number)
- `last_claimed_by` (Number)
- `last_update_time` (Number)
- `mode` (String)
- `pci_slot` (Number)
- `pgpuid` (Number)
- `profile_id` (Number)
- `ram` (Number)
- `reference_id` (String)
- `rg_id` (Number)
- `status` (String)
- `type` (String)
- `vmid` (Number)

View File

@@ -62,7 +62,6 @@ Read-Only:
- `affinity_weight` (Number)
- `anti_affinity_rules` (List of Object) (see [below for nested schema](#nestedobjatt--items--anti_affinity_rules))
- `arch` (String)
- `auto_start_w_node` (Boolean)
- `boot_order` (List of String)
- `bootdisk_size` (Number)
- `cd_image_id` (Number)

View File

@@ -60,7 +60,6 @@ Read-Only:
- `affinity_weight` (Number)
- `anti_affinity_rules` (List of Object) (see [below for nested schema](#nestedobjatt--items--anti_affinity_rules))
- `arch` (String)
- `auto_start_w_node` (Boolean)
- `boot_order` (List of String)
- `bootdisk_size` (Number)
- `cd_image_id` (Number)

View File

@@ -108,7 +108,6 @@ Read-Only:
- `tech_status` (String)
- `type` (String)
- `vins` (List of Number)
- `vnc_password` (String)
- `vnf_id` (Number)
- `vnf_name` (String)
@@ -249,7 +248,10 @@ Read-Only:
Read-Only:
- `account_id` (Number)
- `client_type` (String)
- `desc` (String)
- `domainname` (String)
- `hostname` (String)
- `ip` (String)
- `mac` (String)
- `type` (String)

View File

@@ -62,7 +62,6 @@ description: |-
- `res_name` (String)
- `rescuecd` (Boolean)
- `size` (Number) image size
- `snapshot_id` (String) snapshot id
- `status` (String) status
- `tech_status` (String) tech atatus
- `unc_path` (String) unc path

View File

@@ -37,7 +37,6 @@ description: |-
- `ntp` (List of String) List of NTP addresses
- `ovs_bridge` (String) OpenvSwith bridge name for ExtNet connection
- `pre_reservations_num` (Number) Number of pre created reservations
- `reserved_ip` (Block Set) (see [below for nested schema](#nestedblock--reserved_ip))
- `restart` (Boolean) restart extnet vnf device
- `set_default` (Boolean) Set current extnet as default (can not be undone)
- `shared_with` (Set of Number)
@@ -89,19 +88,6 @@ Required:
- `ip_start` (String)
<a id="nestedblock--reserved_ip"></a>
### Nested Schema for `reserved_ip`
Required:
- `account_id` (Number)
Optional:
- `ip_count` (Number)
- `ips` (Set of String)
<a id="nestedblock--timeouts"></a>
### Nested Schema for `timeouts`
@@ -133,7 +119,6 @@ Read-Only:
Read-Only:
- `account_id` (Number)
- `client_type` (String)
- `desc` (String)
- `domain_name` (String)

View File

@@ -67,7 +67,6 @@ description: |-
- `res_name` (String)
- `rescuecd` (Boolean)
- `size` (Number) image size
- `snapshot_id` (String) snapshot id
- `status` (String) status
- `tech_status` (String) tech atatus
- `unc_path` (String) unc path

View File

@@ -64,7 +64,6 @@ description: |-
- `res_name` (String)
- `rescuecd` (Boolean)
- `size` (Number)
- `snapshot_id` (String) snapshot id
- `status` (String)
- `tech_status` (String)
- `unc_path` (String)

View File

@@ -64,7 +64,6 @@ description: |-
- `res_name` (String)
- `rescuecd` (Boolean)
- `size` (Number)
- `snapshot_id` (String) snapshot id
- `status` (String)
- `tech_status` (String)
- `unc_path` (String)

View File

@@ -30,7 +30,6 @@ description: |-
- `alt_boot_id` (Number) ID of CD-ROM live image to boot
- `anti_affinity_rules` (Block List) (see [below for nested schema](#nestedblock--anti_affinity_rules))
- `auto_start` (Boolean) Flag for redeploy compute
- `auto_start_w_node` (Boolean)
- `boot_disk_size` (Number) This compute instance boot disk size in GB. Make sure it is large enough to accomodate selected OS image.
- `cd` (Block Set, Max: 1) (see [below for nested schema](#nestedblock--cd))
- `chipset` (String) Type of the emulated system.
@@ -129,7 +128,6 @@ description: |-
- `vgpus` (List of Number)
- `virtual_image_id` (Number)
- `virtual_image_name` (String)
- `vnc_password` (String)
<a id="nestedblock--affinity_rules"></a>
### Nested Schema for `affinity_rules`

View File

@@ -167,7 +167,6 @@ Read-Only:
- `tech_status` (String)
- `type` (String)
- `vins` (List of Number)
- `vnc_password` (String)
<a id="nestedobjatt--vnf_dev--config"></a>
### Nested Schema for `vnf_dev.config`

View File

@@ -24,11 +24,11 @@ description: |-
### Optional
- `compute_ids` (List of Number)
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
### Read-Only
- `compute_ids` (List of Number)
- `guid` (String)
- `id` (String) The ID of this resource.
- `route_id` (Number) Unique ID of the static route

View File

@@ -61,7 +61,6 @@ description: |-
- `rescuecd` (Boolean)
- `sep_id` (Number) storage endpoint provider ID
- `size` (Number) image size
- `snapshot_id` (String) snapshot id
- `status` (String) status
- `tech_status` (String) tech atatus
- `unc_path` (String) unc path

View File

@@ -29,7 +29,6 @@ description: |-
- `affinity_rules` (Block List) (see [below for nested schema](#nestedblock--affinity_rules))
- `anti_affinity_rules` (Block List) (see [below for nested schema](#nestedblock--anti_affinity_rules))
- `auto_start` (Boolean) Flag for redeploy compute
- `auto_start_w_node` (Boolean) Flag for start compute after node exits from MAINTENANCE state
- `boot_disk_size` (Number) This compute instance boot disk size in GB. Make sure it is large enough to accomodate selected OS image.
- `cd` (Block Set, Max: 1) (see [below for nested schema](#nestedblock--cd))
- `chipset` (String) Type of the emulated system.
@@ -119,10 +118,9 @@ description: |-
- `updated_by` (String)
- `updated_time` (Number)
- `user_managed` (Boolean)
- `vgpus` (List of Number)
- `vgpus` (List of Object) (see [below for nested schema](#nestedatt--vgpus))
- `virtual_image_id` (Number)
- `virtual_image_name` (String)
- `vnc_password` (String)
<a id="nestedblock--affinity_rules"></a>
### Nested Schema for `affinity_rules`
@@ -359,3 +357,29 @@ Read-Only:
- `guid` (String)
- `label` (String)
- `timestamp` (Number)
<a id="nestedatt--vgpus"></a>
### Nested Schema for `vgpus`
Read-Only:
- `account_id` (Number)
- `bus_number` (Number)
- `created_time` (Number)
- `deleted_time` (Number)
- `gid` (Number)
- `guid` (Number)
- `id` (Number)
- `last_claimed_by` (Number)
- `last_update_time` (Number)
- `mode` (String)
- `pci_slot` (Number)
- `pgpuid` (Number)
- `profile_id` (Number)
- `ram` (Number)
- `reference_id` (String)
- `rg_id` (Number)
- `status` (String)
- `type` (String)
- `vmid` (Number)

View File

@@ -163,7 +163,6 @@ Read-Only:
- `tech_status` (String)
- `type` (String)
- `vins` (List of Number)
- `vnc_password` (String)
- `vnf_id` (Number)
- `vnf_name` (String)
@@ -304,7 +303,10 @@ Read-Only:
Read-Only:
- `account_id` (Number)
- `client_type` (String)
- `desc` (String)
- `domainname` (String)
- `hostname` (String)
- `ip` (String)
- `mac` (String)
- `type` (String)

View File

@@ -24,12 +24,12 @@ description: |-
### Optional
- `compute_ids` (List of Number)
- `route_id` (Number)
- `timeouts` (Block, Optional) (see [below for nested schema](#nestedblock--timeouts))
### Read-Only
- `compute_ids` (List of Number)
- `guid` (String)
- `id` (String) The ID of this resource.

2
go.mod
View File

@@ -8,7 +8,7 @@ require (
github.com/hashicorp/terraform-plugin-sdk/v2 v2.33.0
github.com/sirupsen/logrus v1.9.0
golang.org/x/net v0.23.0
repository.basistech.ru/BASIS/decort-golang-sdk v1.10.0
repository.basistech.ru/BASIS/decort-golang-sdk v1.9.4
)
require (

4
go.sum
View File

@@ -273,5 +273,5 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
repository.basistech.ru/BASIS/decort-golang-sdk v1.9.2 h1:MPH1tMQrDN1Gri4FrQP3cx60uR3uZioEDb707D88/7c=
repository.basistech.ru/BASIS/decort-golang-sdk v1.9.2/go.mod h1:OaUynHHuSjWMzpfyoL4au6oLcUogqUkPPBKA15pbHWo=
repository.basistech.ru/BASIS/decort-golang-sdk v1.9.4 h1:BQ7Q6whTFTmBiBcvdRI6bXmYLkhekvJDiNpW258+j24=
repository.basistech.ru/BASIS/decort-golang-sdk v1.9.4/go.mod h1:OaUynHHuSjWMzpfyoL4au6oLcUogqUkPPBKA15pbHWo=

View File

@@ -137,7 +137,6 @@ func newDataSourcesMap() map[string]*schema.Resource {
"decort_extnet_computes_list": extnet.DataSourceExtnetComputesList(),
"decort_extnet": extnet.DataSourceExtnet(),
"decort_extnet_default": extnet.DataSourceExtnetDefault(),
"decort_extnet_reserved_ip_list": extnet.DataSourceExtnetReservedIp(),
"decort_locations_list": locations.DataSourceLocationsList(),
"decort_location_url": locations.DataSourceLocationUrl(),
"decort_image_list": image.DataSourceImageList(),
@@ -181,7 +180,6 @@ func newDataSourcesMap() map[string]*schema.Resource {
"decort_cb_extnet": cb_extnet.DataSourceExtnetCB(),
"decort_cb_extnet_list": cb_extnet.DataSourceExtnetListCB(),
"decort_cb_extnet_default": cb_extnet.DataSourceExtnetDefaultCB(),
"decort_cb_extnet_reserved_ip_list": cb_extnet.DataSourceExtnetReservedIp(),
"decort_cb_extnet_static_route_list": cb_extnet.DataSourceStaticRouteList(),
"decort_cb_extnet_static_route": cb_extnet.DataSourceStaticRoute(),
"decort_cb_image": cb_image.DataSourceImage(),
@@ -189,6 +187,7 @@ func newDataSourcesMap() map[string]*schema.Resource {
"decort_cb_grid_get_status": cb_grid.DataSourceGridGetStatus(),
"decort_cb_grid_post_status": cb_grid.DataSourceGridPostStatus(),
"decort_cb_grid_get_diagnosis": cb_grid.DataSourceGridGetDiagnosis(),
"decort_cb_grid_post_diagnosis": cb_grid.DataSourceGridPostDiagnosis(),
"decort_cb_grid_get_settings": cb_grid.DataSourceGridGetSettings(),
"decort_cb_grid_list": cb_grid.DataSourceGridList(),
"decort_cb_grid_list_emails": cb_grid.DataSourceGridListEmails(),

View File

@@ -204,10 +204,6 @@ func dataSourceExtnetSchemaMake() map[string]*schema.Schema {
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"client_type": {
Type: schema.TypeString,
Computed: true,

View File

@@ -1,137 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
Tim Tkachev, <tvtkachev@basistech.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.
Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package extnet
import (
"context"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func dataSourceExtnetReservedIpRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
reservedList, err := utilityExtnetReservedIpCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
id := uuid.New()
d.SetId(id.String())
d.Set("items", flattenExtnetReservedIp(reservedList))
return nil
}
func dataSourceExtnetReservedIpSchemaMake() map[string]*schema.Schema {
res := map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Required: true,
},
"extnet_id": {
Type: schema.TypeInt,
Optional: true,
},
"items": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"extnet_id": {
Type: schema.TypeInt,
Computed: true,
},
"reservations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"client_type": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"hostname": {
Type: schema.TypeString,
Computed: true,
},
"ip": {
Type: schema.TypeString,
Computed: true,
},
"mac": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"vm_id": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
},
},
}
return res
}
func DataSourceExtnetReservedIp() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
ReadContext: dataSourceExtnetReservedIpRead,
Timeouts: &schema.ResourceTimeout{
Read: &constants.Timeout30s,
Default: &constants.Timeout60s,
},
Schema: dataSourceExtnetReservedIpSchemaMake(),
}
}

View File

@@ -54,7 +54,6 @@ func flattenExtnetReservations(ers extnet.ListReservations) []map[string]interfa
res := make([]map[string]interface{}, 0, len(ers))
for _, er := range ers {
temp := map[string]interface{}{
"account_id": er.AccountID,
"client_type": er.ClientType,
"domainname": er.DomainName,
"hostname": er.Hostname,
@@ -136,29 +135,3 @@ func flattenExtnetList(el *extnet.ListExtNets) []map[string]interface{} {
}
return res
}
func flattenExtnetReservedIp(el []extnet.RecordReservedIP) []map[string]interface{} {
res := make([]map[string]interface{}, 0, len(el))
for _, e := range el {
reservations := make([]map[string]interface{}, 0, len(e.Reservations))
for _, r := range e.Reservations {
temp := map[string]interface{}{
"account_id": r.AccountID,
"client_type": r.ClientType,
"domain_name": r.DomainName,
"hostname": r.Hostname,
"ip": r.IP,
"mac": r.Mac,
"type": r.Type,
"vm_id": r.VMID,
}
reservations = append(reservations, temp)
}
item := map[string]interface{}{
"extnet_id": e.ExtnetID,
"reservations": reservations,
}
res = append(res, item)
}
return res
}

View File

@@ -1,61 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.
Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package extnet
import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func utilityExtnetReservedIpCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) ([]extnet.RecordReservedIP, error) {
c := m.(*controller.ControllerCfg)
req := extnet.GetReservedIP{
AccountID: uint64(d.Get("account_id").(int)),
}
if extNetID, ok := d.GetOk("extnet_id"); ok {
req.ExtNetID = uint64(extNetID.(int))
}
log.Debugf("utilityExtnetReservedIpCheckPresence")
res, err := c.CloudAPI().ExtNet().GetReservedIP(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}

View File

@@ -703,10 +703,6 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"auto_start_w_node": {
Type: schema.TypeBool,
Computed: true,
},
"chipset": {
Type: schema.TypeString,
Computed: true,
@@ -954,15 +950,84 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"vnc_password": {
Type: schema.TypeString,
Computed: true,
},
"vgpus": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"gid": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"profile_id": {
Type: schema.TypeInt,
Computed: true,
},
"ram": {
Type: schema.TypeInt,
Computed: true,
},
"last_update_time": {
Type: schema.TypeInt,
Computed: true,
},
"created_time": {
Type: schema.TypeInt,
Computed: true,
},
"deleted_time": {
Type: schema.TypeInt,
Computed: true,
},
"vmid": {
Type: schema.TypeInt,
Computed: true,
},
"pgpuid": {
Type: schema.TypeInt,
Computed: true,
},
"reference_id": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"rg_id": {
Type: schema.TypeInt,
Computed: true,
},
"last_claimed_by": {
Type: schema.TypeInt,
Computed: true,
},
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
},
"guid": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"virtual_image_id": {

View File

@@ -121,10 +121,6 @@ func itemComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"auto_start_w_node": {
Type: schema.TypeBool,
Computed: true,
},
"boot_order": {
Type: schema.TypeList,
Computed: true,

View File

@@ -183,7 +183,6 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{}
"affinity_weight": compute.AffinityWeight,
"anti_affinity_rules": flattenListRules(compute.AntiAffinityRules),
"arch": compute.Architecture,
"auto_start_w_node": compute.AutoStart,
"boot_order": compute.BootOrder,
"bootdisk_size": compute.BootDiskSize,
"chipset": compute.Chipset,
@@ -363,7 +362,6 @@ func flattenCompute(d *schema.ResourceData, computeRec compute.RecordCompute, pc
d.Set("account_name", computeRec.AccountName)
d.Set("affinity_weight", computeRec.AffinityWeight)
d.Set("arch", computeRec.Architecture)
d.Set("auto_start_w_node", computeRec.AutoStart)
d.Set("boot_order", computeRec.BootOrder)
// we intentionally use the SizeMax field, do not change it until the BootDiskSize field is fixed on the platform
d.Set("boot_disk_size", bootDisk.SizeMax)
@@ -431,8 +429,7 @@ func flattenCompute(d *schema.ResourceData, computeRec compute.RecordCompute, pc
d.Set("updated_by", computeRec.UpdatedBy)
d.Set("updated_time", computeRec.UpdatedTime)
d.Set("user_managed", computeRec.UserManaged)
d.Set("vnc_password", computeRec.VNCPassword)
d.Set("vgpus", computeRec.VGPUs)
d.Set("vgpus", flattenVGPUs(computeRec.VGPUs))
d.Set("virtual_image_id", computeRec.VirtualImageID)
d.Set("virtual_image_name", computeRec.VirtualImageName)
@@ -616,7 +613,6 @@ func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute
d.Set("affinity_rules", flattenAffinityRules(computeRec.AffinityRules))
d.Set("affinity_weight", computeRec.AffinityWeight)
d.Set("anti_affinity_rules", flattenListRules(computeRec.AntiAffinityRules))
d.Set("auto_start_w_node", computeRec.AutoStart)
d.Set("arch", computeRec.Architecture)
d.Set("chipset", computeRec.Chipset)
d.Set("boot_order", computeRec.BootOrder)
@@ -676,8 +672,7 @@ func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute
d.Set("updated_time", computeRec.UpdatedTime)
d.Set("user_managed", computeRec.UserManaged)
d.Set("userdata", string(userdata))
d.Set("vnc_password", computeRec.VNCPassword)
d.Set("vgpus", computeRec.VGPUs)
d.Set("vgpus", flattenVGPUs(computeRec.VGPUs))
d.Set("virtual_image_id", computeRec.VirtualImageID)
d.Set("virtual_image_name", computeRec.VirtualImageName)
d.Set("pci_devices", flattenPCI(*pciList))
@@ -818,3 +813,33 @@ func flattenPCIDevice(deviceList []compute.ItemPCIDevice) []map[string]interface
}
return res
}
func flattenVGPUs(vgpus []compute.ItemVGPU) []map[string]interface{} {
res := make([]map[string]interface{}, len(vgpus))
for i, vgpu := range vgpus {
res[i] = map[string]interface{}{
"id": int(vgpu.ID),
"gid": int(vgpu.GID),
"type": vgpu.Type,
"mode": vgpu.Mode,
"status": vgpu.Status,
"profile_id": vgpu.ProfileID,
"ram": int(vgpu.RAM),
"last_update_time": int(vgpu.LastUpdateTime),
"created_time": int(vgpu.CreatedTime),
"deleted_time": int(vgpu.DeletedTime),
"vmid": int(vgpu.VMID),
"pgpuid": int(vgpu.PGPUID),
"reference_id": vgpu.ReferenceID,
"account_id": int(vgpu.AccountID),
"rg_id": int(vgpu.RGID),
"last_claimed_by": int(vgpu.LastClaimedBy),
"pci_slot": int(vgpu.PCISlot),
"guid": int(vgpu.GUID),
}
}
return res
}

View File

@@ -491,26 +491,12 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf
req := compute.PinToStackRequest{
ComputeID: computeId,
}
req.AutoStart = d.Get("auto_start_w_node").(bool)
_, err := c.CloudAPI().Compute().PinToStack(ctx, req)
if err != nil {
warnings.Add(err)
}
}
if !d.Get("pin_to_stack").(bool) && d.Get("auto_start_w_node").(bool) {
req := compute.UpdateRequest{
ComputeID: computeId,
AutoStart: d.Get("auto_start_w_node").(bool),
CPUPin: d.Get("cpu_pin").(bool),
HPBacked: d.Get("hp_backed").(bool),
}
_, err := c.CloudAPI().Compute().Update(ctx, req)
if err != nil {
warnings.Add(err)
}
}
if d.Get("pause").(bool) {
req := compute.PauseRequest{
ComputeID: computeId,
@@ -633,7 +619,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
if !hasRG {
return diag.Errorf("resourceComputeUpdate: can't update Compute because rgID %d not allowed or does not exist", d.Get("rg_id").(int))
return diag.Errorf("resourceComputeUpdate: can't update Compute bacause rgID %d not allowed or does not exist", d.Get("rg_id").(int))
}
hasImage, err := existImageId(ctx, d, m)
@@ -642,7 +628,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
if !hasImage {
return diag.Errorf("resourceComputeUpdate: can't update Compute because imageID %d not allowed or does not exist", d.Get("image_id").(int))
return diag.Errorf("resourceComputeUpdate: can't update Compute bacause imageID %d not allowed or does not exist", d.Get("image_id").(int))
}
if disks, ok := d.GetOk("disks"); ok {
@@ -776,64 +762,8 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
log.Debugf("resourceComputeUpdate: enable=%s Compute ID %v after completing its resource configuration", d.Id(), enabled)
}
if d.HasChange("started") {
start := d.Get("started").(bool)
if start {
req := compute.StartRequest{ComputeID: computeRec.ID}
if _, err := c.CloudAPI().Compute().Start(ctx, req); err != nil {
return diag.FromErr(err)
}
}
if !start {
req := compute.StopRequest{ComputeID: computeRec.ID}
if _, err := c.CloudAPI().Compute().Stop(ctx, req); err != nil {
return diag.FromErr(err)
}
}
}
doUpdate := false
resizeReq := compute.ResizeRequest{
ComputeID: computeRec.ID,
}
forceResize, ok := d.GetOk("force_resize")
if ok {
resizeReq.Force = forceResize.(bool)
}
warnings := dc.Warnings{}
oldCpu, newCpu := d.GetChange("cpu")
if oldCpu.(int) > newCpu.(int) && !forceResize.(bool) {
return diag.Errorf("Cannot resize compute ID %d: enable 'force_resize' to reduce compute vCPUs", computeRec.ID)
}
if oldCpu.(int) != newCpu.(int) {
resizeReq.CPU = uint64(newCpu.(int))
doUpdate = true
} else {
resizeReq.CPU = 0
}
oldRam, newRam := d.GetChange("ram")
if oldRam.(int) != newRam.(int) {
resizeReq.RAM = uint64(newRam.(int))
doUpdate = true
} else {
resizeReq.RAM = 0
}
if doUpdate {
log.Debugf("resourceComputeUpdate: changing CPU %d -> %d and/or RAM %d -> %d",
oldCpu.(int), newCpu.(int),
oldRam.(int), newRam.(int))
_, err := c.CloudAPI().Compute().Resize(ctx, resizeReq)
if err != nil {
return diag.FromErr(err)
}
}
oldSize, newSize := d.GetChange("boot_disk_size")
if oldSize.(int) < newSize.(int) {
req := compute.DiskResizeRequest{ComputeID: computeRec.ID}
@@ -876,7 +806,58 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
}
if d.HasChanges("description", "name", "numa_affinity", "cpu_pin", "hp_backed", "chipset", "auto_start_w_node") {
// Note bene: numa_affinity, cpu_pin, "ram", "cpu" and hp_backed are not allowed to be changed for compute in STARTED tech status.
// If STARTED, we need to stop it before update
var isStopRequired bool
if d.HasChanges("numa_affinity", "cpu_pin", "hp_backed", "ram", "cpu") && d.Get("started").(bool) {
isStopRequired = true
}
if isStopRequired {
if _, err := c.CloudAPI().Compute().Stop(ctx, compute.StopRequest{ComputeID: computeRec.ID}); err != nil {
return diag.FromErr(err)
}
}
// resize
doUpdate := false
resizeReq := compute.ResizeRequest{
ComputeID: computeRec.ID,
}
forceResize, ok := d.GetOk("force_resize")
if ok {
resizeReq.Force = forceResize.(bool)
}
oldCpu, newCpu := d.GetChange("cpu")
if oldCpu.(int) > newCpu.(int) && !forceResize.(bool) {
return diag.Errorf("Cannot resize compute ID %d: enable 'force_resize' to reduce compute vCPUs", computeRec.ID)
}
if oldCpu.(int) != newCpu.(int) {
resizeReq.CPU = uint64(newCpu.(int))
doUpdate = true
} else {
resizeReq.CPU = 0
}
oldRam, newRam := d.GetChange("ram")
if oldRam.(int) != newRam.(int) {
resizeReq.RAM = uint64(newRam.(int))
doUpdate = true
} else {
resizeReq.RAM = 0
}
if doUpdate {
log.Debugf("resourceComputeUpdate: changing CPU %d -> %d and/or RAM %d -> %d",
oldCpu.(int), newCpu.(int),
oldRam.(int), newRam.(int))
_, err := c.CloudAPI().Compute().Resize(ctx, resizeReq)
if err != nil {
return diag.FromErr(err)
}
}
if d.HasChanges("description", "name", "numa_affinity", "cpu_pin", "hp_backed") {
req := compute.UpdateRequest{
ComputeID: computeRec.ID,
}
@@ -890,35 +871,28 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
if d.HasChange("numa_affinity") {
req.NumaAffinity = d.Get("numa_affinity").(string)
}
if d.HasChange("cpu_pin") {
req.CPUPin = d.Get("cpu_pin").(bool)
}
if d.HasChange("hp_backed") {
req.HPBacked = d.Get("hp_backed").(bool)
}
if d.HasChange("chipset") {
req.Chipset = d.Get("chipset").(string)
}
req.CPUPin = d.Get("cpu_pin").(bool)
req.HPBacked = d.Get("hp_backed").(bool)
req.AutoStart = d.Get("auto_start_w_node").(bool)
// Note bene: numa_affinity, cpu_pin and hp_backed are not allowed to be changed for compute in STARTED tech status.
// If STARTED, we need to stop it before update
var isStopRequired bool
if d.HasChanges("numa_affinity", "cpu_pin", "hp_backed", "chipset") && d.Get("started").(bool) {
isStopRequired = true
}
if isStopRequired {
if _, err := c.CloudAPI().Compute().Stop(ctx, compute.StopRequest{ComputeID: computeRec.ID}); err != nil {
return diag.FromErr(err)
}
}
// perform update
if _, err := c.CloudAPI().Compute().Update(ctx, req); err != nil {
return diag.FromErr(err)
}
// If used to be STARTED, we need to start it after update
if isStopRequired {
if _, err := c.CloudAPI().Compute().Start(ctx, compute.StartRequest{ComputeID: computeRec.ID}); err != nil {
return diag.FromErr(err)
}
}
// If used to be STARTED, we need to start it after update
if isStopRequired {
if _, err := c.CloudAPI().Compute().Start(ctx, compute.StartRequest{ComputeID: computeRec.ID}); err != nil {
return diag.FromErr(err)
}
}
@@ -1491,7 +1465,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
req := compute.PinToStackRequest{
ComputeID: computeRec.ID,
}
req.AutoStart = d.Get("auto_start_w_node").(bool)
_, err := c.CloudAPI().Compute().PinToStack(ctx, req)
if err != nil {
return diag.FromErr(err)
@@ -2133,12 +2107,6 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema {
Optional: true,
Default: false,
},
"auto_start_w_node": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "Flag for start compute after node exits from MAINTENANCE state",
},
"auto_start": {
Type: schema.TypeBool,
Optional: true,
@@ -2427,15 +2395,88 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeBool,
Computed: true,
},
"vnc_password": {
Type: schema.TypeString,
Computed: true,
},
"vgpus": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"gid": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"profile_id": {
Type: schema.TypeInt,
Computed: true,
},
"ram": {
Type: schema.TypeInt,
Computed: true,
},
"last_update_time": {
Type: schema.TypeInt,
Computed: true,
},
"created_time": {
Type: schema.TypeInt,
Computed: true,
},
"deleted_time": {
Type: schema.TypeInt,
Computed: true,
},
"vmid": {
Type: schema.TypeInt,
Computed: true,
},
"pgpuid": {
Type: schema.TypeInt,
Computed: true,
},
"reference_id": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"rg_id": {
Type: schema.TypeInt,
Computed: true,
},
"last_claimed_by": {
Type: schema.TypeInt,
Computed: true,
},
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
},
"bus_number": {
Type: schema.TypeInt,
Computed: true,
},
"guid": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"virtual_image_id": {
@@ -2464,14 +2505,11 @@ func ResourceCompute() *schema.Resource {
},
CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error {
if diff.HasChanges() || diff.HasChanges("chipset", "pin_to_stack", "auto_start_w_node", "network", "affinity_rules", "anti_affinity_rules",
if diff.HasChanges() || diff.HasChanges("network", "affinity_rules", "anti_affinity_rules",
"disks", "extra_disks", "tags", "port_forwarding", "user_access", "snapshot", "pci_devices") {
diff.SetNewComputed("updated_time")
diff.SetNewComputed("updated_by")
}
if diff.HasChanges("pin_to_stack") {
diff.SetNewComputed("pinned")
}
return nil
},

View File

@@ -98,14 +98,6 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
if detach_set.Len() > 0 {
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
stopReq := compute.StopRequest{
ComputeID: computeId,
Force: false,
}
_, err := c.CloudAPI().Compute().Stop(ctx, stopReq)
if err != nil {
return err
}
for _, diskId := range detach_set.List() {
req := compute.DiskDetachRequest{
@@ -120,14 +112,6 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
}
}
req := compute.StartRequest{
ComputeID: computeId,
AltBootID: 0,
}
_, err = c.CloudAPI().Compute().Start(ctx, req)
if err != nil {
return err
}
}
attach_set := new_set.(*schema.Set).Difference(old_set.(*schema.Set))

View File

@@ -347,10 +347,6 @@ func vnfDevSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"vnc_password": {
Type: schema.TypeString,
Computed: true,
},
"vins": {
Type: schema.TypeList,
Computed: true,
@@ -376,8 +372,20 @@ func vinsComputeSchemaMake() map[string]*schema.Schema {
func reservationSchemaMake() map[string]*schema.Schema {
return map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
"client_type": {
Type: schema.TypeString,
Computed: true,
},
"desc": {
Type: schema.TypeString,
Computed: true,
},
"domainname": {
Type: schema.TypeString,
Computed: true,
},
"hostname": {
Type: schema.TypeString,
Computed: true,
},
"ip": {

View File

@@ -151,7 +151,6 @@ func flattenVNFDev(vnfDev vins.RecordVNFDev) []map[string]interface{} {
"status": vnfDev.Status,
"tech_status": vnfDev.TechStatus,
"type": vnfDev.Type,
"vnc_password": vnfDev.VNCPassword,
"vins": vnfDev.VINS,
}
@@ -177,11 +176,14 @@ func flattenReservations(reservations vins.ListReservations) []map[string]interf
res := make([]map[string]interface{}, 0, len(reservations))
for _, reservation := range reservations {
temp := map[string]interface{}{
"account_id": reservation.AccountID,
"ip": reservation.IP,
"mac": reservation.MAC,
"type": reservation.Type,
"vm_id": reservation.VMID,
"client_type": reservation.ClientType,
"desc": reservation.Description,
"domainname": reservation.DomainName,
"hostname": reservation.Hostname,
"ip": reservation.IP,
"mac": reservation.MAC,
"type": reservation.Type,
"vm_id": reservation.VMID,
}
res = append(res, temp)
}

View File

@@ -1,194 +1,277 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.
Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package vins
import (
"context"
"fmt"
"strconv"
"strings"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(*controller.ControllerCfg)
if _, ok := d.GetOk("vins_id"); ok {
haveVinsID, err := existVinsID(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
if !haveVinsID {
return diag.Errorf("resourceStaticRouteCreate: can't create Static Route because Vins ID %d is not allowed or does not exist", d.Get("vins_id").(int))
}
}
req := vins.StaticRouteAddRequest{
VINSID: uint64(d.Get("vins_id").(int)),
Destination: d.Get("destination").(string),
Netmask: d.Get("netmask").(string),
Gateway: d.Get("gateway").(string),
}
_, err := c.CloudAPI().VINS().StaticRouteAdd(ctx, req)
if err != nil {
return diag.FromErr(err)
}
staticRouteData, err := getStaticRouteData(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
d.SetId(fmt.Sprintf("%d#%d", req.VINSID, staticRouteData.ID))
return resourceStaticRouteRead(ctx, d, m)
}
func resourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
warnings := dc.Warnings{}
staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
flattenStaticRouteData(d, staticRouteData)
return warnings.Get()
}
func resourceStaticRouteUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
return nil
}
func resourceStaticRouteDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(*controller.ControllerCfg)
arr := strings.Split(d.Id(), "#")
if len(arr) != 2 {
return diag.FromErr(fmt.Errorf("broken state id"))
}
vinsId, _ := strconv.ParseUint(arr[0], 10, 64)
routeId, _ := strconv.ParseUint(arr[1], 10, 64)
req := vins.StaticRouteDelRequest{
VINSID: vinsId,
RouteId: routeId,
}
_, err := c.CloudAPI().VINS().StaticRouteDel(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}
func resourceStaticRouteSchemaMake() map[string]*schema.Schema {
rets := dataSourceStaticRouteSchemaMake()
rets["route_id"] = &schema.Schema{
Type: schema.TypeInt,
Computed: true,
Optional: true,
}
rets["compute_ids"] = &schema.Schema{
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
}
rets["destination"] = &schema.Schema{
Type: schema.TypeString,
Required: true,
}
rets["gateway"] = &schema.Schema{
Type: schema.TypeString,
Required: true,
}
rets["netmask"] = &schema.Schema{
Type: schema.TypeString,
Required: true,
}
return rets
}
func isContainsIds(els []interface{}, el interface{}) bool {
convEl := el.(int)
for _, elOld := range els {
if convEl == elOld.(int) {
return true
}
}
return false
}
func ResourceStaticRoute() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
CreateContext: resourceStaticRouteCreate,
ReadContext: resourceStaticRouteRead,
UpdateContext: resourceStaticRouteUpdate,
DeleteContext: resourceStaticRouteDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Create: &constants.Timeout20m,
Read: &constants.Timeout600s,
Update: &constants.Timeout20m,
Delete: &constants.Timeout600s,
Default: &constants.Timeout600s,
},
Schema: resourceStaticRouteSchemaMake(),
}
}
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.
Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package vins
import (
"context"
"fmt"
"strconv"
"strings"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(*controller.ControllerCfg)
if _, ok := d.GetOk("vins_id"); ok {
haveVinsID, err := existVinsID(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
if !haveVinsID {
return diag.Errorf("resourceStaticRouteCreate: can't create Static Route because Vins ID %d is not allowed or does not exist", d.Get("vins_id").(int))
}
}
req := vins.StaticRouteAddRequest{
VINSID: uint64(d.Get("vins_id").(int)),
Destination: d.Get("destination").(string),
Netmask: d.Get("netmask").(string),
Gateway: d.Get("gateway").(string),
}
if computesIDS, ok := d.GetOk("compute_ids"); ok {
ids := computesIDS.([]interface{})
res := make([]uint64, 10)
for _, id := range ids {
computeId := uint64(id.(int))
res = append(res, computeId)
}
req.ComputeIds = res
}
_, err := c.CloudAPI().VINS().StaticRouteAdd(ctx, req)
if err != nil {
return diag.FromErr(err)
}
staticRouteData, err := getStaticRouteData(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
d.SetId(fmt.Sprintf("%d#%d", req.VINSID, staticRouteData.ID))
return resourceStaticRouteRead(ctx, d, m)
}
func resourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
warnings := dc.Warnings{}
staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
flattenStaticRouteData(d, staticRouteData)
return warnings.Get()
}
func resourceStaticRouteUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(*controller.ControllerCfg)
warnings := dc.Warnings{}
if _, ok := d.GetOk("vins_id"); ok {
haveVinsID, err := existVinsID(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
if !haveVinsID {
return diag.Errorf("resourceVinsUpdate: can't update Static Route because VinsID %d is not allowed or does not exist", d.Get("vins_id").(int))
}
}
staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
if d.HasChange("compute_ids") {
deletedIds := make([]uint64, 0)
addedIds := make([]uint64, 0)
oldComputeIds, newComputeIds := d.GetChange("compute_ids")
oldComputeIdsSlice := oldComputeIds.([]interface{})
newComputeIdsSlice := newComputeIds.([]interface{})
for _, el := range oldComputeIdsSlice {
if !isContainsIds(newComputeIdsSlice, el) {
convertedEl := uint64(el.(int))
deletedIds = append(deletedIds, convertedEl)
}
}
for _, el := range newComputeIdsSlice {
if !isContainsIds(oldComputeIdsSlice, el) {
convertedEl := uint64(el.(int))
addedIds = append(addedIds, convertedEl)
}
}
if len(deletedIds) > 0 {
req := vins.StaticRouteAccessRevokeRequest{
VINSID: uint64(d.Get("vins_id").(int)),
RouteId: staticRouteData.ID,
ComputeIds: deletedIds,
}
_, err := c.CloudAPI().VINS().StaticRouteAccessRevoke(ctx, req)
if err != nil {
warnings.Add(err)
}
}
if len(addedIds) > 0 {
req := vins.StaticRouteAccessGrantRequest{
VINSID: uint64(d.Get("vins_id").(int)),
RouteId: staticRouteData.ID,
ComputeIds: addedIds,
}
_, err := c.CloudAPI().VINS().StaticRouteAccessGrant(ctx, req)
if err != nil {
warnings.Add(err)
}
}
}
return append(warnings.Get(), resourceStaticRouteRead(ctx, d, m)...)
}
func resourceStaticRouteDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(*controller.ControllerCfg)
arr := strings.Split(d.Id(), "#")
if len(arr) != 2 {
return diag.FromErr(fmt.Errorf("broken state id"))
}
vinsId, _ := strconv.ParseUint(arr[0], 10, 64)
routeId, _ := strconv.ParseUint(arr[1], 10, 64)
req := vins.StaticRouteDelRequest{
VINSID: vinsId,
RouteId: routeId,
}
_, err := c.CloudAPI().VINS().StaticRouteDel(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}
func resourceStaticRouteSchemaMake() map[string]*schema.Schema {
rets := dataSourceStaticRouteSchemaMake()
rets["route_id"] = &schema.Schema{
Type: schema.TypeInt,
Computed: true,
Optional: true,
}
rets["compute_ids"] = &schema.Schema{
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
}
rets["destination"] = &schema.Schema{
Type: schema.TypeString,
Required: true,
}
rets["gateway"] = &schema.Schema{
Type: schema.TypeString,
Required: true,
}
rets["netmask"] = &schema.Schema{
Type: schema.TypeString,
Required: true,
}
return rets
}
func isContainsIds(els []interface{}, el interface{}) bool {
convEl := el.(int)
for _, elOld := range els {
if convEl == elOld.(int) {
return true
}
}
return false
}
func ResourceStaticRoute() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
CreateContext: resourceStaticRouteCreate,
ReadContext: resourceStaticRouteRead,
UpdateContext: resourceStaticRouteUpdate,
DeleteContext: resourceStaticRouteDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Create: &constants.Timeout20m,
Read: &constants.Timeout600s,
Update: &constants.Timeout20m,
Delete: &constants.Timeout600s,
Default: &constants.Timeout600s,
},
Schema: resourceStaticRouteSchemaMake(),
}
}

View File

@@ -1,71 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
Tim Tkachev, <tvtkachev@basistech.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.
Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package extnet
import (
"context"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func dataSourceExtnetReservedIpRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
reservedList, err := utilityExtnetReservedIpCheckPresence(ctx, d, m)
if err != nil {
return diag.FromErr(err)
}
id := uuid.New()
d.SetId(id.String())
d.Set("items", flattenExtnetReservedIp(reservedList))
return nil
}
func DataSourceExtnetReservedIp() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
ReadContext: dataSourceExtnetReservedIpRead,
Timeouts: &schema.ResourceTimeout{
Read: &constants.Timeout30s,
Default: &constants.Timeout60s,
},
Schema: dataSourceExtnetReservedIpSchemaMake(),
}
}

View File

@@ -133,6 +133,7 @@ func flattenRecordExtnetResource(d *schema.ResourceData, recNet *extnet.RecordEx
d.Set("routes", flattenStaticRouteList(staticRouteList))
}
func flattenExtnetExcluded(ers extnet.ListReservations) []map[string]interface{} {
res := make([]map[string]interface{}, 0)
for _, er := range ers {
@@ -156,7 +157,6 @@ func flattenExtnetReservations(ers extnet.ListReservations) []map[string]interfa
res := make([]map[string]interface{}, 0)
for _, er := range ers {
temp := map[string]interface{}{
"account_id": er.AccountID,
"client_type": er.ClientType,
"domain_name": er.DomainName,
"hostname": er.Hostname,
@@ -217,30 +217,4 @@ func flattenStaticRouteData(d *schema.ResourceData, route *extnet.ItemRoutes) {
d.Set("netmask", route.Netmask)
d.Set("compute_ids", route.ComputeIds)
d.Set("route_id", route.ID)
}
func flattenExtnetReservedIp(el []extnet.RecordReservedIP) []map[string]interface{} {
res := make([]map[string]interface{}, 0, len(el))
for _, e := range el {
reservations := make([]map[string]interface{}, 0, len(e.Reservations))
for _, r := range e.Reservations {
temp := map[string]interface{}{
"account_id": r.AccountID,
"client_type": r.ClientType,
"domain_name": r.DomainName,
"hostname": r.Hostname,
"ip": r.IP,
"mac": r.Mac,
"type": r.Type,
"vm_id": r.VMID,
}
reservations = append(reservations, temp)
}
item := map[string]interface{}{
"extnet_id": e.ExtnetID,
"reservations": reservations,
}
res = append(res, item)
}
return res
}
}

View File

@@ -54,9 +54,6 @@ func resourceExtnetCreate(ctx context.Context, d *schema.ResourceData, m interfa
if err := ic.ExistGID(ctx, uint64(d.Get("gid").(int)), c); err != nil {
return diag.FromErr(err)
}
if err := checkReserveIp(ctx, d, c); err != nil {
return diag.FromErr(err)
}
req := extnet.CreateRequest{
Name: d.Get("name").(string),
@@ -194,34 +191,6 @@ func resourceExtnetCreate(ctx context.Context, d *schema.ResourceData, m interfa
}
}
// for reserve IP extnet must be enabled
if d.Get("reserved_ip").(*schema.Set).Len() > 0 {
for _, reservedIP := range d.Get("reserved_ip").(*schema.Set).List() {
reservedIPMap := reservedIP.(map[string]interface{})
req := extnet.AddReserveIPRequest{
AccountID: uint64(reservedIPMap["account_id"].(int)),
ExtNetID: netID,
}
if ipCount, ok := reservedIPMap["ip_count"]; ok {
req.IPCount = uint64(ipCount.(int))
}
if reservedIPMap["ips"].(*schema.Set).Len() > 0 {
ips := reservedIPMap["ips"].(*schema.Set).List()
for i, ip := range ips {
if i >= int(req.IPCount) {
break
}
req.IPs = append(req.IPs, ip.(string))
}
}
_, err := c.CloudBroker().ExtNet().AddReserveIP(ctx, req)
if err != nil {
w.Add(err)
}
}
}
return resourceExtnetRead(ctx, d, m)
}
@@ -246,10 +215,6 @@ func resourceExtnetUpdate(ctx context.Context, d *schema.ResourceData, m interfa
log.Debugf("cloudbroker: resourceExtnetUpdate called with id %s", d.Id())
c := m.(*controller.ControllerCfg)
if err := checkReserveIp(ctx, d, c); err != nil {
return diag.FromErr(err)
}
recNet, err := utilityExtnetCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
@@ -302,12 +267,6 @@ func resourceExtnetUpdate(ctx context.Context, d *schema.ResourceData, m interfa
}
}
if d.HasChange("reserved_ip") {
if err := reservedIPsUpdate(ctx, d, c, recNet); err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("shared_with") {
if err := handleSharedWithUpdate(ctx, d, c); err != nil {
return diag.FromErr(err)
@@ -371,8 +330,6 @@ func ResourceExtnetCB() *schema.Resource {
Default: &constants.Timeout300s,
},
CustomizeDiff: validateReserveIPs,
Schema: resourceExtnetSchemaMake(),
}
}

View File

@@ -1,9 +1,6 @@
package extnet
import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
func dataSourceExtnetDefaultSchemaMake() map[string]*schema.Schema {
return map[string]*schema.Schema{
@@ -477,10 +474,6 @@ func dataSourceExtnetSchemaMake() map[string]*schema.Schema {
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"client_type": {
Type: schema.TypeString,
Computed: true,
@@ -735,30 +728,6 @@ func resourceExtnetSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
},
},
"reserved_ip": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Required: true,
},
"ip_count": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 255),
},
"ips": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"ckey": {
Type: schema.TypeString,
Computed: true,
@@ -899,10 +868,6 @@ func resourceExtnetSchemaMake() map[string]*schema.Schema {
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"client_type": {
Type: schema.TypeString,
Computed: true,
@@ -940,69 +905,3 @@ func resourceExtnetSchemaMake() map[string]*schema.Schema {
},
}
}
func dataSourceExtnetReservedIpSchemaMake() map[string]*schema.Schema {
res := map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Required: true,
},
"extnet_id": {
Type: schema.TypeInt,
Optional: true,
},
"items": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"extnet_id": {
Type: schema.TypeInt,
Computed: true,
},
"reservations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"client_type": {
Type: schema.TypeString,
Computed: true,
},
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"hostname": {
Type: schema.TypeString,
Computed: true,
},
"ip": {
Type: schema.TypeString,
Computed: true,
},
"mac": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"vm_id": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
},
},
}
return res
}

View File

@@ -1,61 +0,0 @@
/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.
Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort
Please see README.md to learn where to place source code so that it
builds seamlessly.
Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/
package extnet
import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/extnet"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)
func utilityExtnetReservedIpCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) ([]extnet.RecordReservedIP, error) {
c := m.(*controller.ControllerCfg)
req := extnet.GetReservedIP{
AccountID: uint64(d.Get("account_id").(int)),
}
if extNetID, ok := d.GetOk("extnet_id"); ok {
req.ExtNetID = uint64(extNetID.(int))
}
log.Debugf("utilityExtnetReservedIpCheckPresence")
res, err := c.CloudBroker().ExtNet().GetReservedIP(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}

View File

@@ -35,8 +35,6 @@ package extnet
import (
"context"
"errors"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
@@ -343,255 +341,3 @@ func handleMigrateUpdate(ctx context.Context, d *schema.ResourceData, c *control
return nil
}
func checkReserveIp(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg) error {
var err error
if d.Get("reserved_ip").(*schema.Set).Len() > 0 {
reservedIPList := d.Get("reserved_ip").(*schema.Set).List()
accountMap := make(map[int]struct{}, len(reservedIPList))
for _, reservedIP := range reservedIPList {
reservedIPMap := reservedIP.(map[string]interface{})
accountId := reservedIPMap["account_id"].(int)
if _, ok := accountMap[accountId]; ok {
err = errors.Join(err, fmt.Errorf("checkReserveIp: you must have only one block with id %d", accountId))
}
accountMap[accountId] = struct{}{}
_, okCount := reservedIPMap["ip_count"]
if !okCount && reservedIPMap["ips"].(*schema.Set).Len() == 0 {
err = errors.Join(err, fmt.Errorf("checkReserveIp: either ip_count or set of ips must be specified"))
}
existErr := ic.ExistAccount(ctx, uint64(accountId), c)
if existErr != nil {
err = errors.Join(err, existErr)
}
}
}
return err
}
func reservedIPsUpdate(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, recNet *extnet.RecordExtNet) error {
addSet, delSet, err := differenceIPReserved(ctx, d, c)
if err != nil {
return err
}
if len(delSet) > 0 {
for _, del := range delSet {
delMap := del.(map[string]interface{})
log.Debugf("reservedIPsUpdate: removing reserved IPs for account %d", delMap["account_id"].(int))
req := extnet.DelReserveIPRequest{
AccountID: uint64(delMap["account_id"].(int)),
ExtNetID: recNet.ID,
}
if ipCount, ok := delMap["ip_count"]; ok {
req.IPCount = uint64(ipCount.(int))
}
if delIPs, ok := delMap["ips"]; ok {
ips := delIPs.(*schema.Set).List()
for _, ip := range ips {
req.IPs = append(req.IPs, ip.(string))
}
}
_, err := c.CloudBroker().ExtNet().DelReserveIP(ctx, req)
if err != nil {
return err
}
}
}
if len(addSet) > 0 {
for _, add := range addSet {
addMap := add.(map[string]interface{})
log.Debugf("reservedIPsUpdate: add reserved IPs for account %d", addMap["account_id"].(int))
req := extnet.AddReserveIPRequest{
AccountID: uint64(addMap["account_id"].(int)),
ExtNetID: recNet.ID,
}
if ipCount, ok := addMap["ip_count"]; ok {
req.IPCount = uint64(ipCount.(int))
}
if addIPs, ok := addMap["ips"]; ok {
ips := addIPs.(*schema.Set).List()
for _, ip := range ips {
req.IPs = append(req.IPs, ip.(string))
}
}
_, err := c.CloudBroker().ExtNet().AddReserveIP(ctx, req)
if err != nil {
return err
}
}
}
return nil
}
func differenceIPReserved(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg) (addList, delList []interface{}, errs error) {
addList = make([]interface{}, 0)
delList = make([]interface{}, 0)
oldSet, newSet := d.GetChange("reserved_ip")
oldList := oldSet.(*schema.Set).List()
newList := newSet.(*schema.Set).List()
for _, oldReservedIP := range oldList {
oldMap := oldReservedIP.(map[string]interface{})
found := false
for _, newReservedIP := range newList {
newMap := newReservedIP.(map[string]interface{})
if newMap["account_id"] == oldMap["account_id"] && newMap["ip_count"] == oldMap["ip_count"] && newMap["ips"] == oldMap["ips"] {
found = true
break
}
if newMap["account_id"] == oldMap["account_id"] {
add := make(map[string]interface{}, 0)
del := make(map[string]interface{}, 0)
delSet := oldMap["ips"].(*schema.Set).Difference(newMap["ips"].(*schema.Set))
addSet := newMap["ips"].(*schema.Set).Difference(oldMap["ips"].(*schema.Set))
if delSet.Len() > 0 {
del["account_id"] = oldMap["account_id"].(int)
del["ips"] = delSet
if oldMap["ip_count"].(int)-newMap["ip_count"].(int) >= delSet.Len() {
del["ip_count"] = oldMap["ip_count"].(int) - newMap["ip_count"].(int)
} else {
del["ip_count"] = delSet.Len()
newMap["ip_count"] = newMap["ip_count"].(int) + delSet.Len()
}
} else if newMap["ip_count"].(int) < oldMap["ip_count"].(int) {
del["account_id"] = oldMap["account_id"].(int)
del["ip_count"] = oldMap["ip_count"].(int) - newMap["ip_count"].(int)
}
if addSet.Len() > 0 {
add["account_id"] = oldMap["account_id"].(int)
add["ips"] = addSet
add["ip_count"] = newMap["ip_count"].(int) - oldMap["ip_count"].(int)
if add["ip_count"].(int) < 0 {
add["ip_count"] = 0
}
if add["ip_count"].(int)-addSet.Len() < 0 {
del["account_id"] = oldMap["account_id"].(int)
if _, ok := del["ip_count"]; ok {
del["ip_count"] = del["ip_count"].(int) + addSet.Len()
} else {
del["ip_count"] = addSet.Len()
}
}
} else if newMap["ip_count"].(int)-oldMap["ip_count"].(int) > 0 {
add["account_id"] = oldMap["account_id"].(int)
add["ip_count"] = newMap["ip_count"].(int) - oldMap["ip_count"].(int)
}
if _, ok := add["account_id"]; ok {
addList = append(addList, add)
}
if _, ok := del["account_id"]; ok {
ipsLen := 0
if _, ok := del["ips"]; ok {
ipsLen = del["ips"].(*schema.Set).Len()
}
freeCount := del["ip_count"].(int) - ipsLen
if freeCount > 0 {
req := extnet.GetReservedIP{
AccountID: uint64(del["account_id"].(int)),
ExtNetID: uint64(d.Get("extnet_id").(int)),
}
resIpsList, err := c.CloudBroker().ExtNet().GetReservedIP(ctx, req)
if err != nil {
errs = errors.Join(errs, err)
}
freeIPs := getFreeIps(resIpsList[0].Reservations, newMap["ips"], del["ips"])
if _, ok := del["ips"]; !ok {
del["ips"] = schema.NewSet(schema.HashString, []interface{}{})
}
for i := 0; i < freeCount; i++ {
del["ips"].(*schema.Set).Add(freeIPs[i])
}
}
delList = append(delList, del)
}
found = true
break
}
}
if found {
continue
}
delList = append(delList, oldReservedIP)
}
for _, newReservedIP := range newList {
newMap := newReservedIP.(map[string]interface{})
found := false
for _, oldReservedIP := range oldList {
oldMap := oldReservedIP.(map[string]interface{})
if newMap["account_id"] == oldMap["account_id"] {
found = true
break
}
}
if found {
continue
}
addList = append(addList, newReservedIP)
}
if errs != nil {
d.Set("reserved_ip", oldSet)
}
return
}
// getFreeIps returns array IPs which can be deleted
func getFreeIps(reserved []extnet.Reservations, newIps, delIps interface{}) []string {
newIpsList := make([]interface{}, 0)
delIpsList := make([]interface{}, 0)
if newIps != nil {
newIpsList = newIps.(*schema.Set).List()
}
if delIps != nil {
delIpsList = delIps.(*schema.Set).List()
}
newIpsMap := make(map[string]struct{}, len(newIpsList))
delIpsMap := make(map[string]struct{}, len(delIpsList))
freeIPs := make([]string, 0)
for _, ip := range newIpsList {
newIpsMap[ip.(string)] = struct{}{}
}
for _, ip := range delIpsList {
delIpsMap[ip.(string)] = struct{}{}
}
for _, item := range reserved {
if _, ok := newIpsMap[item.IP]; ok {
continue
}
if _, ok := delIpsMap[item.IP]; ok {
continue
}
freeIPs = append(freeIPs, item.IP)
}
return freeIPs
}
func validateReserveIPs(ctx context.Context, d *schema.ResourceDiff, m interface{}) error {
list := d.Get("reserved_ip").(*schema.Set).List()
var errs error
for _, reservedIP := range list {
reservedIPMap := reservedIP.(map[string]interface{})
var countIP, ipsLen int
if _, ok := reservedIPMap["ip_count"]; ok {
countIP = reservedIPMap["ip_count"].(int)
}
if _, ok := reservedIPMap["ips"]; ok {
ipsLen = reservedIPMap["ips"].(*schema.Set).Len()
}
if ipsLen > countIP {
errs = errors.Join(errs, fmt.Errorf("for the reserved_ip block with account_id %d the count parameter must be greater than or equal to len the ips array", reservedIPMap["account_id"].(int)))
}
}
return errs
}

View File

@@ -34,45 +34,21 @@ package grid
import (
"context"
"os"
"strconv"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
)
func dataSourceGridGetDiagnosisRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
filePath := "diagnosis.tar.gz"
if userPath, ok := d.GetOk("file_path"); ok {
filePath = userPath.(string)
}
log.Debugf("dataSourceGridGetDiagnosisRead: create file with name: %s", filePath)
file, err := os.Create(filePath)
defer file.Close()
if err != nil {
d.SetId("") // ensure ID is empty in this case
return diag.FromErr(err)
}
diagnosis, err := utilityGridGetDiagnosisCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
log.Debugf("dataSourceGridGetDiagnosisRead: write data to file with name: %s", filePath)
_, err = file.WriteString(diagnosis)
if err != nil {
d.SetId("") // ensure ID is empty in this case
return diag.FromErr(err)
}
id := uuid.New()
d.SetId(id.String())
d.SetId(strconv.Itoa(d.Get("gid").(int)))
d.Set("diagnosis", diagnosis)
return nil
}
@@ -90,3 +66,29 @@ func DataSourceGridGetDiagnosis() *schema.Resource {
Schema: dataSourceGridGetDiagnosisSchemaMake(),
}
}
func dataSourceGridPostDiagnosisRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
diagnosis, err := utilityGridPostDiagnosisCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
d.SetId(strconv.Itoa(d.Get("gid").(int)))
d.Set("diagnosis", diagnosis)
return nil
}
func DataSourceGridPostDiagnosis() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
ReadContext: dataSourceGridPostDiagnosisRead,
Timeouts: &schema.ResourceTimeout{
Read: &constants.Timeout30s,
Default: &constants.Timeout60s,
},
Schema: dataSourceGridPostDiagnosisSchemaMake(),
}
}

View File

@@ -586,10 +586,23 @@ func dataSourceGridGetDiagnosisSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Required: true,
},
"file_path": {
"diagnosis": {
Type: schema.TypeString,
Computed: true,
},
}
}
func dataSourceGridPostDiagnosisSchemaMake() map[string]*schema.Schema {
return map[string]*schema.Schema{
"gid": {
Type: schema.TypeInt,
Required: true,
},
"diagnosis": {
Type: schema.TypeString,
Computed: true,
},
}
}

View File

@@ -62,3 +62,23 @@ func utilityGridGetDiagnosisCheckPresence(ctx context.Context, d *schema.Resourc
return gridGetDiagnosis, nil
}
func utilityGridPostDiagnosisCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (string, error) {
c := m.(*controller.ControllerCfg)
req := grid.GetDiagnosisRequest{}
if d.Id() != "" {
id, _ := strconv.ParseUint(d.Id(), 10, 64)
req.GID = id
} else {
req.GID = uint64(d.Get("gid").(int))
}
log.Debugf("utilityGridPostDiagnosisCheckPresence: load grid post diagnosis")
gridPostDiagnosis, err := c.CloudBroker().Grid().GetDiagnosis(ctx, req)
if err != nil {
return "", err
}
return gridPostDiagnosis, nil
}

View File

@@ -48,7 +48,6 @@ func flattenImage(d *schema.ResourceData, img *image.RecordImage) {
d.Set("sep_id", img.SEPID)
d.Set("shared_with", img.SharedWith)
d.Set("size", img.Size)
d.Set("snapshot_id", img.SnapshotID)
d.Set("status", img.Status)
d.Set("tech_status", img.TechStatus)
d.Set("image_type", img.Type)
@@ -93,48 +92,47 @@ func flattenImageList(il *image.ListImages) []map[string]interface{} {
cdPresentedTo, _ := json.Marshal(item.CdPresentedTo)
temp := map[string]interface{}{
"image_id": item.ID,
"unc_path": item.UNCPath,
"account_id": item.AccountID,
"acl": flattenAcl(item.ACL),
"architecture": item.Architecture,
"boot_type": item.BootType,
"bootable": item.Bootable,
"computeci_id": item.ComputeCIID,
"cd_presented_to": string(cdPresentedTo),
"deleted_time": item.DeletedTime,
"desc": item.Description,
"drivers": item.Drivers,
"enabled": item.Enabled,
"gid": item.GID,
"guid": item.GUID,
"history": flattenHistory(item.History),
"hot_resize": item.HotResize,
"last_modified": item.LastModified,
"link_to": item.LinkTo,
"milestones": item.Milestones,
"name": item.Name,
"image_id": item.ID,
"unc_path": item.UNCPath,
"account_id": item.AccountID,
"acl": flattenAcl(item.ACL),
"architecture": item.Architecture,
"boot_type": item.BootType,
"bootable": item.Bootable,
"computeci_id": item.ComputeCIID,
"cd_presented_to": string(cdPresentedTo),
"deleted_time": item.DeletedTime,
"desc": item.Description,
"drivers": item.Drivers,
"enabled": item.Enabled,
"gid": item.GID,
"guid": item.GUID,
"history": flattenHistory(item.History),
"hot_resize": item.HotResize,
"last_modified": item.LastModified,
"link_to": item.LinkTo,
"milestones": item.Milestones,
"name": item.Name,
"network_interface_naming": item.NetworkInterfaceNaming,
"password": item.Password,
"pool_name": item.Pool,
"present_to": item.PresentTo,
"provider_name": item.ProviderName,
"purge_attempts": item.PurgeAttempts,
"reference_id": item.ReferenceID,
"res_id": item.ResID,
"res_name": item.ResName,
"rescuecd": item.RescueCD,
"sep_id": item.SEPID,
"shared_with": item.SharedWith,
"size": item.Size,
"snapshot_id": item.SnapshotID,
"status": item.Status,
"tech_status": item.TechStatus,
"image_type": item.Type,
"url": item.URL,
"username": item.Username,
"version": item.Version,
"virtual": item.Virtual,
"password": item.Password,
"pool_name": item.Pool,
"present_to": item.PresentTo,
"provider_name": item.ProviderName,
"purge_attempts": item.PurgeAttempts,
"reference_id": item.ReferenceID,
"res_id": item.ResID,
"res_name": item.ResName,
"rescuecd": item.RescueCD,
"sep_id": item.SEPID,
"shared_with": item.SharedWith,
"size": item.Size,
"status": item.Status,
"tech_status": item.TechStatus,
"image_type": item.Type,
"url": item.URL,
"username": item.Username,
"version": item.Version,
"virtual": item.Virtual,
}
res = append(res, temp)
}

View File

@@ -622,11 +622,6 @@ func dataSourceImageListSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "image size",
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: "snapshot id",
},
"status": {
Type: schema.TypeString,
Computed: true,
@@ -880,11 +875,6 @@ func dataSourceImageSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "image size",
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: "snapshot id",
},
"status": {
Type: schema.TypeString,
Computed: true,
@@ -1134,11 +1124,6 @@ func resourceCDROMImageSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
},
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: "snapshot id",
},
"status": {
Type: schema.TypeString,
Computed: true,
@@ -1430,11 +1415,6 @@ func resourceImageSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
},
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: "snapshot id",
},
"status": {
Type: schema.TypeString,
Computed: true,
@@ -1709,11 +1689,6 @@ func resourceVirtualImageSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "image size",
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: "snapshot id",
},
"status": {
Type: schema.TypeString,
Computed: true,
@@ -1992,11 +1967,6 @@ func resourceImageFromBlankComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: "snapshot id",
},
"status": {
Type: schema.TypeString,
Computed: true,
@@ -2271,11 +2241,6 @@ func resourceImageFromPlatformDiskSchemaMake() map[string]*schema.Schema {
Type: schema.TypeInt,
Computed: true,
},
"snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: "snapshot id",
},
"status": {
Type: schema.TypeString,
Computed: true,

View File

@@ -34,7 +34,6 @@ func flattenCompute(d *schema.ResourceData, computeRec *compute.RecordCompute, p
d.Set("affinity_rules", flattenAffinityRules(computeRec.AffinityRules))
d.Set("anti_affinity_rules", flattenAffinityRules(computeRec.AntiAffinityRules))
d.Set("arch", computeRec.Arch)
d.Set("auto_start_w_node", computeRec.AutoStart)
d.Set("boot_order", computeRec.BootOrder)
d.Set("boot_disk_id", bootDisk.ID)
// we intentionally use the SizeMax field, do not change it until the BootDiskSize field is fixed on the platform
@@ -93,8 +92,7 @@ func flattenCompute(d *schema.ResourceData, computeRec *compute.RecordCompute, p
d.Set("updated_time", computeRec.UpdatedTime)
d.Set("user_data", string(userData))
d.Set("user_managed", computeRec.UserManaged)
d.Set("vnc_password", computeRec.VNCPassword)
d.Set("vgpus", computeRec.VGPUs)
d.Set("vgpus", flattenVGPUs(computeRec.VGPUs))
d.Set("virtual_image_id", computeRec.VirtualImageID)
d.Set("virtual_image_name", computeRec.VirtualImageName)
d.Set("pci_devices", flattenPCI(*pciList))
@@ -296,7 +294,6 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{}
"affinity_weight": computeItem.AffinityWeight,
"anti_affinity_rules": flattenListRules(computeItem.AntiAffinityRules),
"arch": computeItem.Arch,
"auto_start_w_node": computeItem.AutoStart,
"chipset": computeItem.Chipset,
"cd_image_id": computeItem.CdImageId,
"boot_order": computeItem.BootOrder,
@@ -616,7 +613,6 @@ func flattenDataCompute(d *schema.ResourceData, compFacts *compute.RecordCompute
d.Set("affinity_weight", compFacts.AffinityWeight)
d.Set("anti_affinity_rules", flattenAffinityRules(compFacts.AntiAffinityRules))
d.Set("arch", compFacts.Arch)
d.Set("auto_start_w_node", compFacts.AutoStart)
d.Set("boot_order", compFacts.BootOrder)
d.Set("chipset", compFacts.Chipset)
d.Set("cd_image_id", compFacts.CdImageId)
@@ -675,8 +671,7 @@ func flattenDataCompute(d *schema.ResourceData, compFacts *compute.RecordCompute
d.Set("updated_time", compFacts.UpdatedTime)
d.Set("user_data", string(userData))
d.Set("user_managed", compFacts.UserManaged)
d.Set("vnc_password", compFacts.VNCPassword)
d.Set("vgpus", compFacts.VGPUs)
d.Set("vgpus", flattenVGPUs(compFacts.VGPUs))
d.Set("virtual_image_id", compFacts.VirtualImageID)
d.Set("virtual_image_name", compFacts.VirtualImageName)
d.Set("pci_devices", flattenPCI(*pciList))
@@ -834,3 +829,33 @@ func flattendDiskSnapshotList(sl compute.ListDetailedSnapshots) []interface{} {
return res
}
func flattenVGPUs(vgpus []compute.ItemVGPU) []map[string]interface{} {
res := make([]map[string]interface{}, len(vgpus))
for i, vgpu := range vgpus {
res[i] = map[string]interface{}{
"id": int(vgpu.ID),
"gid": int(vgpu.GID),
"type": vgpu.Type,
"mode": vgpu.Mode,
"status": vgpu.Status,
"profile_id": vgpu.ProfileID,
"ram": int(vgpu.RAM),
"last_update_time": int(vgpu.LastUpdateTime),
"created_time": int(vgpu.CreatedTime),
"deleted_time": int(vgpu.DeletedTime),
"vmid": int(vgpu.VMID),
"pgpuid": int(vgpu.PGPUID),
"reference_id": vgpu.ReferenceID,
"account_id": int(vgpu.AccountID),
"rg_id": int(vgpu.RGID),
"last_claimed_by": int(vgpu.LastClaimedBy),
"pci_slot": int(vgpu.PCISlot),
"guid": int(vgpu.GUID),
}
}
return res
}

View File

@@ -484,29 +484,12 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf
req.Force = force
}
if autoStart, ok := d.Get("auto_start_w_node").(bool); ok {
req.AutoStart = autoStart
}
_, err := c.CloudBroker().Compute().PinToStack(ctx, req)
if err != nil {
warnings.Add(err)
}
}
if !d.Get("pin_to_stack").(bool) && d.Get("auto_start_w_node").(bool) {
req := compute.UpdateRequest{
ComputeID: computeId,
AutoStart: d.Get("auto_start_w_node").(bool),
CPUPin: d.Get("cpu_pin").(bool),
HPBacked: d.Get("hp_backed").(bool),
}
_, err := c.CloudBroker().Compute().Update(ctx, req)
if err != nil {
warnings.Add(err)
}
}
if d.Get("pause").(bool) {
req := compute.PauseRequest{
ComputeID: computeId,
@@ -671,12 +654,6 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
}
if d.HasChange("started") {
if err := utilityComputeStarted(ctx, d, m); err != nil {
return diag.FromErr(err)
}
}
if d.HasChanges("cpu", "ram") {
if err := utilityComputeResize(ctx, d, m); err != nil {
return diag.FromErr(err)
@@ -703,7 +680,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
}
if d.HasChanges("description", "name", "numa_affinity", "cpu_pin", "hp_backed", "chipset", "auto_start_w_node") {
if d.HasChanges("description", "name", "numa_affinity", "cpu_pin", "hp_backed") {
if err := utilityComputeUpdate(ctx, d, m); err != nil {
return diag.FromErr(err)
}
@@ -805,6 +782,12 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf
}
}
if d.HasChange("started") {
if err := utilityComputeStarted(ctx, d, m); err != nil {
return diag.FromErr(err)
}
}
return append(resourceComputeRead(ctx, d, m), warnings.Get()...)
}
@@ -856,14 +839,11 @@ func ResourceCompute() *schema.Resource {
SchemaVersion: 1,
CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error {
if diff.HasChanges() || diff.HasChanges("chipset", "pin_to_stack", "auto_start_w_node", "libvirt_settings", "network", "affinity_rules", "anti_affinity_rules",
if diff.HasChanges() || diff.HasChanges("libvirt_settings", "network", "affinity_rules", "anti_affinity_rules",
"disks", "extra_disks", "tags", "port_forwarding", "user_access", "snapshot", "pci_devices") {
diff.SetNewComputed("updated_time")
diff.SetNewComputed("updated_by")
}
if diff.HasChanges("pin_to_stack") {
diff.SetNewComputed("pinned")
}
return nil
},

View File

@@ -134,10 +134,6 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"auto_start_w_node": {
Type: schema.TypeBool,
Computed: true,
},
"boot_order": {
Type: schema.TypeList,
Computed: true,
@@ -906,15 +902,88 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeBool,
Computed: true,
},
"vnc_password": {
Type: schema.TypeString,
Computed: true,
},
"vgpus": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"gid": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"profile_id": {
Type: schema.TypeInt,
Computed: true,
},
"ram": {
Type: schema.TypeInt,
Computed: true,
},
"last_update_time": {
Type: schema.TypeInt,
Computed: true,
},
"created_time": {
Type: schema.TypeInt,
Computed: true,
},
"deleted_time": {
Type: schema.TypeInt,
Computed: true,
},
"vmid": {
Type: schema.TypeInt,
Computed: true,
},
"pgpuid": {
Type: schema.TypeInt,
Computed: true,
},
"reference_id": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"rg_id": {
Type: schema.TypeInt,
Computed: true,
},
"last_claimed_by": {
Type: schema.TypeInt,
Computed: true,
},
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
},
"bus_number": {
Type: schema.TypeInt,
Computed: true,
},
"guid": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"virtual_image_id": {
@@ -998,11 +1067,6 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema {
Optional: true,
Description: "Find by image ID",
},
"cd_image_id": {
Type: schema.TypeInt,
Optional: true,
Description: "Find by CD image ID",
},
"extnet_name": {
Type: schema.TypeString,
Optional: true,
@@ -1158,10 +1222,6 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"auto_start_w_node": {
Type: schema.TypeBool,
Computed: true,
},
"boot_order": {
Type: schema.TypeList,
Computed: true,
@@ -1608,8 +1668,85 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema {
"vgpus": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"gid": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"mode": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"profile_id": {
Type: schema.TypeInt,
Computed: true,
},
"ram": {
Type: schema.TypeInt,
Computed: true,
},
"last_update_time": {
Type: schema.TypeInt,
Computed: true,
},
"created_time": {
Type: schema.TypeInt,
Computed: true,
},
"deleted_time": {
Type: schema.TypeInt,
Computed: true,
},
"vmid": {
Type: schema.TypeInt,
Computed: true,
},
"pgpuid": {
Type: schema.TypeInt,
Computed: true,
},
"reference_id": {
Type: schema.TypeString,
Computed: true,
},
"account_id": {
Type: schema.TypeInt,
Computed: true,
},
"rg_id": {
Type: schema.TypeInt,
Computed: true,
},
"last_claimed_by": {
Type: schema.TypeInt,
Computed: true,
},
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
},
"bus_number": {
Type: schema.TypeInt,
Computed: true,
},
"guid": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
"vins_connected": {
@@ -1819,10 +1956,6 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema {
Type: schema.TypeString,
Computed: true,
},
"auto_start_w_node": {
Type: schema.TypeBool,
Computed: true,
},
"boot_order": {
Type: schema.TypeList,
Computed: true,
@@ -3396,11 +3529,6 @@ func resourceComputeSchemaMake() map[string]*schema.Schema {
Optional: true,
Default: false,
},
"auto_start_w_node": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"target_stack_id": {
Type: schema.TypeInt,
Optional: true,
@@ -3932,10 +4060,6 @@ func resourceComputeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeBool,
Computed: true,
},
"vnc_password": {
Type: schema.TypeString,
Computed: true,
},
"vgpus": {
Type: schema.TypeList,
Computed: true,

View File

@@ -114,6 +114,23 @@ func utilityComputeResize(ctx context.Context, d *schema.ResourceData, m interfa
c := m.(*controller.ControllerCfg)
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
var isStopRequired bool
if d.Get("started").(bool) {
isStopRequired = true
}
if isStopRequired {
stopReq := compute.StopRequest{
ComputeID: computeId,
Force: false,
}
if depresent, ok := d.Get("depresent").(bool); ok {
stopReq.Depresent = depresent
}
if _, err := c.CloudBroker().Compute().Stop(ctx, stopReq); err != nil {
return err
}
}
resizeReq := compute.ResizeRequest{
ComputeID: computeId,
}
@@ -153,6 +170,12 @@ func utilityComputeResize(ctx context.Context, d *schema.ResourceData, m interfa
}
}
if isStopRequired {
if _, err := c.CloudBroker().Compute().Start(ctx, compute.StartRequest{ComputeID: computeId}); err != nil {
return err
}
}
return nil
}
@@ -458,19 +481,6 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
if detach_set.Len() > 0 {
computeId, _ := strconv.ParseUint(d.Id(), 10, 64)
stopReq := compute.StopRequest{
ComputeID: computeId,
Force: false,
}
if depresent, ok := d.Get("depresent").(bool); ok {
stopReq.Depresent = depresent
}
_, err := c.CloudBroker().Compute().Stop(ctx, stopReq)
if err != nil {
return err
}
for _, diskId := range detach_set.List() {
req := compute.DiskDetachRequest{
@@ -485,14 +495,6 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa
}
}
req := compute.StartRequest{
ComputeID: computeId,
AltBootID: 0,
}
_, err = c.CloudBroker().Compute().Start(ctx, req)
if err != nil {
return err
}
}
attach_set := new_set.(*schema.Set).Difference(old_set.(*schema.Set))
@@ -852,17 +854,21 @@ func utilityComputeUpdate(ctx context.Context, d *schema.ResourceData, m interfa
if d.HasChange("numa_affinity") {
req.NumaAffinity = d.Get("numa_affinity").(string)
}
if d.HasChange("cpu_pin") {
req.CPUPin = d.Get("cpu_pin").(bool)
}
if d.HasChange("hp_backed") {
req.HPBacked = d.Get("hp_backed").(bool)
}
if d.HasChange("chipset") {
req.Chipset = d.Get("chipset").(string)
}
req.CPUPin = d.Get("cpu_pin").(bool)
req.HPBacked = d.Get("hp_backed").(bool)
req.AutoStart = d.Get("auto_start_w_node").(bool)
// Note bene: numa_affinity, cpu_pin and hp_backed are not allowed to be changed for compute in STARTED tech status.
// If STARTED, we need to stop it before update
var isStopRequired bool
if d.HasChanges("numa_affinity", "cpu_pin", "hp_backed", "chipset") && d.Get("started").(bool) {
if d.HasChanges("numa_affinity", "cpu_pin", "hp_backed") && d.Get("started").(bool) {
isStopRequired = true
}
if isStopRequired {
@@ -1430,11 +1436,6 @@ func utilityComputePinToStack(ctx context.Context, d *schema.ResourceData, m int
if force, ok := d.Get("force_pin").(bool); ok {
req.Force = force
}
if autoStart, ok := d.Get("auto_start_w_node").(bool); ok {
req.AutoStart = autoStart
}
_, err := c.CloudBroker().Compute().PinToStack(ctx, req)
if err != nil {
return err

View File

@@ -75,9 +75,6 @@ func utilityDataComputeListCheckPresence(ctx context.Context, d *schema.Resource
if imageID, ok := d.GetOk("image_id"); ok {
req.ImageID = imageID.(uint64)
}
if cdImageID, ok := d.GetOk("cd_image_id"); ok {
req.CDImageID = cdImageID.(uint64)
}
if extNetName, ok := d.GetOk("extnet_name"); ok {
req.ExtNetName = extNetName.(string)
}

View File

@@ -51,7 +51,6 @@ func flattenNode(d *schema.ResourceData, item *node.RecordNode) {
d.Set("isolated_cpus", flattenNodeItem(item.IsolatedCpus))
d.Set("name", item.Name)
d.Set("need_reboot", item.NeedReboot)
d.Set("net_addr", flattenGetNetAddr(item.NetAddr))
d.Set("nic_info", flattenNicInfo(item.NicInfo))
d.Set("numa_topology", flattenNumaTopology(item.NumaTopology))
d.Set("reserved_cpus", flattenNodeItem(item.ReservedCPUs))
@@ -206,9 +205,9 @@ func flattenVFList(vfList []interface{}) []map[string]interface{} {
return res
}
func flattenNetAddr(addresses node.ListNetAddr) []map[string]interface{} {
res := make([]map[string]interface{}, 0, len(addresses))
for _, item := range addresses {
func flattenNetAddr(adresses node.ListNetAddr) []map[string]interface{} {
res := make([]map[string]interface{}, 0, len(adresses))
for _, item := range adresses {
temp := map[string]interface{}{
"cidr": item.CIDR,
"index": item.Index,
@@ -222,16 +221,6 @@ func flattenNetAddr(addresses node.ListNetAddr) []map[string]interface{} {
return res
}
func flattenGetNetAddr(address node.NetAddr) []map[string]interface{} {
res := make([]map[string]interface{}, 1)
temp := map[string]interface{}{
"ip": address.IP,
"name": address.Name,
}
res[0] = temp
return res
}
func flattenCpuInfo(info node.CpuInfo) []map[string]interface{} {
res := make([]map[string]interface{}, 1)
temp := map[string]interface{}{

View File

@@ -131,25 +131,6 @@ func dataSourceNodeSchemaMake() map[string]*schema.Schema {
Type: schema.TypeBool,
Computed: true,
},
"net_addr": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"nic_info": {
Type: schema.TypeList,
Computed: true,

View File

@@ -150,7 +150,6 @@ func flattenVinsVNFDev(vd vins.VNFDev) []map[string]interface{} {
"status": vd.Status,
"tech_status": vd.TechStatus,
"type": vd.Type,
"vnc_password": vd.VNCPassword,
"vins": vd.VINS,
}
res = append(res, temp)
@@ -372,12 +371,14 @@ func flattenVinsListReservations(li vins.ListReservations) []map[string]interfac
res := make([]map[string]interface{}, 0, len(li))
for _, v := range li {
temp := map[string]interface{}{
//TODO
//"account_id": v.AccountID,
"ip": v.IP,
"mac": v.MAC,
"type": v.Type,
"vm_id": v.VMID,
"client_type": v.ClientType,
"description": v.Description,
"domain_name": v.DomainName,
"host_name": v.Hostname,
"ip": v.IP,
"mac": v.MAC,
"type": v.Type,
"vm_id": v.VMID,
}
res = append(res, temp)
}

View File

@@ -38,12 +38,14 @@ import (
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
log "github.com/sirupsen/logrus"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vins"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
"repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
@@ -62,6 +64,19 @@ func resourceStaticRouteCreate(ctx context.Context, d *schema.ResourceData, m in
Gateway: d.Get("gateway").(string),
}
if computesIDS, ok := d.GetOk("compute_ids"); ok {
ids := computesIDS.([]interface{})
res := make([]uint64, 10)
for _, id := range ids {
computeId := uint64(id.(int))
res = append(res, computeId)
}
req.ComputeIds = res
}
_, err := c.CloudBroker().VINS().StaticRouteAdd(ctx, req)
if err != nil {
d.SetId("")
@@ -93,7 +108,30 @@ func resourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m inte
}
func resourceStaticRouteUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
return nil
log.Debugf("resourceStaticRouteUpdate: called for static route id %s", d.Id())
c := m.(*controller.ControllerCfg)
if diags := checkParamsExistenceStaticRoute(ctx, d, c); diags != nil {
return diags
}
staticRouteData, err := utilityDataStaticRouteCheckPresence(ctx, d, m)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
warnings := dc.Warnings{}
if d.HasChange("compute_ids") {
if errs := resourceStaticRouteChangeComputeIds(ctx, d, m, staticRouteData); len(errs) != 0 {
for _, err := range errs {
warnings.Add(err)
}
}
}
return append(warnings.Get(), resourceStaticRouteRead(ctx, d, m)...)
}
func resourceStaticRouteDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
@@ -120,6 +158,61 @@ func resourceStaticRouteDelete(ctx context.Context, d *schema.ResourceData, m in
return nil
}
func resourceStaticRouteChangeComputeIds(ctx context.Context, d *schema.ResourceData, m interface{}, staticRouteData *vins.ItemRoutes) []error {
c := m.(*controller.ControllerCfg)
var errs []error
vinsId := uint64(d.Get("vins_id").(int))
deletedIds := make([]uint64, 0)
addedIds := make([]uint64, 0)
oldComputeIds, newComputeIds := d.GetChange("compute_ids")
oldComputeIdsSlice := oldComputeIds.([]interface{})
newComputeIdsSlice := newComputeIds.([]interface{})
for _, el := range oldComputeIdsSlice {
if !isContainsIds(newComputeIdsSlice, el) {
convertedEl := uint64(el.(int))
deletedIds = append(deletedIds, convertedEl)
}
}
for _, el := range newComputeIdsSlice {
if !isContainsIds(oldComputeIdsSlice, el) {
convertedEl := uint64(el.(int))
addedIds = append(addedIds, convertedEl)
}
}
if len(deletedIds) > 0 {
req := vins.StaticRouteAccessRevokeRequest{
VINSID: vinsId,
RouteId: staticRouteData.ID,
ComputeIds: deletedIds,
}
if _, err := c.CloudBroker().VINS().StaticRouteAccessRevoke(ctx, req); err != nil {
errs = append(errs, err)
}
}
if len(addedIds) > 0 {
req := vins.StaticRouteAccessGrantRequest{
VINSID: vinsId,
RouteId: staticRouteData.ID,
ComputeIds: addedIds,
}
if _, err := c.CloudBroker().VINS().StaticRouteAccessGrant(ctx, req); err != nil {
errs = append(errs, err)
}
}
return errs
}
func isContainsIds(els []interface{}, el interface{}) bool {
convEl := el.(int)
for _, elOld := range els {

View File

@@ -341,10 +341,6 @@ func dataSourceVinsSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "type",
},
"vnc_password": {
Type: schema.TypeString,
Computed: true,
},
"vins": {
Type: schema.TypeList,
Computed: true,
@@ -2513,10 +2509,6 @@ func resourceVinsSchemaMake() map[string]*schema.Schema {
Computed: true,
Description: "type",
},
"vnc_password": {
Type: schema.TypeString,
Computed: true,
},
"vins": {
Type: schema.TypeList,
Computed: true,
@@ -3397,6 +3389,7 @@ func resourceStaticRouteSchemaMake() map[string]*schema.Schema {
"compute_ids": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
},

View File

@@ -43,7 +43,6 @@
- extnet_computes_list
- extnet_default
- extnet_list
- extnet_reserved_ip_list
- flipgroup
- flipgroup_list
- image
@@ -158,7 +157,6 @@
- cb_extnet
- cb_extnet_default
- cb_extnet_list
- cb_extnet_reserved_ip_list
- cb_extnet_static_route
- cb_extnet_static_route_list
- cb_flipgroup
@@ -171,6 +169,7 @@
- cb_grid_list
- cb_grid_list_consumption
- cb_grid_list_emails
- cb_grid_post_diagnosis
- cb_grid_post_status
- cb_image
- cb_image_list

View File

@@ -396,11 +396,6 @@ resource "decort_kvmvm" "comp" {
#тип - булев
pin_to_stack = true
#флаг для старта компьюта при рестарте ноды
#опциональный параметр
#тип - булев
auto_start_w_node = true
#флаг доступности компьюта для проведения с ним операций
#опциональный параметр
#тип - булев

View File

@@ -52,6 +52,12 @@ resource "decort_vins_static_route" "sr" {
#обязательный параметр
#тип - строка
gateway = "192.168.201.40"
#список виртуальных машин, которым будет предоставлен доступ к роуту
#опциональный параметр
#тип - массив целых чисел
compute_ids = [111, 222]
}
output "sr" {

View File

@@ -1,43 +0,0 @@
/*
Пример использования
Получение информации о зарезервированных IP адресах или пуле адресов
*/
#Расскомментируйте этот код,
#и внесите необходимые правки в версию и путь,
#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером
/*
terraform {
required_providers {
decort = {
source = "basis/decort/decort"
version = "<VERSION>"
}
}
}
*/
provider "decort" {
authenticator = "decs3o"
#controller_url = <DECORT_CONTROLLER_URL>
controller_url = "https://ds1.digitalenergy.online"
#oauth2_url = <DECORT_SSO_URL>
oauth2_url = "https://sso.digitalenergy.online"
allow_unverified_ssl = true
}
data "decort_cb_extnet_reserved_ip_list" "ex_reserved_ip" {
#идентификатор аккаунта, для которого зарезервированны ресурсы
#обязательный параметр
#тип - целое число
account_id = 1111
#идентификатор сети
#опциональный параметр
#тип - целое число
#extnet_id = 1111
}
output "test" {
value = data.decort_cb_extnet_reserved_ip_list.ex_reserved_ip
}

View File

@@ -168,26 +168,6 @@ resource "decort_cb_extnet" "new_extnet" {
#e_rate = 0
}
#список зарезервированных IP или пула адресов
#опциональный параметр
#тип - блок
reserved_ip {
#идентификатор аккаунта, для которого резервируются ресурсы
#обязательный параметр
#тип - целое число
account_id = 11111
#количество резервируемых IP
#опциональный параметр
#тип - целое число
ip_count = 15
#список резервируемых IP
#опциональный параметр
#тип - массив строк
ips = ["192.168.10.10", "192.168.10.20"]
}
#ID stack на который происходит миграция
#опциональный параметр
#тип - целое число

View File

@@ -32,10 +32,6 @@ data "decort_cb_grid_get_diagnosis" "grid" {
#тип - целое число
gid = 215
#путь, где будет создан архив, если не указан, создается в директории с main.tf с именем "diagnosis.tar.gz"
#обязательный параметр
#тип - строка
file_path = "abcdefg.tar.gz"
}
output "test" {

View File

@@ -1,6 +1,6 @@
/*
Пример использования
Получение информации о зарезервированных IP адресах или пуле адресов
Получение снимка платформы с дополнительной диагностической информацией, такой как журналы и т.д.
*/
#Расскомментируйте этот код,
@@ -26,18 +26,14 @@ provider "decort" {
allow_unverified_ssl = true
}
data "decort_extnet_reserved_ip_list" "ex_reserved_ip" {
#идентификатор аккаунта, для которого зарезервированны ресурсы
#обязательный параметр
data "decort_cb_grid_post_diagnosis" "grid" {
#id grid для получения информации
#обязательный параметр
#тип - целое число
account_id = 1111
gid = 215
#идентификатор сети
#опциональный параметр
#тип - целое число
#extnet_id = 1111
}
output "test" {
value = data.decort_extnet_reserved_ip_list.ex_reserved_ip
value = data.decort_cb_grid_post_diagnosis.grid
}

View File

@@ -66,21 +66,6 @@ data "decort_cb_kvmvm_list" "compute_list" {
#тип - строка
#ip_address = "test"
#фильтр по stack id
#опциональный параметр
#тип - целое число
#stack_id = 123
#фильтр по image id
#опциональный параметр
#тип - целое число
#image_id = 123
#фильтр по cd image id
#опциональный параметр
#тип - целое число
#cd_image_id = 123
#фильтр по имени extnet
#опциональный параметр
#тип - строка

View File

@@ -409,11 +409,6 @@ resource "decort_cb_kvmvm" "comp" {
#тип - булев
#pin_to_stack = true
#флаг для старта компьюта при рестарте ноды
#опциональный параметр
#тип - булев
#auto_start_w_node = true
#id stack для добавления компьюта на этот стэк
#опциональный параметр
#тип - целое число

View File

@@ -51,6 +51,12 @@ resource "decort_cb_vins_static_route" "sr" {
#обязательный параметр
#тип - строка
gateway = "192.168.201.40"
#список виртуальных машин, которым будет предоставлен доступ к роуту
#опциональный параметр
#тип - массив целых чисел
#compute_ids = [111,222]
}
output "sr" {

1
wiki/.gitignore vendored
View File

@@ -1 +0,0 @@
.idea/

View File

@@ -1,7 +1,7 @@
DECORT Terraform Provider версии 4.8.x позволяет управлять облачными ресурсами на платформе Digital Energy Cloud Orchestration Technology (DECORT) версии 4.2.x и выше посредством Terraform.
DECORT Terraform Provider версии 4.7.x позволяет управлять облачными ресурсами на платформе Digital Energy Cloud Orchestration Technology (DECORT) версии 4.1.x и выше посредством Terraform.
С помощью данного провайдера можно организовать программное управление вычислительными ресурсами (_compute_), ресурсными группами, сетевыми и дисковыми ресурсами, образами дисков, кластером, а также другими параметрами облачной платформы DECORT.
Если вы хорошо знакомы с инструментом Terraform и хотите максимально быстро начать использовать платформу DECORT в своих Terraform-проектах, то можете сразу перейти к разделу [Пример работы](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/02.-Пример-работы.md), где приведён подробно откомментированный пример работы с основными видами ресурсов платформы. Если у вас всё же возникнут вопросы по облачной платформе DECORT и порядку авторизации в ней, то обратитесь к главе [«Обзор облачной платформы DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/03.-Обзор-облачной-платформы-DECORT.md). Также может оказаться полезной глава [«Инициализация Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/04.02-Инициализация-Terraform-провайдера-DECORT.md).
Если вы хорошо знакомы с инструментом Terraform и хотите максимально быстро начать использовать платформу DECORT в своих Terraform-проектах, то можете сразу перейти к разделу [Пример работы](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/02.-Пример-работы.md), где приведён подробно откомментированный пример работы с основными видами ресурсов платформы. Если у вас всё же возникнут вопросы по облачной платформе DECORT и порядку авторизации в ней, то обратитесь к главе [«Обзор облачной платформы DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/03.-Обзор-облачной-платформы-DECORT.md). Также может оказаться полезной глава [«Инициализация Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/04.02-Инициализация-Terraform-провайдера-DECORT.md).
Если вы только начинаете использовать инструмент Terraform и облачную платформу DECORT, то рекомендуем вам начать с главы [«Обзор облачной платформы DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/03.-Обзор-облачной-платформы-DECORT.md), после чего изучить главы [«_Data source_ функции Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/06.-Data-source-функции-Terraform-провайдера-DECORT.md) и [«_Resource_ функции Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/07.-Resource-функции-Terraform-провайдера-DECORT.md). Примеры, приведенные в этих разделах, помогут вам быстро освоить базовые приёмы работы с инструментом Terraform и провайдером DECORT.
Если вы только начинаете использовать инструмент Terraform и облачную платформу DECORT, то рекомендуем вам начать с главы [«Обзор облачной платформы DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/03.-Обзор-облачной-платформы-DECORT.md), после чего изучить главы [«_Data source_ функции Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/06.-Data-source-функции-Terraform-провайдера-DECORT.md) и [«_Resource_ функции Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/07.-Resource-функции-Terraform-провайдера-DECORT.md). Примеры, приведенные в этих разделах, помогут вам быстро освоить базовые приёмы работы с инструментом Terraform и провайдером DECORT.

View File

@@ -10,7 +10,7 @@
Виртуальный сервер - в данном примере на базе системы виртуализации KVM x86 - создаётся посредством _resource_ функции `decort_kvmvm`.
Только авторизованные в контроллере облачной платформы пользователи могут управлять облачными ресурсами. Подробнее о способах авторизации см. [Обзор облачной платформы DECORT](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/03.-Обзор-облачной-платформы-DECORT.md).
Только авторизованные в контроллере облачной платформы пользователи могут управлять облачными ресурсами. Подробнее о способах авторизации см. [Обзор облачной платформы DECORT](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/03.-Обзор-облачной-платформы-DECORT.md).
```terraform
# 1. Initialize DECORT plugin and connection to DECORT cloud controller

View File

@@ -2,7 +2,7 @@
Для запуска провайдера вам потребуется машина, на которой установлен Terraform.
Кроме того, в связи с тем, что начиная с версии 0.12 Terraform изменил алгоритм поиска и инициализации локальных провайдеров, настройка данного провайдера для работы с Terraform 0.12 или более новыми версиями потребует выполнения ряда дополнительных действий. Подробнее см. [8.3 Настройка локального провайдера для работы с новыми версиями Terraform](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/08.-Полезные-советы#user-content-8-3-настройка-локального-провайдера-для-работы-с-новыми-версиями-terraform.md).
Кроме того, в связи с тем, что начиная с версии 0.12 Terraform изменил алгоритм поиска и инициализации локальных провайдеров, настройка данного провайдера для работы с Terraform 0.12 или более новыми версиями потребует выполнения ряда дополнительных действий. Подробнее см. [8.3 Настройка локального провайдера для работы с новыми версиями Terraform](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/08.-Полезные-советы#user-content-8-3-настройка-локального-провайдера-для-работы-с-новыми-версиями-terraform.md).
## Установка
Начиная с версии провайдера `4.3.0` в релизном архиве находятся скрипты-инсталляторы.

View File

@@ -1,7 +1,7 @@
## Список аргументов для инициализации
Перед началом использования любой Terraform провайдер должен быть инициализирован.
В процессе инициализации Terraform провайдера DECORT проверяется корректность переданных аргументов и выполняется авторизация в указанном контроллере облачной инфраструктуры. Подробнее о способах авторизации в платформе DECORT смотри соответствующий [раздел](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/03.-Обзор-облачной-платформы-DECORT#user-content-способы-авторизации.md).
В процессе инициализации Terraform провайдера DECORT проверяется корректность переданных аргументов и выполняется авторизация в указанном контроллере облачной инфраструктуры. Подробнее о способах авторизации в платформе DECORT смотри соответствующий [раздел](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/03.-Обзор-облачной-платформы-DECORT#user-content-способы-авторизации.md).
При инициализации Terraform провайдера DECORT используются следующие аргументы:

View File

@@ -58,7 +58,7 @@ terraform destroy -target <модуль>.<имя-ресурса>
### Пример использования target
В качестве примера возьмем пример конфигурации из [прошлой статьи](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/05.04-Массовое-создание-ресурсов.-Мета-аргументы.md):
В качестве примера возьмем пример конфигурации из [прошлой статьи](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/05.04-Массовое-создание-ресурсов.-Мета-аргументы.md):
```terraform
resource "decort_disk" "disk1" {

View File

@@ -5,11 +5,11 @@ _Data source_ функция **decort_kvmvm** принимает следующ
| Аргумент | Тип | Обязательный | Описание |
| --- | --- | --- | --- |
| compute_id | int | :heavy_check_mark: | Идентификатор экземпляра _compute_, соответствующего данной виртуальной машине (подробнее о понятии _compute_ см. в разделе [Обзор облачной платформы DECORT](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/03.-Обзор-облачной-платформы-DECORT.md)). |
| compute_id | int | :heavy_check_mark: | Идентификатор экземпляра _compute_, соответствующего данной виртуальной машине (подробнее о понятии _compute_ см. в разделе [Обзор облачной платформы DECORT](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/03.-Обзор-облачной-платформы-DECORT.md)). |
Пользователь облачной платформы, от лица которого происходит обращение к данной функции, должен иметь доступ к указанному виртуальному серверу и ресурсной группе. В противном случае возникнет ошибка доступа.
Пользователь облачной платформы задается на стадии инициализации Terraform провайдера DECORT (см. [подробности](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/04.02-Инициализация-Terraform-провайдера-DECORT.md)).
Пользователь облачной платформы задается на стадии инициализации Terraform провайдера DECORT (см. [подробности](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/04.02-Инициализация-Terraform-провайдера-DECORT.md)).
## Возвращаемые значения
В случае успешного выполнения _data source_ функция **decort_kvmvm** возвращает в указанную при вызове переменную следующие значения:
@@ -23,7 +23,6 @@ _Data source_ функция **decort_kvmvm** принимает следующ
| affinity_rules | []Struct [см. ниже](#описание-структуры-affinity-rules) | Правила аффинити для компьютов |
| affinity_weight | int | weight аффинити |
| arch | string | Архитектура |
| auto_start_w_node | bool | Автостарт при рестарте ноды |
| boot_order | []string | Boot order |
| boot_disk_id | int | Идентификатор загрузочного диска виртуальной машины |
| boot_disk_size | int | Размер загрузочного диска в ГБ |
@@ -81,8 +80,7 @@ _Data source_ функция **decort_kvmvm** принимает следующ
| user_managed | bool | User managed |
| pci_devices | []int | Список PCI девайсов |
| userdata | string | Параметры cloud_init |
| vnc_password | string | vnc пароль |
| vgpus | []int | Список vgpu |
| vgpus | []Struct [см. ниже](#описание-структуры-vgpu) | Список vgpu |
| virtual_image_id | int | ID виртуального образа |
| virtual_image_name | string | Имя образа ОС, на базе которого создан загрузочный диск этой виртуальной машины |
@@ -264,6 +262,29 @@ _Data source_ функция **decort_kvmvm** принимает следующ
| label | string | Лейбл |
| timestamp | int | Время |
### Описание структуры vgpu
| Параметр | Тип | Описание |
| --- | --- | --- |
| id | int | Идентификатор ресурса |
| gid | int | ID платформы |
| type | string | Тип |
| mode | string | Режим работы ресурса |
| status | string | Статус ресурса |
| profile_id | int | Идентификатор профиля |
| ram | int | Объем оперативной памяти |
| last_update_time | int | Время последнего обновления |
| created_time | int | Время создания |
| deleted_time | int | Время удаления |
| vmid | int | Идентификатор виртуальной машины |
| pgpuid | int | Идентификатор GPU профиля |
| reference_id | string | Ссылочный идентификатор |
| account_id | int | Идентификатор аккаунта |
| rg_id | int | Идентификатор ресурсной группы |
| last_claimed_by | int | Последний пользователь, запросивший ресурс |
| pci_slot | int | Номер PCI слота |
| bus_number | int | Номер шины |
| guid | int | GUID |
## Пример использования
В нижеприведённом примере посредством вызова _data source_ функции **decort_kvmvm** извлекается информация об уже существующем в платформе виртуальном сервере со следующими характеристиками:
* Имя сервера _MyOldVM_;
@@ -279,9 +300,9 @@ data "decort_kvmvm" "comp" {
}
```
Данный пример подразумевает, что ранее по тексту tf-файла выполнена корректная инициализация провайдера (подробнее об инициализации Terraform провайдера DECORT см. соответствующий [раздел](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/04.02-Инициализация-Terraform-провайдера-DECORT.md)).
Данный пример подразумевает, что ранее по тексту tf-файла выполнена корректная инициализация провайдера (подробнее об инициализации Terraform провайдера DECORT см. соответствующий [раздел](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/04.02-Инициализация-Terraform-провайдера-DECORT.md)).
Чтобы получить идентификатор ресурсной группы (аргумент `rg_id`), можно воспользоваться _data source_ функцией [decort_resgroup](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.8.0/06.01.12-Data_decort_rg_list.md).
Чтобы получить идентификатор ресурсной группы (аргумент `rg_id`), можно воспользоваться _data source_ функцией [decort_resgroup](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.7.4/06.01.12-Data_decort_rg_list.md).
После успешного завершения такого вызова **decort_kvmvm** в переменной `data.decort_kvmvm.comp` будут сохранены возвращаемые значения. Так, например:
* пароль для доступа в гостевую ОС, назначенный по умолчанию при создании VM - `"data.decort_kvmvm.comp.os_users.0.password`

Some files were not shown because too many files have changed in this diff Show More