diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bda6e8..765ecda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,31 +1,128 @@ -## Version 4.5.3 - -### Bugfix -- Change field Value in schema resource kvmvm in blocks affinity_rules and anti_affinity_rules from required to optional in cloudapi and cloudbroker -- Change the format ID in resource k8s_wg from wg_id to k8s_id#wg_id -- Fix scripts intall.bat and intall.sh -- Increased timeouts for resources account, disk, cdrom_image, image, virtual_image, k8s_wg, vins, rg in cloudbroker so that they match the same from cloudapi -- Increased timeouts for resources pcidevice, sep, sep_config in cloudbroker -- Fix bug in affinity_rules in cloudbroker/kvmvm -- Add field NeedReboot in cloudapi/kvmvm in data_source, data_source_list and resource schemas -- Fix bug with field ExtNetID in CreateInRGRequest in cloudapi/vins and cloudbroker/vins -- Add boolean field Safe in Restart func in resource cloudapi/lb -- Add field force_resize in Resize func in resource cloudapi/kvmvm and cloudbroker/kvmvm -- Fix bug in cloudBroker/kvmvm with disk and extra_disks -- Change logic from disk delete and disk add to disk rename when disk.disk_name field is changed in resource cloudapi/kvmvm and cloudbroker/kvmvm -- Fix allowed network plugin value from "weawenet" to "weavenet" for k8ci, k8s resources in cloudbroker and for k8s resource in cloudapi -- Fix bug with deleting decort_bservice resource when setting enable=false in cloudapi/bservice -- Fix panic in data source decort_bservice_snapshot_list in cloudapi/bservice -- Fix panic in data source decort_rg_affinity_groups_list in cloudapi/rg -- Fix change description in resource decort_cb_kvmvm in cloudbroker -- Computed field bootdisk_size has been renamed to boot_disk_size in data sources decort_kvmvm, decort_kvmvm_list, decort_cb_kvmvm_list in cloudapi and cloudbroker -- Change request logic for delete resource decort_cb_k8s_cp in cloudbroker -- Fix schema in datasource decort_cb_kvmvm in cloudbroker, fields boot_disk_id, sep_id, pool, extra_disks, network, net_id, net_type, ip_address, mac have been removes -- Fix panic with RG in cloudapi -- Fix permanently field for disks delete in decort_kvmvm in cloudapi/kvmvm and decort_cb_kvmvm in cloudbroker/kvmvm -- Fix bug with enable request duplication +## Version 4.6.0 ### Feature -- Add RAM divisibility validation in compute, k8s, k8s_cp and k8s_wg resources in cloudapi and cloudbroker -- Add "permanently" flag in k8s, k8s_cp in cloudapi \ No newline at end of file +#### general +- Add sort_by optional string field for the below data sources in cloudapi and cloudbroker: + +| group | cloudapi data sources | cloudbroker data sources | +|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| account | decort_account_computes_list
decort_account_deleted_list
decort_account_disks_list
decort_account_list
decort_account_rg_list
decort_account_templates_list
decort_account_vins_list | decort_cb_account_computes_list
decort_cb_account_disks_list
decort_cb_account_flipgroups_list
decort_cb_account_list
decort_cb_account_list_deleted
decort_cb_account_rg_list
decort_cb_account_vins_list | +| audit | - | decort_cb_audit_list | +| bservice | decort_bservice_deleted_list
decort_bservice_list | - | +| disk | decort_disk_list
decort_disk_list_types
decort_disk_list_types_detailed
decort_disk_list_unattached
decort_disk_list_deleted | decort_cb_disk_list
decort_cb_disk_list_deleted
decort_cb_disk_list_types
decort_cb_disk_list_types_detailed
decort_cb_disk_list_unattached | +| extnet | decort_extnet_computes_list
decort_extnet_list | decort_cb_extnet_list | +| flipgroup | decort_flipgroup_list | decort_cb_flipgroup_list | +| grid | - | decort_cb_grid_list | +| image | decort_image_list | decort_cb_image_list
decort_cb_image_list_stacks | +| k8ci | decort_k8ci_list | decort_cb_k8ci_list
decort_cb_k8ci_list_deleted | +| k8s | decort_k8s_list
decort_k8s_list_deleted | decort_cb_k8s_list
decort_cb_k8s_list_deleted | +| kvmvm | decort_kvmvm_list
decort_kvmvm_list_deleted
decort_kvmvm_pci_device_list
decort_kvmvm_vgpu_list | decort_cb_kvmvm_list
decort_cb_kvmvm_list_deleted
decort_cb_kvmvm_pci_device_list
decort_cb_kvmvm_vgpu_list | +| lb | decort_lb_list
decort_lb_list_deleted | decort_cb_lb_list
decort_cb_lb_list_deleted | +| locations | decort_locations_list | - | +| rg | decort_rg_list
decort_rg_list_computes
decort_rg_list_deleted
decort_rg_list_lb
decort_rg_list_vins | decort_cb_rg_list
decort_cb_rg_list_computes
decort_cb_rg_list_deleted
decort_cb_rg_list_lb
decort_cb_rg_list_vins | +| sep | - | decort_cb_sep_list | +| stack | decort_stack_list | decort_cb_stack_list | +| vfpool | decort_vfpool_list | decort_cb_vfpool_list | +| vins | decort_vins_list
decort_vins_list_deleted | decort_cb_vins_list
decort_cb_vins_list_deleted | + +#### account: +- Add available_templates optional field to resource decort_cb_account in cloudbroker/account +- Add data source decort_cb_account_available_templates_list in cloudbroker/account +- Add compute_features computed fields to data sources decort_account, decort_account_list, decort_account_deleted_list, decort_cb_account, decort_cb_account_list, decort_account_deleted_list and to resource decort_account in cloudapi/account and cloudbroker/account +- Add compute_features optional field to resource decort_cb_account in cloudbroker/account +- Add extnet_id, free_ips computed fields to data sources decort_account_vins_list and decort_cb_account_vins_list in cloudapi/account and cloudbroker/account + +#### audit: +- Add guid computed field to data source decort_cb_audit_linked_jobs in cloudbroker/audit +- Delete field status_code in data source decort_cb_audit_list in cloudbroker/audit +- Add fields min_status_code and max_status_code in data source decort_cb_audit_list in cloudbroker/audit + +#### bservice: +- Add validation of ram to be divisible by 128 to resource decort_bservice_group in cloudapi/bservice + +#### disks: +- Add resource and data source decort_disk_replication and decort_cb_disk_replication +- Add field replication in data sources and resource decort_disk, decort_disk_list, decort_disk_list_deleted, decort_cb_disk, decort_cb_disk_list, decort_cb_disk_list_deleted +- Add node_ids optional field to resource decort_cb_disk in cloudbroker/disk + +#### flipgroup: +- Add conn_id, status and account_id optional fields to data sources decort_flipgroup_list and decort_cb_flipgroup_list in cloudapi/flipgroup and cloudbroker/flipgroup +- Add client_ids optional fields to data sources decort_flipgroup_list and decort_cb_flipgroup_list in cloudapi/flipgroup and cloudbroker/flipgroup + +#### kvmvm: +- Add cd_image_id computed field to data sources decort_kvmvm, decort_kvmvm_list, decort_cb_kvmvm, decort_cb_kvmvm_list and resourced decort_kvmvm, decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add natable_vins_id, natable_vins_ip, natable_vins_name, natable_vins_network and natable_vins_network_name computed fields to data source decort_cb_kvmvm and to resource decort_cb_kvmvm in cloudbroker/kvmvm +- Change field local_port (in block port_forwarding) from required to optional in resources decort_kvmvm and decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add hp_backed, cpu_pin, numa_affinity and numa_node_id computed fields to data sources decort_kvmvm, decort_kvmvm_list, decort_cb_kvmvm, decort_cb_kvmvm_list in cloudapi/kvmvm and cloudbroker/kvmvm +- Add hp_backed, cpu_pin, numa_affinity optional fields and numa_node_id computed field to resources decort_kvmvm, decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add validation of ram to be divisible by 128 to resources decort_kvmvm and decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add name optional field to data source decort_cb_kvmvm_pci_device_list in cloudbroker/kvmvm +- Add fields image_name and virtual_image_name in resource and data source decort_cb_kvmvm in cloudbroker/kvmvm +- Add fields enabled and node_id in resource and data sources decort_cb_kvmvm, decort_cb_kvmvm_list, decort_cb_kvmvm_list_deleted in cloudbroker/kvmvm. Add field node_id in resource and data sources decort_kvmvm, decort_kvmvm_list, decort_kvmvm_list_deleted in cloudapi/kvmvm +- Delete network and extra_disk fields in data source decort_cb_kvmvm in cloudbroker/kvmvm +- Add computed fields compute_id, description, guid, hwpath, device_id, name, rg_id, stack_id, status, system_name in data source decort_kvmvm_pci_device_list in cloudapi/kvmvm +- Add computed fields account_id, created_time, deleted_time, gid, guid, vgpu_id, last_claimed_by, last_update_time, mode, pci_slot, pgpuid, profile_id, ram, reference_id, rg_id, status, type, vm_id in data sources decort_kvmvm_vgpu_list and decort_cb_kvmvm_vgpu_list in cloudapi/kvmvm and cloudbroker/kvmvm +- Add field replication (disk_id, pool_id, role, self_volume_id, storage_id, volume_id) in data source decort_kvmvm, decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add computed field reserved_node_cpus in data sources decort_kvmvm, decort_kvmvm_list, decort_kvmvm_list_deleted, decort_cb_kvmvm, decort_cb_kvmvm_list, decort_cb_kvmvm_list_deleted and in resources decort_kvmvm, decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add "VFNIC" as allowed net_type value in network block for resources decort_kvmvm and decort_cb_kvmvm (created with "KVM_X86" driver) in cloudapi/kvmvm and cloudbroker/kvmvm +- Set optional field image_id in resource decort_kvmvm, decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add optional field without_boot_disk in resource decort_kvmvm, decort_cb_kvmvm in cloudapi/kvmvm and cloudbroker/kvmvm +- Add optional fields depresent, node_ids in resource decort_cb_kvmvm in cloudbroker/kvmvm + +#### image: +- Add cd_presented_to computed field to data sources decort_image, decort_cb_image and to resources decort_image, decort_cb_image in cloudapi/image and cloudbroker/image +- Add account_id required field to resource decort_image in cloudapi/image +- Add accounts optional field to resource decort_cb_image in cloudbroker/image +- Add network_interface_naming computed field to data sources decort_image, decort_image_list, decort_cb_image, decort_cb_image_list and to resources decort_image, decort_cb_image in cloudapi/image and cloudbroker/image +- Delete gid required field from resource decort_image in cloudapi/image +- Delete meta and ckey computed fields from data sources and resource decort_cb_image and decort_cb_image_list in cloudbroker/image +- Add resource decort_image_from_blank_compute and decort_cb_image_from_blank_compute in cloudapi/compute and cloudbroker/compute +- Add resource decort_image_from_platoform_disk and decort_cb_image_from_platoform_disk in cloudapi/compute and cloudbroker/compute +- Add file_path optional field to resource decort_cb_image in cloudbroker/image +- Сhanged url field from required to optional in resource decort_cb_image in cloudbroker/image + +#### k8s: +- Change lb_sysctl_params optional field from string to array in resources decort_k8s and decort_k8s_cp in cloudapi/k8s +- Add lb_sysctl_params optional field to resource decort_cb_k8s_cp in cloudbroker/k8s +- Add validation of ram to be divisible by 128 to resources decort_k8s, decort_k8s_cp, decort_k8s_wg, decort_cb_k8s_cp and decort_cb_k8s_wg in cloudapi/k8s and cloudbroker/k8s +- Change possible values num field (can be 5) in resources decort_k8s(cloudapi/k8s), decort_k8s_cp(cloudapi/k8s) and decort_cb_k8s_cp(cloudbroker/k8s) + +#### lb: +- Add user_managed, manager_id, manager_type and part_k8s computed fields to data sources decort_lb, decort_lb_list, decort_cb_lb, decort_cb_lb_list and to resources decort_lb, decort_cb_lb in cloudapi/lb and cloudbroker/lb +- Add sysctl_params optional field to resources decort_lb and decort_cb_lb in cloudapi/lb and cloudbroker/lb +- Add safe optional field to resource decort_cb_lb in cloudbroker/lb + +#### node: +- Add data sources decort_cb_node and decort_cb_node_list in cloudbroker/node + +#### rg: +- Add compute_features computed fields to data sources decort_resgroup, decort_rg_list, decort_rg_list_deleted, decort_cb_rg, decort_cb_rg_list, decort_cb_rg_list_deleted and to resource decort_resgroup in clouapi/rg and cloudbroker/rg +- Add compute_features optional field to resource decort_cb_rg in cloudbroker/rg +- Add extnet_id, free_ips computed fields to data sources decort_rg_vins_list and decort_cb_rg_vins_list in cloudapi/rg and cloudbroker/rg +- Change resource quota handling logic in cloudapi to be like cloudbroker's. Added "cu_d" field into cloudapi resource quota schema. Deleted default values of "cpu", "ram", "disk", "ext_traffic", "ext_ips" and "gpu_units" fields in cloudapi resource schema + +#### sep: +- Add pools optional field to resource decort_cb_sep in cloudbroker/sep +- Change config field from optional to required in resource decort_cb_sep in cloudbroker/sep + +#### user: +- Add data sources decort_cb_user, decort_cb_user_list and decort_cb_user_get_audit in cloudbroker/user +- Add resource decort_cb_user in cloudbroker/user + +#### vfpool: +- Add data sources decort_vfpool, decort_vfpool_list and decort_cb_vfpool, decort_cb_vfpool_list in cloudapi/vfpool and cloudbroker/vfpool +- Add resource decort_cb_vfpool in cloudbroker/vfpool + +#### vins: +- Change field int_port (in block nat_rule) from required to optional in resource decort_cb_vins in cloudbroker/vins +- Add extnet_id, free_ips computed fields to data sources decort_vins_list, decort_cb_vins_list in cloudapi/vins and cloudbroker/vins +- Add dns optional field to resources decort_vins and decort_cb_vins in cloudapi/vins and cloudbroker/vins +- Add node_id computed field to resources and data sources decort_vins and decort_cb_vins in cloudapi/vins and cloudbroker/vins +- Add vnfdev_id optional field to data sources decort_cb_vins_list in cloudbroker/vins +- Add vnfdev_id optional field to data sources decort_vins_list_deleted in cloudapi/vins + +### Bugfix +- Fix boot_disk_size field to be saved correctly in state in order to stop unnecessary resource update attempts after `terraform apply` in resource decort_cb_kvmvm in cloudbroker/kvmvm +- Rename computed field name to k8s_name in order to fix state in data source decort_k8s_list_deleted in cloudapi/k8s +- Delete account_id field in data sources decort_rg_list_lb and decort_cb_rg_list_lb in cloudapi/rg and cloubroker/rg diff --git a/Makefile b/Makefile index 39fa310..2c87f4c 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ ZIPDIR = ./zip BINARY=${NAME} WORKPATH= ./examples/terraform.d/plugins/${HOSTNAME}/${NAMESPACE}/${NAMESPACE}/${VERSION}/${OS_ARCH} MAINPATH = ./cmd/decort/ -VERSION=4.5.3 +VERSION=4.6.0 OS_ARCH=$(shell go env GOHOSTOS)_$(shell go env GOHOSTARCH) FILES = ${BINARY}_${VERSION}_darwin_amd64\ diff --git a/README.md b/README.md index efa48f5..fab546b 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ Terraform provider для платформы Digital Energy Cloud Orchestration | Версия DECORT API | Версия провайдера Terraform | | ------ | ------ | +| 4.4.0 | 4.6.x | | 3.8.9 | 4.5.x | | 3.8.8 | 4.4.x | | 3.8.7 | 4.3.x | @@ -59,6 +60,7 @@ Terraform provider для платформы Digital Energy Cloud Orchestration - Работа с pci device, - Работа с resource groups, - Работа с seps, + - Работа с user, - Работа с stacks, - Работа с VINS. diff --git a/go.mod b/go.mod index 6b2c091..01ccbdc 100644 --- a/go.mod +++ b/go.mod @@ -1,27 +1,27 @@ module repository.basistech.ru/BASIS/terraform-provider-decort -go 1.18 +go 1.20 require ( - github.com/google/uuid v1.3.0 + github.com/google/uuid v1.4.0 github.com/hashicorp/terraform-plugin-docs v0.13.0 - github.com/hashicorp/terraform-plugin-sdk/v2 v2.30.0 + github.com/hashicorp/terraform-plugin-sdk/v2 v2.33.0 github.com/sirupsen/logrus v1.9.0 - golang.org/x/net v0.17.0 - repository.basistech.ru/BASIS/decort-golang-sdk v1.7.7 + golang.org/x/net v0.19.0 + repository.basistech.ru/BASIS/decort-golang-sdk v1.8.1 ) require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.2.0 // indirect github.com/Masterminds/sprig/v3 v3.2.3 // indirect - github.com/ProtonMail/go-crypto v0.0.0-20230828082145-3c4c8a2d2371 // indirect + github.com/ProtonMail/go-crypto v1.1.0-alpha.0 // indirect github.com/agext/levenshtein v1.2.3 // indirect github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/armon/go-radix v1.0.0 // indirect github.com/bgentry/speakeasy v0.1.0 // indirect - github.com/cloudflare/circl v1.3.3 // indirect - github.com/fatih/color v1.13.0 // indirect + github.com/cloudflare/circl v1.3.7 // indirect + github.com/fatih/color v1.16.0 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect @@ -35,24 +35,24 @@ require ( github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-plugin v1.5.1 // indirect + github.com/hashicorp/go-plugin v1.6.0 // indirect github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/go-version v1.6.0 // indirect - github.com/hashicorp/hc-install v0.6.1 // indirect + github.com/hashicorp/hc-install v0.6.3 // indirect github.com/hashicorp/hcl/v2 v2.19.1 // indirect github.com/hashicorp/logutils v1.0.0 // indirect - github.com/hashicorp/terraform-exec v0.19.0 // indirect - github.com/hashicorp/terraform-json v0.17.1 // indirect - github.com/hashicorp/terraform-plugin-go v0.19.0 // indirect + github.com/hashicorp/terraform-exec v0.20.0 // indirect + github.com/hashicorp/terraform-json v0.21.0 // indirect + github.com/hashicorp/terraform-plugin-go v0.22.0 // indirect github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect - github.com/hashicorp/terraform-registry-address v0.2.2 // indirect + github.com/hashicorp/terraform-registry-address v0.2.3 // indirect github.com/hashicorp/terraform-svchost v0.1.1 // indirect github.com/hashicorp/yamux v0.1.1 // indirect github.com/huandu/xstrings v1.4.0 // indirect github.com/imdario/mergo v0.3.15 // indirect github.com/leodido/go-urn v1.2.4 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.16 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/cli v1.1.5 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect @@ -65,16 +65,16 @@ require ( github.com/shopspring/decimal v1.3.1 // indirect github.com/spf13/cast v1.5.0 // indirect github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect - github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect + github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect - github.com/zclconf/go-cty v1.14.1 // indirect - golang.org/x/crypto v0.15.0 // indirect - golang.org/x/mod v0.13.0 // indirect - golang.org/x/sys v0.14.0 // indirect + github.com/zclconf/go-cty v1.14.2 // indirect + golang.org/x/crypto v0.19.0 // indirect + golang.org/x/mod v0.15.0 // indirect + golang.org/x/sys v0.17.0 // indirect golang.org/x/text v0.14.0 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 // indirect - google.golang.org/grpc v1.57.1 // indirect - google.golang.org/protobuf v1.31.0 // indirect + google.golang.org/appengine v1.6.8 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect + google.golang.org/grpc v1.61.1 // indirect + google.golang.org/protobuf v1.32.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index d1db9a1..ce4a1e6 100644 --- a/go.sum +++ b/go.sum @@ -8,9 +8,8 @@ github.com/Masterminds/sprig/v3 v3.2.1/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFP github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= -github.com/ProtonMail/go-crypto v0.0.0-20230828082145-3c4c8a2d2371 h1:kkhsdkhsCvIsutKu5zLMgWtgh9YxGCNAw8Ad8hjwfYg= -github.com/ProtonMail/go-crypto v0.0.0-20230828082145-3c4c8a2d2371/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0= -github.com/acomagu/bufpipe v1.0.4 h1:e3H4WUzM3npvo5uv95QuJM3cQspFNtFBzvJ2oNjKIDQ= +github.com/ProtonMail/go-crypto v1.1.0-alpha.0 h1:nHGfwXmFvJrSR9xu8qL7BkO4DqTHXE9N5vPhgY2I+j0= +github.com/ProtonMail/go-crypto v1.1.0-alpha.0/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE= github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= @@ -22,23 +21,23 @@ github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgI github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= -github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= -github.com/cloudflare/circl v1.3.3 h1:fE/Qz0QdIGqeWfnwq0RE0R7MI51s0M2E4Ga9kq5AEMs= -github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= +github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= +github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= +github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= +github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= github.com/go-git/go-billy/v5 v5.5.0 h1:yEY4yhzCDuMGSv83oGxiBotRzhwhNr8VZyphhiu+mTU= -github.com/go-git/go-git/v5 v5.9.0 h1:cD9SFA7sHVRdJ7AYck1ZaAa/yeuBvGPxwXDL8cxrObY= +github.com/go-git/go-git/v5 v5.11.0 h1:XIZc1p+8YzypNr34itUfSvYJcv+eYdTnTvOZ2vD3cA4= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= @@ -49,8 +48,8 @@ github.com/go-playground/validator/v10 v10.15.4/go.mod h1:9iXMNT7sEkjXb0I+enO7QX github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -62,8 +61,8 @@ github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -79,33 +78,33 @@ github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVH github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.5.1 h1:oGm7cWBaYIp3lJpx1RUEfLWophprE2EV/KUeqBYo+6k= -github.com/hashicorp/go-plugin v1.5.1/go.mod h1:w1sAEES3g3PuV/RzUrgow20W2uErMly84hhD3um1WL4= +github.com/hashicorp/go-plugin v1.6.0 h1:wgd4KxHJTVGGqWBq4QPB1i5BZNEx9BR8+OFmHDmTk8A= +github.com/hashicorp/go-plugin v1.6.0/go.mod h1:lBS5MtSSBZk0SHc66KACcjjlU6WzEVP/8pwz68aMkCI= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/hc-install v0.6.1 h1:IGxShH7AVhPaSuSJpKtVi/EFORNjO+OYVJJrAtGG2mY= -github.com/hashicorp/hc-install v0.6.1/go.mod h1:0fW3jpg+wraYSnFDJ6Rlie3RvLf1bIqVIkzoon4KoVE= +github.com/hashicorp/hc-install v0.6.3 h1:yE/r1yJvWbtrJ0STwScgEnCanb0U9v7zp0Gbkmcoxqs= +github.com/hashicorp/hc-install v0.6.3/go.mod h1:KamGdbodYzlufbWh4r9NRo8y6GLHWZP2GBtdnms1Ln0= github.com/hashicorp/hcl/v2 v2.19.1 h1://i05Jqznmb2EXqa39Nsvyan2o5XyMowW5fnCKW5RPI= github.com/hashicorp/hcl/v2 v2.19.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/terraform-exec v0.19.0 h1:FpqZ6n50Tk95mItTSS9BjeOVUb4eg81SpgVtZNNtFSM= -github.com/hashicorp/terraform-exec v0.19.0/go.mod h1:tbxUpe3JKruE9Cuf65mycSIT8KiNPZ0FkuTE3H4urQg= -github.com/hashicorp/terraform-json v0.17.1 h1:eMfvh/uWggKmY7Pmb3T85u86E2EQg6EQHgyRwf3RkyA= -github.com/hashicorp/terraform-json v0.17.1/go.mod h1:Huy6zt6euxaY9knPAFKjUITn8QxUFIe9VuSzb4zn/0o= +github.com/hashicorp/terraform-exec v0.20.0 h1:DIZnPsqzPGuUnq6cH8jWcPunBfY+C+M8JyYF3vpnuEo= +github.com/hashicorp/terraform-exec v0.20.0/go.mod h1:ckKGkJWbsNqFKV1itgMnE0hY9IYf1HoiekpuN0eWoDw= +github.com/hashicorp/terraform-json v0.21.0 h1:9NQxbLNqPbEMze+S6+YluEdXgJmhQykRyRNd+zTI05U= +github.com/hashicorp/terraform-json v0.21.0/go.mod h1:qdeBs11ovMzo5puhrRibdD6d2Dq6TyE/28JiU4tIQxk= github.com/hashicorp/terraform-plugin-docs v0.13.0 h1:6e+VIWsVGb6jYJewfzq2ok2smPzZrt1Wlm9koLeKazY= github.com/hashicorp/terraform-plugin-docs v0.13.0/go.mod h1:W0oCmHAjIlTHBbvtppWHe8fLfZ2BznQbuv8+UD8OucQ= -github.com/hashicorp/terraform-plugin-go v0.19.0 h1:BuZx/6Cp+lkmiG0cOBk6Zps0Cb2tmqQpDM3iAtnhDQU= -github.com/hashicorp/terraform-plugin-go v0.19.0/go.mod h1:EhRSkEPNoylLQntYsk5KrDHTZJh9HQoumZXbOGOXmec= +github.com/hashicorp/terraform-plugin-go v0.22.0 h1:1OS1Jk5mO0f5hrziWJGXXIxBrMe2j/B8E+DVGw43Xmc= +github.com/hashicorp/terraform-plugin-go v0.22.0/go.mod h1:mPULV91VKss7sik6KFEcEu7HuTogMLLO/EvWCuFkRVE= github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= github.com/hashicorp/terraform-plugin-log v0.9.0/go.mod h1:rKL8egZQ/eXSyDqzLUuwUYLVdlYeamldAHSxjUFADow= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.30.0 h1:X7vB6vn5tON2b49ILa4W7mFAsndeqJ7bZFOGbVO+0Cc= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.30.0/go.mod h1:ydFcxbdj6klCqYEPkPvdvFKiNGKZLUs+896ODUXCyao= -github.com/hashicorp/terraform-registry-address v0.2.2 h1:lPQBg403El8PPicg/qONZJDC6YlgCVbWDtNmmZKtBno= -github.com/hashicorp/terraform-registry-address v0.2.2/go.mod h1:LtwNbCihUoUZ3RYriyS2wF/lGPB6gF9ICLRtuDk7hSo= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.33.0 h1:qHprzXy/As0rxedphECBEQAh3R4yp6pKksKHcqZx5G8= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.33.0/go.mod h1:H+8tjs9TjV2w57QFVSMBQacf8k/E1XwLXGCARgViC6A= +github.com/hashicorp/terraform-registry-address v0.2.3 h1:2TAiKJ1A3MAkZlH1YI/aTVcLZRu7JseiXNRHbOAyoTI= +github.com/hashicorp/terraform-registry-address v0.2.3/go.mod h1:lFHA76T8jfQteVfT7caREqguFrW3c4MFSPhZB7HHgUM= github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ= github.com/hashicorp/terraform-svchost v0.1.1/go.mod h1:mNsjQfZyf/Jhz35v6/0LWcv26+X7JPS+buii2c9/ctc= github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= @@ -137,8 +136,9 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mitchellh/cli v1.1.5 h1:OxRIeJXpAMztws/XHlN2vu6imG5Dpq+j61AzAX5fLng= github.com/mitchellh/cli v1.1.5/go.mod h1:v8+iFts2sPIKUV1ltktPXMCC8fumSKFItNcD2cLtRR4= github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= @@ -170,7 +170,7 @@ github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5g github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/skeema/knownhosts v1.2.0 h1:h9r9cf0+u7wSE+M183ZtMGgOJKiL96brpaz5ekfJCpM= +github.com/skeema/knownhosts v1.2.1 h1:SHWdIUa82uGZz+F+47k8SY4QhhI291cXCpopT1lK2AQ= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= @@ -190,41 +190,34 @@ github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU= -github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= +github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= +github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/zclconf/go-cty v1.14.1 h1:t9fyA35fwjjUMcmL5hLER+e/rEPqrbCK1/OSE4SI9KA= -github.com/zclconf/go-cty v1.14.1/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= +github.com/zclconf/go-cty v1.14.2 h1:kTG7lqmBou0Zkx35r6HJHUQTvaRPr5bIAf3AoHS0izI= +github.com/zclconf/go-cty v1.14.2/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200414173820-0848c9571904/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= -golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA= -golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g= +golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY= -golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= -golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= +golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -239,43 +232,37 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= -golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 h1:0nDDozoAU19Qb2HwhXadU8OcsiO/09cnTqhUtq2MEOM= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA= -google.golang.org/grpc v1.57.1 h1:upNTNqv0ES+2ZOOqACwVtS3Il8M12/+Hz41RCPzAjQg= -google.golang.org/grpc v1.57.1/go.mod h1:Sd+9RMTACXwmub0zcNY2c4arhtrbBYD1AUHI/dt16Mo= +google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 h1:Jyp0Hsi0bmHXG6k9eATXoYtjd6e2UzZ1SCn/wIupY14= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:oQ5rr10WTTMvP4A36n8JpR1OrO1BEiV4f78CneXZxkA= +google.golang.org/grpc v1.61.1 h1:kLAiWrZs7YeDM6MumDe7m3y4aM6wacLzM1Y/wiLP9XY= +google.golang.org/grpc v1.61.1/go.mod h1:VUbo7IFqmF1QtCAstipjG0GIoq49KvMe9+h1jFLBNJs= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= +google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -285,5 +272,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.7.7 h1:VIF+NXXfYec8DtlTcPae+CjB0fhH8ovBQxKMwEnLgE8= -repository.basistech.ru/BASIS/decort-golang-sdk v1.7.7/go.mod h1:7fj8sgGZFiiExewQeqckCS4WxwOmU0oP6BO6mi1Lpkw= +repository.basistech.ru/BASIS/decort-golang-sdk v1.8.1 h1:wpxjnVO7hGaQVWbtFoYVbNoeFxk0QUnEfDsPuWjiNk0= +repository.basistech.ru/BASIS/decort-golang-sdk v1.8.1/go.mod h1:OaUynHHuSjWMzpfyoL4au6oLcUogqUkPPBKA15pbHWo= diff --git a/internal/constants/constants.go b/internal/constants/constants.go index afa5779..e712480 100644 --- a/internal/constants/constants.go +++ b/internal/constants/constants.go @@ -20,23 +20,23 @@ limitations under the License. package constants -// LimitMaxVinsPerResgroup set maximum number of VINs instances per Resource Group -const LimitMaxVinsPerResgroup = 4 +// LIMIT_MAX_VINS_PER_RESGROUP set maximum number of VINs instances per Resource Group +const LIMIT_MAX_VINS_PER_RESGROUP = 4 -// MaxSshKeysPerCompute sets maximum number of user:ssh_key pairs to authorize when creating new compute -const MaxSshKeysPerCompute = 12 +// MAX_SSHKEYS_PER_COMPUTE sets maximum number of user:ssh_key pairs to authorize when creating new compute +const MAX_SSHKEYS_PER_COMPUTE = 12 -// MaxExtraDisksPerCompute sets maximum number of extra disks that can be added when creating new compute -const MaxExtraDisksPerCompute = 12 +// MAX_EXTRA_DISKS_PER_COMPUTE sets maximum number of extra disks that can be added when creating new compute +const MAX_EXTRA_DISKS_PER_COMPUTE = 12 -// MaxNetworksPerCompute sets maximum number of vNICs per compute -const MaxNetworksPerCompute = 8 +// MAX_NETWORKS_PER_COMPUTE sets maximum number of vNICs per compute +const MAX_NETWORKS_PER_COMPUTE = 8 -// MaxCpusPerCompute sets maximum number of vCPUs per compute -const MaxCpusPerCompute = 128 +// MAX_CPUS_PER_COMPUTE sets maximum number of vCPUs per compute +const MAX_CPUS_PER_COMPUTE = 128 -// MinRamPerCompute sets minimum amount of RAM per compute in MB -const MinRamPerCompute = 128 +// MIN_RAM_PER_COMPUTE sets minimum amount of RAM per compute in MB +const MIN_RAM_PER_COMPUTE = 128 -// RAMDivisibility sets divisibility of RAM value -const RAMDivisibility = 128 +// RAM_DIVISIBILITY sets divisibility of RAM value +const RAM_DIVISIBILITY = 128 diff --git a/internal/location/api.go b/internal/location/api.go index d8c40a1..e78743c 100644 --- a/internal/location/api.go +++ b/internal/location/api.go @@ -1,23 +1,23 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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. -*/ - -package location - -const LocationsListAPI = "/restmachine/cloudapi/locations/list" // Returns list of GridRecord on success +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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. +*/ + +package location + +const LOCATIONS_LIST_API = "/restmachine/cloudapi/locations/list" // Returns list of GridRecord on success diff --git a/internal/provider/data_sources_map.go b/internal/provider/data_sources_map.go index be4e279..353db7d 100644 --- a/internal/provider/data_sources_map.go +++ b/internal/provider/data_sources_map.go @@ -35,6 +35,7 @@ import ( "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/rg" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/snapshot" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/stack" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/vfpool" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudapi/vins" cb_account "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/account" @@ -44,17 +45,19 @@ import ( cb_flipgroup "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/flipgroup" cb_grid "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/grid" cb_image "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/image" + cb_k8ci "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/k8ci" + cb_k8s "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/k8s" cb_kvmvm "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/kvmvm" cb_lb "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/lb" + cb_node "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/node" cb_pcidevice "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/pcidevice" cb_rg "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/rg" cb_sep "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/sep" cb_stack "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/stack" + cb_user "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/user" + cb_vfpool "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/vfpool" cb_vins "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/vins" - // cb_vgpu "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/vgpu" - cb_k8ci "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/k8ci" - cb_k8s "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/k8s" ) func newDataSourcesMap() map[string]*schema.Resource { @@ -106,6 +109,7 @@ func newDataSourcesMap() map[string]*schema.Resource { "decort_disk_list_unattached": disks.DataSourceDiskListUnattached(), "decort_disk_snapshot": disks.DataSourceDiskSnapshot(), "decort_disk_snapshot_list": disks.DataSourceDiskSnapshotList(), + "decort_disk_replication": disks.DataSourceDiskReplication(), "decort_account_list": account.DataSourceAccountList(), "decort_account_computes_list": account.DataSourceAccountComputesList(), "decort_account_disks_list": account.DataSourceAccountDisksList(), @@ -138,6 +142,8 @@ func newDataSourcesMap() map[string]*schema.Resource { "decort_flipgroup_list": flipgroup.DataSourceFlipGroupList(), "decort_stack": stack.DataSourceStack(), "decort_stack_list": stack.DataSourceStackList(), + "decort_vfpool": vfpool.DataSourceVFPool(), + "decort_vfpool_list": vfpool.DataSourceVFPoolList(), "decort_account_resource_consumption_list": account.DataSourceAccountResourceConsumptionList(), "decort_account_resource_consumption_get": account.DataSourceAccountResourceConsumptionGet(), "decort_kvmvm_list_deleted": kvmvm.DataSourceComputeListDeleted(), @@ -158,6 +164,7 @@ func newDataSourcesMap() map[string]*schema.Resource { "decort_cb_account_resource_consumption_get": cb_account.DataSourceAccountResourceConsumptionGet(), "decort_cb_account_resource_consumption_list": cb_account.DataSourceAccountResourceConsumptionList(), "decort_cb_account_audits_list": cb_account.DataSourceAccountAuditsList(), + "decort_cb_account_available_templates_list": cb_account.DataSourceAccountAvailableTemplatesList(), "decort_cb_audit": cb_audit.DataSourceAudit(), "decort_cb_audit_list": cb_audit.DataSourceAuditList(), "decort_cb_audit_linked_jobs": cb_audit.DataSourceAuditLinkedJobs(), @@ -194,6 +201,8 @@ func newDataSourcesMap() map[string]*schema.Resource { "decort_cb_kvmvm_snapshot_usage": cb_kvmvm.DataSourceComputeSnapshotUsage(), "decort_cb_kvmvm_user_list": cb_kvmvm.DataSourceComputeUserList(), "decort_cb_kvmvm_vgpu_list": cb_kvmvm.DataSourceComputeVGPUList(), + "decort_cb_node": cb_node.DataSourceNode(), + "decort_cb_node_list": cb_node.DataSourceNodeList(), "decort_cb_disk": cb_disks.DataSourceDisk(), "decort_cb_disk_list": cb_disks.DataSourceDiskList(), "decort_cb_disk_list_deleted": cb_disks.DataSourceDiskListDeleted(), @@ -202,6 +211,7 @@ func newDataSourcesMap() map[string]*schema.Resource { "decort_cb_disk_list_unattached": cb_disks.DataSourceDiskListUnattached(), "decort_cb_disk_snapshot": cb_disks.DataSourceDiskSnapshot(), "decort_cb_disk_snapshot_list": cb_disks.DataSourceDiskSnapshotList(), + "decort_cb_disk_replication": cb_disks.DataSourceDiskReplication(), "decort_cb_pcidevice": cb_pcidevice.DataSourcePcidevice(), "decort_cb_pcidevice_list": cb_pcidevice.DataSourcePcideviceList(), "decort_cb_rg": cb_rg.DataSourceResgroup(), @@ -231,6 +241,11 @@ func newDataSourcesMap() map[string]*schema.Resource { "decort_cb_flipgroup": cb_flipgroup.DataSourceFlipgroup(), "decort_cb_stack_list": cb_stack.DataSourceStacksList(), "decort_cb_stack": cb_stack.DataSourceStack(), + "decort_cb_user": cb_user.DataSourceUser(), + "decort_cb_user_get_audit": cb_user.DataSourceUserGetAudit(), + "decort_cb_user_list": cb_user.DataSourceUserList(), + "decort_cb_vfpool": cb_vfpool.DataSourceVFPool(), + "decort_cb_vfpool_list": cb_vfpool.DataSourceVFPoolList(), "decort_cb_vins": cb_vins.DataSourceVins(), "decort_cb_vins_list": cb_vins.DataSourceVinsList(), "decort_cb_vins_audits": cb_vins.DataSourceVinsAudits(), diff --git a/internal/provider/resource_map.go b/internal/provider/resource_map.go index 9f7bf07..0858cb3 100644 --- a/internal/provider/resource_map.go +++ b/internal/provider/resource_map.go @@ -40,64 +40,74 @@ import ( cb_extnet "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/extnet" cb_flipgroup "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/flipgroup" cb_image "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/image" + cb_k8ci "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/k8ci" cb_k8s "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/k8s" cb_kvmvm "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/kvmvm" cb_lb "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/lb" cb_pcidevice "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/pcidevice" cb_rg "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/rg" cb_sep "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/sep" - cb_k8ci "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/k8ci" + cb_user "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/user" + cb_vfpool "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/vfpool" cb_vins "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/vins" ) func newResourcesMap() map[string]*schema.Resource { return map[string]*schema.Resource{ - "decort_resgroup": rg.ResourceResgroup(), - "decort_kvmvm": kvmvm.ResourceCompute(), - "decort_disk": disks.ResourceDisk(), - "decort_disk_snapshot": disks.ResourceDiskSnapshot(), - "decort_vins": vins.ResourceVins(), - "decort_pfw": pfw.ResourcePfw(), - "decort_k8s": k8s.ResourceK8s(), - "decort_k8s_wg": k8s.ResourceK8sWg(), - "decort_k8s_cp": k8s.ResourceK8sCP(), - "decort_snapshot": snapshot.ResourceSnapshot(), - "decort_account": account.ResourceAccount(), - "decort_bservice": bservice.ResourceBasicService(), - "decort_bservice_group": bservice.ResourceBasicServiceGroup(), - "decort_image": image.ResourceImage(), - "decort_image_virtual": image.ResourceImageVirtual(), - "decort_lb": lb.ResourceLB(), - "decort_lb_backend": lb.ResourceLBBackend(), - "decort_lb_backend_server": lb.ResourceLBBackendServer(), - "decort_lb_frontend": lb.ResourceLBFrontend(), - "decort_lb_frontend_bind": lb.ResourceLBFrontendBind(), - "decort_flipgroup": flipgroup.ResourceFlipgroup(), - "decort_vins_static_route": vins.ResourceStaticRoute(), + "decort_resgroup": rg.ResourceResgroup(), + "decort_kvmvm": kvmvm.ResourceCompute(), + "decort_disk": disks.ResourceDisk(), + "decort_disk_snapshot": disks.ResourceDiskSnapshot(), + "decort_disk_replication": disks.ResourceDiskReplication(), + "decort_vins": vins.ResourceVins(), + "decort_pfw": pfw.ResourcePfw(), + "decort_k8s": k8s.ResourceK8s(), + "decort_k8s_wg": k8s.ResourceK8sWg(), + "decort_k8s_cp": k8s.ResourceK8sCP(), + "decort_snapshot": snapshot.ResourceSnapshot(), + "decort_account": account.ResourceAccount(), + "decort_bservice": bservice.ResourceBasicService(), + "decort_bservice_group": bservice.ResourceBasicServiceGroup(), + "decort_image": image.ResourceImage(), + "decort_image_from_blank_compute": image.ResourceImageFromBlankCompute(), + "decort_image_from_platform_disk": image.ResourceImageFromPlatformDisk(), + "decort_image_virtual": image.ResourceImageVirtual(), + "decort_lb": lb.ResourceLB(), + "decort_lb_backend": lb.ResourceLBBackend(), + "decort_lb_backend_server": lb.ResourceLBBackendServer(), + "decort_lb_frontend": lb.ResourceLBFrontend(), + "decort_lb_frontend_bind": lb.ResourceLBFrontendBind(), + "decort_flipgroup": flipgroup.ResourceFlipgroup(), + "decort_vins_static_route": vins.ResourceStaticRoute(), - "decort_cb_account": cb_account.ResourceAccount(), - "decort_cb_extnet": cb_extnet.ResourceExtnetCB(), - "decort_cb_extnet_static_route": cb_extnet.ResourceStaticRoute(), - "decort_cb_disk": cb_disks.ResourceDisk(), - "decort_cb_disk_snapshot": cb_disks.ResourceDiskSnapshot(), - "decort_cb_image": cb_image.ResourceImage(), - "decort_cb_virtual_image": cb_image.ResourceVirtualImage(), - "decort_cb_cdrom_image": cb_image.ResourceCDROMImage(), - "decort_cb_pcidevice": cb_pcidevice.ResourcePcidevice(), - "decort_cb_sep": cb_sep.ResourceSep(), - "decort_cb_sep_config": cb_sep.ResourceSepConfig(), - "decort_cb_kvmvm": cb_kvmvm.ResourceCompute(), - "decort_cb_vins": cb_vins.ResourceVins(), - "decort_cb_k8ci": cb_k8ci.ResourceK8CI(), - "decort_cb_k8s_cp": cb_k8s.ResourceK8sCP(), - "decort_cb_k8s_wg": cb_k8s.ResourceK8sWg(), - "decort_cb_vins_static_route": cb_vins.ResourceStaticRoute(), - "decort_cb_flipgroup": cb_flipgroup.ResourceFlipgroup(), - "decort_cb_lb": cb_lb.ResourceLB(), - "decort_cb_lb_backend": cb_lb.ResourceLBBackend(), - "decort_cb_lb_backend_server": cb_lb.ResourceLBBackendServer(), - "decort_cb_lb_frontend": cb_lb.ResourceLBFrontend(), - "decort_cb_lb_frontend_bind": cb_lb.ResourceLBFrontendBind(), - "decort_cb_rg": cb_rg.ResourceResgroup(), + "decort_cb_account": cb_account.ResourceAccount(), + "decort_cb_extnet": cb_extnet.ResourceExtnetCB(), + "decort_cb_extnet_static_route": cb_extnet.ResourceStaticRoute(), + "decort_cb_disk": cb_disks.ResourceDisk(), + "decort_cb_disk_snapshot": cb_disks.ResourceDiskSnapshot(), + "decort_cb_disk_replication": cb_disks.ResourceDiskReplication(), + "decort_cb_image": cb_image.ResourceImage(), + "decort_cb_image_from_blank_compute": cb_image.ResourceImageFromBlankCompute(), + "decort_cb_image_from_platform_disk": cb_image.ResourceImageFromPlatformDisk(), + "decort_cb_virtual_image": cb_image.ResourceVirtualImage(), + "decort_cb_cdrom_image": cb_image.ResourceCDROMImage(), + "decort_cb_pcidevice": cb_pcidevice.ResourcePcidevice(), + "decort_cb_sep": cb_sep.ResourceSep(), + "decort_cb_sep_config": cb_sep.ResourceSepConfig(), + "decort_cb_kvmvm": cb_kvmvm.ResourceCompute(), + "decort_cb_vins": cb_vins.ResourceVins(), + "decort_cb_k8ci": cb_k8ci.ResourceK8CI(), + "decort_cb_k8s_cp": cb_k8s.ResourceK8sCP(), + "decort_cb_k8s_wg": cb_k8s.ResourceK8sWg(), + "decort_cb_vins_static_route": cb_vins.ResourceStaticRoute(), + "decort_cb_flipgroup": cb_flipgroup.ResourceFlipgroup(), + "decort_cb_lb": cb_lb.ResourceLB(), + "decort_cb_lb_backend": cb_lb.ResourceLBBackend(), + "decort_cb_lb_backend_server": cb_lb.ResourceLBBackendServer(), + "decort_cb_lb_frontend": cb_lb.ResourceLBFrontend(), + "decort_cb_lb_frontend_bind": cb_lb.ResourceLBFrontendBind(), + "decort_cb_rg": cb_rg.ResourceResgroup(), + "decort_cb_user": cb_user.ResourceUser(), + "decort_cb_vfpool": cb_vfpool.ResourceVFPool(), } } diff --git a/internal/service/cloudapi/account/data_source_account.go b/internal/service/cloudapi/account/data_source_account.go index af86671..9968ce8 100644 --- a/internal/service/cloudapi/account/data_source_account.go +++ b/internal/service/cloudapi/account/data_source_account.go @@ -307,6 +307,13 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "created_by": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/account/data_source_account_computes_list.go b/internal/service/cloudapi/account/data_source_account_computes_list.go index 062cf60..6f65152 100644 --- a/internal/service/cloudapi/account/data_source_account_computes_list.go +++ b/internal/service/cloudapi/account/data_source_account_computes_list.go @@ -135,6 +135,11 @@ func dataSourceAccountComputesListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by extnet ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/account/data_source_account_disks_list.go b/internal/service/cloudapi/account/data_source_account_disks_list.go index 294ade3..971fac9 100644 --- a/internal/service/cloudapi/account/data_source_account_disks_list.go +++ b/internal/service/cloudapi/account/data_source_account_disks_list.go @@ -101,6 +101,11 @@ func dataSourceAccountDisksListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by disk type", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/account/data_source_account_list.go b/internal/service/cloudapi/account/data_source_account_list.go index 3728725..f07829f 100644 --- a/internal/service/cloudapi/account/data_source_account_list.go +++ b/internal/service/cloudapi/account/data_source_account_list.go @@ -46,13 +46,14 @@ func flattenAccountList(al *account.ListAccounts) []map[string]interface{} { res := make([]map[string]interface{}, 0) for _, acc := range al.Data { temp := map[string]interface{}{ - "acl": flattenRgAcl(acc.ACL), - "created_time": acc.CreatedTime, - "deleted_time": acc.DeletedTime, - "account_id": acc.ID, - "account_name": acc.Name, - "status": acc.Status, - "updated_time": acc.UpdatedTime, + "acl": flattenRgAcl(acc.ACL), + "compute_features": acc.ComputeFeatures, + "created_time": acc.CreatedTime, + "deleted_time": acc.DeletedTime, + "account_id": acc.ID, + "account_name": acc.Name, + "status": acc.Status, + "updated_time": acc.UpdatedTime, } res = append(res, temp) } @@ -112,6 +113,11 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -159,6 +165,13 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { }, }, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "created_time": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/account/data_source_account_rg_list.go b/internal/service/cloudapi/account/data_source_account_rg_list.go index edad40f..6752099 100644 --- a/internal/service/cloudapi/account/data_source_account_rg_list.go +++ b/internal/service/cloudapi/account/data_source_account_rg_list.go @@ -138,6 +138,11 @@ func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { Required: true, Description: "ID of the account", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/account/data_source_account_templates_list.go b/internal/service/cloudapi/account/data_source_account_templates_list.go index 2607a30..42069e1 100644 --- a/internal/service/cloudapi/account/data_source_account_templates_list.go +++ b/internal/service/cloudapi/account/data_source_account_templates_list.go @@ -103,6 +103,11 @@ func dataSourceAccountTemplatesListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by type", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/account/data_source_account_vins_list.go b/internal/service/cloudapi/account/data_source_account_vins_list.go index 6451cae..cda7ca6 100644 --- a/internal/service/cloudapi/account/data_source_account_vins_list.go +++ b/internal/service/cloudapi/account/data_source_account_vins_list.go @@ -54,6 +54,8 @@ func flattenAccountVinsList(avl *account.ListVINS) []map[string]interface{} { "deleted_by": av.DeletedBy, "deleted_time": av.DeletedTime, "external_ip": av.ExternalIP, + "extnet_id": av.ExtnetId, + "free_ips": av.FreeIPs, "vin_id": av.ID, "vin_name": av.Name, "network": av.Network, @@ -112,6 +114,11 @@ func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by external IP", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -160,6 +167,14 @@ func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "extnet_id": { + Type: schema.TypeInt, + Computed: true, + }, + "free_ips": { + Type: schema.TypeInt, + Computed: true, + }, "vin_id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/account/flattens.go b/internal/service/cloudapi/account/flattens.go index ae64554..e09903b 100644 --- a/internal/service/cloudapi/account/flattens.go +++ b/internal/service/cloudapi/account/flattens.go @@ -12,6 +12,7 @@ func flattenAccount(d *schema.ResourceData, acc account.RecordAccount) error { d.Set("acl", flattenAccAcl(acc.ACL)) d.Set("company", acc.Company) d.Set("companyurl", acc.CompanyURL) + d.Set("compute_features", acc.ComputeFeatures) d.Set("created_by", acc.CreatedBy) d.Set("created_time", acc.CreatedTime) d.Set("deactivation_time", acc.DeactivationTime) diff --git a/internal/service/cloudapi/account/resource_account.go b/internal/service/cloudapi/account/resource_account.go index ca27a2f..c867f9f 100644 --- a/internal/service/cloudapi/account/resource_account.go +++ b/internal/service/cloudapi/account/resource_account.go @@ -279,19 +279,6 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf } } - if d.HasChange("restore") { - restore := d.Get("restore").(bool) - if restore && acc.Status == "DELETED" { - req := account.RestoreRequest{ - AccountID: accountId, - } - _, err := c.CloudAPI().Account().Restore(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - if d.HasChange("users") { deletedUsers := make([]interface{}, 0) addedUsers := make([]interface{}, 0) @@ -542,6 +529,13 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "created_by": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/account/utility_account_computes_list.go b/internal/service/cloudapi/account/utility_account_computes_list.go index 48bc44a..306f9fa 100644 --- a/internal/service/cloudapi/account/utility_account_computes_list.go +++ b/internal/service/cloudapi/account/utility_account_computes_list.go @@ -1,102 +1,106 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListComputes, error) { - c := m.(*controller.ControllerCfg) - var id uint64 - - id = uint64(d.Get("account_id").(int)) - - req := account.ListComputesRequest{ - AccountID: id, - } - - if compute_id, ok := d.GetOk("compute_id"); ok { - req.ComputeID = uint64(compute_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if rg_name, ok := d.GetOk("rg_name"); ok { - req.RGName = rg_name.(string) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if tech_status, ok := d.GetOk("tech_status"); ok { - req.TechStatus = tech_status.(string) - } - - if ip_address, ok := d.GetOk("ip_address"); ok { - req.IPAddress = ip_address.(string) - } - - if extnet_name, ok := d.GetOk("extnet_name"); ok { - req.ExtNetName = extnet_name.(string) - } - - if extnet_id, ok := d.GetOk("extnet_id"); ok { - req.ExtNetID = uint64(extnet_id.(int)) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityAccountComputesListCheckPresence: load account list") - accountComputesList, err := c.CloudAPI().Account().ListComputes(ctx, req) - if err != nil { - return nil, err - } - - return accountComputesList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListComputes, error) { + c := m.(*controller.ControllerCfg) + var id uint64 + + id = uint64(d.Get("account_id").(int)) + + req := account.ListComputesRequest{ + AccountID: id, + } + + if compute_id, ok := d.GetOk("compute_id"); ok { + req.ComputeID = uint64(compute_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if rg_name, ok := d.GetOk("rg_name"); ok { + req.RGName = rg_name.(string) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if tech_status, ok := d.GetOk("tech_status"); ok { + req.TechStatus = tech_status.(string) + } + + if ip_address, ok := d.GetOk("ip_address"); ok { + req.IPAddress = ip_address.(string) + } + + if extnet_name, ok := d.GetOk("extnet_name"); ok { + req.ExtNetName = extnet_name.(string) + } + + if extnet_id, ok := d.GetOk("extnet_id"); ok { + req.ExtNetID = uint64(extnet_id.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityAccountComputesListCheckPresence: load account list") + accountComputesList, err := c.CloudAPI().Account().ListComputes(ctx, req) + if err != nil { + return nil, err + } + + return accountComputesList, nil +} diff --git a/internal/service/cloudapi/account/utility_account_deleted_list.go b/internal/service/cloudapi/account/utility_account_deleted_list.go index 1612afc..6ddbdaa 100644 --- a/internal/service/cloudapi/account/utility_account_deleted_list.go +++ b/internal/service/cloudapi/account/utility_account_deleted_list.go @@ -1,76 +1,80 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { - c := m.(*controller.ControllerCfg) - - req := account.ListDeletedRequest{} - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if acl, ok := d.GetOk("acl"); ok { - req.ACL = acl.(string) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - log.Debugf("utilityAccountDeletedListCheckPresence: load") - accountDeletedList, err := c.CloudAPI().Account().ListDeleted(ctx, req) - if err != nil { - return nil, err - } - return accountDeletedList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { + c := m.(*controller.ControllerCfg) + + req := account.ListDeletedRequest{} + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if acl, ok := d.GetOk("acl"); ok { + req.ACL = acl.(string) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + log.Debugf("utilityAccountDeletedListCheckPresence: load") + accountDeletedList, err := c.CloudAPI().Account().ListDeleted(ctx, req) + if err != nil { + return nil, err + } + return accountDeletedList, nil +} diff --git a/internal/service/cloudapi/account/utility_account_disks_list.go b/internal/service/cloudapi/account/utility_account_disks_list.go index c8a7728..506e16f 100644 --- a/internal/service/cloudapi/account/utility_account_disks_list.go +++ b/internal/service/cloudapi/account/utility_account_disks_list.go @@ -1,84 +1,88 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 account - -import ( - "context" - - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListDisks, error) { - c := m.(*controller.ControllerCfg) - var id uint64 - - id = uint64(d.Get("account_id").(int)) - - req := account.ListDisksRequest{ - AccountID: id, - } - - if disk_id, ok := d.GetOk("disk_id"); ok { - req.DiskID = uint64(disk_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if disk_max_size, ok := d.GetOk("disk_max_size"); ok { - req.DiskMaxSize = uint64(disk_max_size.(int)) - } - - if typeVal, ok := d.GetOk("type"); ok { - req.Type = typeVal.(string) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - accountDisksList, err := c.CloudAPI().Account().ListDisks(ctx, req) - if err != nil { - return nil, err - } - - return accountDisksList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListDisks, error) { + c := m.(*controller.ControllerCfg) + var id uint64 + + id = uint64(d.Get("account_id").(int)) + + req := account.ListDisksRequest{ + AccountID: id, + } + + if disk_id, ok := d.GetOk("disk_id"); ok { + req.DiskID = uint64(disk_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if disk_max_size, ok := d.GetOk("disk_max_size"); ok { + req.DiskMaxSize = uint64(disk_max_size.(int)) + } + + if typeVal, ok := d.GetOk("type"); ok { + req.Type = typeVal.(string) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + accountDisksList, err := c.CloudAPI().Account().ListDisks(ctx, req) + if err != nil { + return nil, err + } + + return accountDisksList, nil +} diff --git a/internal/service/cloudapi/account/utility_account_list.go b/internal/service/cloudapi/account/utility_account_list.go index 4bf9527..f483a31 100644 --- a/internal/service/cloudapi/account/utility_account_list.go +++ b/internal/service/cloudapi/account/utility_account_list.go @@ -1,79 +1,83 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { - c := m.(*controller.ControllerCfg) - req := account.ListRequest{} - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if acl, ok := d.GetOk("acl"); ok { - req.ACL = acl.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - log.Debugf("utilityAccountListCheckPresence: load account list") - accountList, err := c.CloudAPI().Account().List(ctx, req) - if err != nil { - return nil, err - } - - return accountList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { + c := m.(*controller.ControllerCfg) + req := account.ListRequest{} + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if acl, ok := d.GetOk("acl"); ok { + req.ACL = acl.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + log.Debugf("utilityAccountListCheckPresence: load account list") + accountList, err := c.CloudAPI().Account().List(ctx, req) + if err != nil { + return nil, err + } + + return accountList, nil +} diff --git a/internal/service/cloudapi/account/utility_account_rg_list.go b/internal/service/cloudapi/account/utility_account_rg_list.go index 5765010..28087cc 100644 --- a/internal/service/cloudapi/account/utility_account_rg_list.go +++ b/internal/service/cloudapi/account/utility_account_rg_list.go @@ -1,90 +1,94 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListRG, error) { - c := m.(*controller.ControllerCfg) - var id uint64 - - id = uint64(d.Get("account_id").(int)) - - req := account.ListRGRequest{ - AccountID: id, - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if vins_id, ok := d.GetOk("vins_id"); ok { - req.VINSID = uint64(vins_id.(int)) - } - - if vm_id, ok := d.GetOk("vm_id"); ok { - req.VMID = uint64(vm_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - log.Debugf("utilityAccountRGListCheckPresence: load account list") - accountRGList, err := c.CloudAPI().Account().ListRG(ctx, req) - if err != nil { - return nil, err - } - - return accountRGList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListRG, error) { + c := m.(*controller.ControllerCfg) + var id uint64 + + id = uint64(d.Get("account_id").(int)) + + req := account.ListRGRequest{ + AccountID: id, + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if vins_id, ok := d.GetOk("vins_id"); ok { + req.VINSID = uint64(vins_id.(int)) + } + + if vm_id, ok := d.GetOk("vm_id"); ok { + req.VMID = uint64(vm_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + log.Debugf("utilityAccountRGListCheckPresence: load account list") + accountRGList, err := c.CloudAPI().Account().ListRG(ctx, req) + if err != nil { + return nil, err + } + + return accountRGList, nil +} diff --git a/internal/service/cloudapi/account/utility_account_templates_list.go b/internal/service/cloudapi/account/utility_account_templates_list.go index 3db541a..624707d 100644 --- a/internal/service/cloudapi/account/utility_account_templates_list.go +++ b/internal/service/cloudapi/account/utility_account_templates_list.go @@ -1,80 +1,83 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountTemplatesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListTemplates, error) { - c := m.(*controller.ControllerCfg) - - id := uint64(d.Get("account_id").(int)) - - req := account.ListTemplatesRequest{ - AccountID: id, - } - - if include_deleted, ok := d.GetOk("include_deleted"); ok { - req.IncludeDeleted = include_deleted.(bool) - } - if imageId, ok := d.GetOk("image_id"); ok { - req.ImageID = uint64(imageId.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if typeTemplates, ok := d.GetOk("type"); ok { - req.Type = typeTemplates.(string) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityAccountTemplatesListCheckPresence: load") - accountTemplatesList, err := c.CloudAPI().Account().ListTemplates(ctx, req) - if err != nil { - return nil, err - } - - return accountTemplatesList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountTemplatesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListTemplates, error) { + c := m.(*controller.ControllerCfg) + + id := uint64(d.Get("account_id").(int)) + + req := account.ListTemplatesRequest{ + AccountID: id, + } + + if include_deleted, ok := d.GetOk("include_deleted"); ok { + req.IncludeDeleted = include_deleted.(bool) + } + if imageId, ok := d.GetOk("image_id"); ok { + req.ImageID = uint64(imageId.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if typeTemplates, ok := d.GetOk("type"); ok { + req.Type = typeTemplates.(string) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityAccountTemplatesListCheckPresence: load") + accountTemplatesList, err := c.CloudAPI().Account().ListTemplates(ctx, req) + if err != nil { + return nil, err + } + + return accountTemplatesList, nil +} diff --git a/internal/service/cloudapi/account/utility_account_vins_list.go b/internal/service/cloudapi/account/utility_account_vins_list.go index a5b21aa..cb4b978 100644 --- a/internal/service/cloudapi/account/utility_account_vins_list.go +++ b/internal/service/cloudapi/account/utility_account_vins_list.go @@ -1,86 +1,90 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListVINS, error) { - c := m.(*controller.ControllerCfg) - var id uint64 - - id = uint64(d.Get("account_id").(int)) - - req := account.ListVINSRequest{ - AccountID: id, - } - - if vins_id, ok := d.GetOk("vins_id"); ok { - req.VINSID = uint64(vins_id.(int)) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if ext_ip, ok := d.GetOk("ext_ip"); ok { - req.ExtIP = ext_ip.(string) - } - - log.Debugf("utilityAccountVinsListCheckPresence: load account list") - accountVinsList, err := c.CloudAPI().Account().ListVINS(ctx, req) - if err != nil { - return nil, err - } - - return accountVinsList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListVINS, error) { + c := m.(*controller.ControllerCfg) + var id uint64 + + id = uint64(d.Get("account_id").(int)) + + req := account.ListVINSRequest{ + AccountID: id, + } + + if vins_id, ok := d.GetOk("vins_id"); ok { + req.VINSID = uint64(vins_id.(int)) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if ext_ip, ok := d.GetOk("ext_ip"); ok { + req.ExtIP = ext_ip.(string) + } + + log.Debugf("utilityAccountVinsListCheckPresence: load account list") + accountVinsList, err := c.CloudAPI().Account().ListVINS(ctx, req) + if err != nil { + return nil, err + } + + return accountVinsList, nil +} diff --git a/internal/service/cloudapi/bservice/data_source_bservice_list.go b/internal/service/cloudapi/bservice/data_source_bservice_list.go index 94be8d3..c032d94 100644 --- a/internal/service/cloudapi/bservice/data_source_bservice_list.go +++ b/internal/service/cloudapi/bservice/data_source_bservice_list.go @@ -131,6 +131,11 @@ func dataSourceBasicServiceListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "ID of the resource group to query for BasicService instances", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/bservice/resource_bservice.go b/internal/service/cloudapi/bservice/resource_bservice.go index 2c95ac7..7c2cfba 100644 --- a/internal/service/cloudapi/bservice/resource_bservice.go +++ b/internal/service/cloudapi/bservice/resource_bservice.go @@ -34,7 +34,7 @@ package bservice import ( "context" - "fmt" + "errors" "strconv" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -85,37 +85,38 @@ func resourceBasicServiceCreate(ctx context.Context, d *schema.ResourceData, m i return diag.FromErr(err) } - warn := dc.Warnings{} + warnings := dc.Warnings{} + enable := d.Get("enable").(bool) - if !d.Get("enable").(bool) && d.Get("start").(bool) { - - warn.Add(fmt.Errorf("the basic service is in tech_status %s, troubles can occur with the usage. Please, enable bservice first", service.TechStatus)) - } - - if d.Get("enable").(bool) && (service.Status == status.Disabled || service.Status == status.Created) { + if enable && (service.Status == status.Disabled || service.Status == status.Created) { log.Debugf("trying to enable bservice %v", serviceId) _, err := c.CloudAPI().BService().Enable(ctx, bservice.EnableRequest{ ServiceID: serviceId, }) if err != nil { - return diag.FromErr(err) + warnings.Add(err) } - } - if d.Get("start").(bool) && d.Get("enable").(bool) { - + if d.Get("start").(bool) { log.Debugf("trying to start bservice %v", serviceId) - _, err = c.CloudAPI().BService().Start(ctx, bservice.StartRequest{ - ServiceID: serviceId, - }) - if err != nil { - return diag.FromErr(err) + if !enable { + warnings.Add(errors.New("can not start bservice that is not enabled. Set enable = true and start = true to enable and start bservice")) + } + + if enable { + _, err := c.CloudAPI().BService().Start(ctx, bservice.StartRequest{ + ServiceID: serviceId, + }) + + if err != nil { + warnings.Add(err) + } } } - return append(warn.Get(), resourceBasicServiceRead(ctx, d, m)...) + return append(warnings.Get(), resourceBasicServiceRead(ctx, d, m)...) } func resourceBasicServiceRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -241,44 +242,35 @@ func resourceBasicServiceUpdate(ctx context.Context, d *schema.ResourceData, m i case status.Disabling: log.Debugf("The basic service is in status: %s, troubles can occur with the update.", bs.Status) case status.Deleted: - id, _ := strconv.ParseUint(d.Id(), 10, 64) - - if restore, ok := d.GetOk("restore"); ok { - if restore.(bool) { - restoreReq := bservice.RestoreRequest{ - ServiceID: id, - } - _, err := c.CloudAPI().BService().Restore(ctx, restoreReq) - if err != nil { - return diag.FromErr(err) - } + if d.Get("restore").(bool) { + restoreReq := bservice.RestoreRequest{ + ServiceID: bs.ID, } + _, err := c.CloudAPI().BService().Restore(ctx, restoreReq) + if err != nil { + return diag.FromErr(err) + } + hasChanged = true - } - if enable, ok := d.GetOk("enable"); ok { - if enable.(bool) { + if d.Get("enable").(bool) { enableReq := bservice.EnableRequest{ - ServiceID: id, + ServiceID: bs.ID, } _, err = c.CloudAPI().BService().Enable(ctx, enableReq) if err != nil { return diag.FromErr(err) } - hasChanged = true } - } - if start, ok := d.GetOk("start"); ok { - if start.(bool) { + if d.Get("start").(bool) { startReq := bservice.StartRequest{ - ServiceID: id, + ServiceID: bs.ID, } _, err = c.CloudAPI().BService().Start(ctx, startReq) if err != nil { return diag.FromErr(err) } - hasChanged = true } } case status.Deleting: @@ -301,8 +293,7 @@ func resourceBasicServiceUpdate(ctx context.Context, d *schema.ResourceData, m i } if d.HasChange("enable") { - enable := d.Get("enable").(bool) - if enable { + if d.Get("enable").(bool) { req := bservice.EnableRequest{ ServiceID: uint64(d.Get("service_id").(int)), } @@ -324,8 +315,7 @@ func resourceBasicServiceUpdate(ctx context.Context, d *schema.ResourceData, m i } if d.HasChange("start") { - start := d.Get("start").(bool) - if start { + if d.Get("start").(bool) { req := bservice.StartRequest{ ServiceID: uint64(d.Get("service_id").(int)), } diff --git a/internal/service/cloudapi/bservice/resource_bservice_group.go b/internal/service/cloudapi/bservice/resource_bservice_group.go index b6e0b18..27b73e5 100644 --- a/internal/service/cloudapi/bservice/resource_bservice_group.go +++ b/internal/service/cloudapi/bservice/resource_bservice_group.go @@ -43,6 +43,7 @@ import ( "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice" "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/validators" ) func resourceBasicServiceGroupCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -372,8 +373,12 @@ func resourceBasicServiceGroupSchemaMake() map[string]*schema.Schema { Description: "compute CPU number. All computes in the group have the same CPU count", }, "ram": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.All( + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), + ), Description: "compute RAM volume in MB. All computes in the group have the same RAM volume", }, "disk": { diff --git a/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go b/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go index 31d4eaa..63522b7 100644 --- a/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go +++ b/internal/service/cloudapi/bservice/utility_bservicce_deleted_list.go @@ -1,69 +1,73 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 bservice - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityBasicServiceDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*bservice.ListBasicServices, error) { - c := m.(*controller.ControllerCfg) - req := bservice.ListDeletedRequest{} - - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if rgId, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rgId.(int)) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityBasicServiceDeletedListCheckPresence") - basicServiceDeletedList, err := c.CloudAPI().BService().ListDeleted(ctx, req) - if err != nil { - return nil, err - } - - return basicServiceDeletedList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 bservice + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityBasicServiceDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*bservice.ListBasicServices, error) { + c := m.(*controller.ControllerCfg) + req := bservice.ListDeletedRequest{} + + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if rgId, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rgId.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityBasicServiceDeletedListCheckPresence") + basicServiceDeletedList, err := c.CloudAPI().BService().ListDeleted(ctx, req) + if err != nil { + return nil, err + } + + return basicServiceDeletedList, nil +} diff --git a/internal/service/cloudapi/bservice/utility_bservice_list.go b/internal/service/cloudapi/bservice/utility_bservice_list.go index 5e1c662..5bb1784 100644 --- a/internal/service/cloudapi/bservice/utility_bservice_list.go +++ b/internal/service/cloudapi/bservice/utility_bservice_list.go @@ -1,93 +1,96 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 bservice - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityBasicServiceListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*bservice.ListBasicServices, error) { - c := m.(*controller.ControllerCfg) - req := bservice.ListRequest{} - - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if rgId, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rgId.(int)) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if rg_name, ok := d.GetOk("rg_name"); ok { - req.RGName = rg_name.(string) - } - - if tech_status, ok := d.GetOk("tech_status"); ok { - req.TechStatus = tech_status.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - if acc_name, ok := d.GetOk("account_name"); ok { - req.AccountName = acc_name.(string) - } - - log.Debugf("utilityBasicServiceListCheckPresence") - basicServiceList, err := c.CloudAPI().BService().List(ctx, req) - if err != nil { - return nil, err - } - - return basicServiceList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 bservice + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityBasicServiceListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*bservice.ListBasicServices, error) { + c := m.(*controller.ControllerCfg) + req := bservice.ListRequest{} + + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if rgId, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rgId.(int)) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if rg_name, ok := d.GetOk("rg_name"); ok { + req.RGName = rg_name.(string) + } + + if tech_status, ok := d.GetOk("tech_status"); ok { + req.TechStatus = tech_status.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + if acc_name, ok := d.GetOk("account_name"); ok { + req.AccountName = acc_name.(string) + } + + log.Debugf("utilityBasicServiceListCheckPresence") + basicServiceList, err := c.CloudAPI().BService().List(ctx, req) + if err != nil { + return nil, err + } + + return basicServiceList, nil +} diff --git a/internal/service/cloudapi/disks/data_source_disk.go b/internal/service/cloudapi/disks/data_source_disk.go index 369286e..ead990c 100644 --- a/internal/service/cloudapi/disks/data_source_disk.go +++ b/internal/service/cloudapi/disks/data_source_disk.go @@ -294,6 +294,39 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Time of the last deletion attempt", }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, // "reality_device_number": { // Type: schema.TypeInt, // Computed: true, diff --git a/internal/service/cloudapi/disks/data_source_disk_list.go b/internal/service/cloudapi/disks/data_source_disk_list.go index c484b6c..dc6799e 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list.go +++ b/internal/service/cloudapi/disks/data_source_disk_list.go @@ -108,6 +108,11 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "find by pool name", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -376,6 +381,39 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { // Computed: true, // Description: "ID of the reference to the disk", // }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, "res_id": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/disks/data_source_disk_list_types.go b/internal/service/cloudapi/disks/data_source_disk_list_types.go index 97255fa..a3cfde4 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list_types.go +++ b/internal/service/cloudapi/disks/data_source_disk_list_types.go @@ -57,6 +57,11 @@ func dataSourceDiskListTypesRead(ctx context.Context, d *schema.ResourceData, m func dataSourceDiskListTypesSchemaMake() map[string]*schema.Schema { res := map[string]*schema.Schema{ + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go b/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go index 61d7a38..9ea2b03 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go +++ b/internal/service/cloudapi/disks/data_source_disk_list_types_detailed.go @@ -87,6 +87,11 @@ func dataSourceDiskListTypesDetailedRead(ctx context.Context, d *schema.Resource func dataSourceDiskListTypesDetailedSchemaMake() map[string]*schema.Schema { res := map[string]*schema.Schema{ + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/disks/data_source_disk_list_unattached.go b/internal/service/cloudapi/disks/data_source_disk_list_unattached.go index 001af64..a673186 100644 --- a/internal/service/cloudapi/disks/data_source_disk_list_unattached.go +++ b/internal/service/cloudapi/disks/data_source_disk_list_unattached.go @@ -113,6 +113,11 @@ func dataSourceDiskListUnattachedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "type of the disks", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/disks/data_source_disk_replication.go b/internal/service/cloudapi/disks/data_source_disk_replication.go new file mode 100644 index 0000000..0488d57 --- /dev/null +++ b/internal/service/cloudapi/disks/data_source_disk_replication.go @@ -0,0 +1,480 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 disks + +import ( + "context" + + "github.com/google/uuid" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceDiskReplicationRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("dataSourceDiskReplicationRead: called for disk with ID: %s", d.Id()) + c := m.(*controller.ControllerCfg) + + req := disks.ReplicationStatusRequest{ + DiskID: uint64(d.Get("disk_id").(int)), + } + + status, err := c.CloudAPI().Disks().ReplicationStatus(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + disk, err := utilityDiskReplicaCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + flattenDiskReplica(d, disk, status) + + log.Debugf("dataSourceDiskReplicationRead: read complete for disk with ID: %s", d.Id()) + + return nil +} + +func dataSourceDiskReplicationSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Id of primary disk", + }, + "replica_disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Id of secondary disk", + }, + "status_replication": { + Type: schema.TypeString, + Computed: true, + Description: "Status of replication", + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + Description: "The unique ID of the subscriber-owner of the disk", + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the subscriber '(account') to whom this disk belongs", + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + // "boot_partition": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Number of disk partitions", + // }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeString, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Created time", + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Deleted time", + }, + "desc": { + Type: schema.TypeString, + Computed: true, + Description: "Description of disk", + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Time of final deletion", + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the device", + }, + // "disk_path": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Disk path", + // }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the grid (platform)", + }, + // "guid": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Disk ID on the storage side", + // }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Image ID", + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "IDs of images using the disk", + }, + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of bytes to read per second", + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of bytes to read", + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of io read operations per second", + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of io read operations", + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Size of io operations", + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Total size bytes per second", + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum total size of bytes per second", + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Total number of io operations per second", + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum total number of io operations per second", + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of bytes to write per second", + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of bytes to write per second", + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of write operations per second", + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of write operations per second", + }, + }, + }, + }, + // "iqn": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Disk IQN", + // }, + // "login": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Login to access the disk", + // }, + // "milestones": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Milestones", + // }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of disk", + }, + "order": { + Type: schema.TypeInt, + Computed: true, + Description: "Disk order", + }, + "params": { + Type: schema.TypeString, + Computed: true, + Description: "Disk params", + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the parent disk", + }, + // "passwd": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Password to access the disk", + // }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the pci slot to which the disk is connected", + }, + "pool": { + Type: schema.TypeString, + Computed: true, + Description: "Pool for disk location", + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + // "purge_attempts": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Number of deletion attempts", + // }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Time of the last deletion attempt", + }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, + // "reality_device_number": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Reality device number", + // }, + // "reference_id": { + // Type: schema.TypeString, + // Computed: true, + // Description: "ID of the reference to the disk", + // }, + "res_id": { + Type: schema.TypeString, + Computed: true, + Description: "Resource ID", + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the resource", + }, + "role": { + Type: schema.TypeString, + Computed: true, + Description: "Disk role", + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Storage endpoint provider ID to create disk", + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + Description: "Type SEP. Defines the type of storage system and contains one of the values set in the cloud platform", + }, + "shareable": { + Type: schema.TypeBool, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Size in GB", + }, + "size_used": { + Type: schema.TypeFloat, + Computed: true, + Description: "Number of used space, in GB", + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "ID of the snapshot", + }, + "label": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the snapshot", + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + Description: "Reference to the snapshot", + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + Description: "The set snapshot ID", + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + Description: "The set time of the snapshot", + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + Description: "Snapshot time", + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Disk status", + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + Description: "Technical status of the disk", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of disk in terms of its role in compute: 'B=Boot, D=Data, T=Temp'", + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + Description: "Virtual Machine ID (Deprecated)", + }, + } + + return rets +} + +func DataSourceDiskReplication() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceDiskReplicationRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceDiskReplicationSchemaMake(), + } +} diff --git a/internal/service/cloudapi/disks/data_source_list_deleted.go b/internal/service/cloudapi/disks/data_source_list_deleted.go index 33ab9e4..7368909 100644 --- a/internal/service/cloudapi/disks/data_source_list_deleted.go +++ b/internal/service/cloudapi/disks/data_source_list_deleted.go @@ -94,6 +94,11 @@ func dataSourceDiskDeletedListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "type of the disks", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -352,6 +357,39 @@ func dataSourceDiskDeletedListSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Time of the last deletion attempt", }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, // "reality_device_number": { // Type: schema.TypeInt, // Computed: true, diff --git a/internal/service/cloudapi/disks/flattens.go b/internal/service/cloudapi/disks/flattens.go index aa9f283..e045f51 100644 --- a/internal/service/cloudapi/disks/flattens.go +++ b/internal/service/cloudapi/disks/flattens.go @@ -72,7 +72,6 @@ func flattenDiskListUnattached(ul *disks.ListDisksUnattached) []map[string]inter func flattenDisk(d *schema.ResourceData, disk *disks.RecordDisk) { diskAcl, _ := json.Marshal(disk.ACL) - d.Set("account_id", disk.AccountID) d.Set("account_name", disk.AccountName) d.Set("acl", string(diskAcl)) @@ -103,6 +102,71 @@ func flattenDisk(d *schema.ResourceData, disk *disks.RecordDisk) { d.Set("present_to", disk.PresentTo) // d.Set("purge_attempts", disk.PurgeAttempts) d.Set("purge_time", disk.PurgeTime) + d.Set("replication", flattenDiskReplication(disk.Replication)) + // d.Set("reality_device_number", disk.RealityDeviceNumber) + // d.Set("reference_id", disk.ReferenceID) + d.Set("res_id", disk.ResID) + d.Set("res_name", disk.ResName) + d.Set("role", disk.Role) + d.Set("sep_id", disk.SepID) + d.Set("sep_type", disk.SepType) + d.Set("size_max", disk.SizeMax) + d.Set("size_used", disk.SizeUsed) + d.Set("shareable", disk.Shareable) + d.Set("snapshots", flattenDiskSnapshotList(disk.Snapshots)) + d.Set("status", disk.Status) + d.Set("tech_status", disk.TechStatus) + d.Set("type", disk.Type) + d.Set("vmid", disk.VMID) +} + +func flattenDiskReplication(rep disks.ItemReplication) []map[string]interface{} { + res := []map[string]interface{}{ + { + "disk_id": rep.DiskID, + "pool_id": rep.PoolID, + "role": rep.Role, + "self_volume_id": rep.SelfVolumeID, + "storage_id": rep.StorageID, + "volume_id": rep.VolumeID, + }, + } + return res +} + +func flattenDiskReplica(d *schema.ResourceData, disk *disks.RecordDisk, statusReplication string) { + diskAcl, _ := json.Marshal(disk.ACL) + d.Set("account_id", disk.AccountID) + d.Set("account_name", disk.AccountName) + d.Set("acl", string(diskAcl)) + // d.Set("boot_partition", disk.BootPartition) + d.Set("computes", flattenDiskComputes(disk.Computes)) + d.Set("created_time", disk.CreatedTime) + d.Set("deleted_time", disk.DeletedTime) + d.Set("desc", disk.Description) + d.Set("destruction_time", disk.DestructionTime) + d.Set("devicename", disk.DeviceName) + // d.Set("disk_path", disk.DiskPath) + d.Set("gid", disk.GID) + // d.Set("guid", disk.GUID) + d.Set("replica_disk_id", disk.ID) + d.Set("image_id", disk.ImageID) + d.Set("images", disk.Images) + d.Set("iotune", flattenIOTune(disk.IOTune)) + // d.Set("iqn", disk.IQN) + // d.Set("login", disk.Login) + // d.Set("milestones", disk.Milestones) + d.Set("disk_name", disk.Name) + d.Set("order", disk.Order) + d.Set("params", disk.Params) + d.Set("parent_id", disk.ParentID) + // d.Set("passwd", disk.Passwd) + d.Set("pci_slot", disk.PCISlot) + d.Set("pool", disk.Pool) + d.Set("present_to", disk.PresentTo) + // d.Set("purge_attempts", disk.PurgeAttempts) + d.Set("purge_time", disk.PurgeTime) + d.Set("replication", flattenDiskReplication(disk.Replication)) // d.Set("reality_device_number", disk.RealityDeviceNumber) // d.Set("reference_id", disk.ReferenceID) d.Set("res_id", disk.ResID) @@ -115,6 +179,7 @@ func flattenDisk(d *schema.ResourceData, disk *disks.RecordDisk) { d.Set("shareable", disk.Shareable) d.Set("snapshots", flattenDiskSnapshotList(disk.Snapshots)) d.Set("status", disk.Status) + d.Set("status_replication", statusReplication) d.Set("tech_status", disk.TechStatus) d.Set("type", disk.Type) d.Set("vmid", disk.VMID) @@ -166,6 +231,7 @@ func flattenDiskList(dl *disks.ListDisks) []map[string]interface{} { "pool": disk.Pool, "present_to": disk.PresentTo, "purge_time": disk.PurgeTime, + "replication": flattenDiskReplication(disk.Replication), "res_id": disk.ResID, "res_name": disk.ResName, "role": disk.Role, diff --git a/internal/service/cloudapi/disks/resource_check_input_values.go b/internal/service/cloudapi/disks/resource_check_input_values.go index bfc4722..a06024c 100644 --- a/internal/service/cloudapi/disks/resource_check_input_values.go +++ b/internal/service/cloudapi/disks/resource_check_input_values.go @@ -2,9 +2,11 @@ package disks import ( "context" + "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" ) @@ -34,3 +36,26 @@ func existGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, return len(locationList.FilterByGID(gid).Data) != 0, nil } + +func existDiskID(ctx context.Context, diskId uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + + req := disks.ListRequest{ + ByID: diskId, + } + + diskList, err := c.CloudAPI().Disks().List(ctx, req) + if err != nil { + return err + } + + if len(diskList.Data) == 0 { + return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not allowed or does not exist", diskId) + } + + if diskList.Data[0].SepType != "TATLIN" { + return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not TATLIN SEP Type", diskId) + } + + return nil +} diff --git a/internal/service/cloudapi/disks/resource_disk.go b/internal/service/cloudapi/disks/resource_disk.go index 1607917..acc9be0 100644 --- a/internal/service/cloudapi/disks/resource_disk.go +++ b/internal/service/cloudapi/disks/resource_disk.go @@ -671,6 +671,39 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Time of the last deletion attempt", }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, // "reality_device_number": { // Type: schema.TypeInt, // Computed: true, diff --git a/internal/service/cloudapi/disks/resource_disk_replication.go b/internal/service/cloudapi/disks/resource_disk_replication.go new file mode 100644 index 0000000..6cca162 --- /dev/null +++ b/internal/service/cloudapi/disks/resource_disk_replication.go @@ -0,0 +1,642 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 disks + +import ( + "context" + "strconv" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" + "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 resourceDiskReplicationCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskId := uint64(d.Get("disk_id").(int)) + + log.Debugf("resourceDiskReplicationCreate: called for disk with ID: %d", diskId) + + c := m.(*controller.ControllerCfg) + + err := existDiskID(ctx, diskId, m) + if err != nil { + return diag.FromErr(err) + } + + reqCreate := disks.ReplicateRequest{ + DiskID: diskId, + Name: d.Get("disk_name").(string), + SepID: uint64(d.Get("sep_id").(int)), + PoolName: d.Get("pool_name").(string), + } + + diskReplicaId, err := c.CloudAPI().Disks().Replicate(ctx, reqCreate) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(diskReplicaId, 10)) + d.Set("replica_disk_id", diskReplicaId) + + log.Debugf("resourceDiskReplicationCreate: create replica complete for disk with ID: %d", diskId) + + warnings := dc.Warnings{} + + if start, ok := d.GetOk("start"); ok && !start.(bool) { + log.Debugf("resourceDiskReplicationCreate: replication between disk with ID: %d and replica with ID: %d, try to stop", diskId, diskReplicaId) + reqStop := disks.ReplicationStopRequest{ + DiskID: diskId, + } + _, err = c.CloudAPI().Disks().ReplicationStop(ctx, reqStop) + if err != nil { + warnings.Add(err) + } + log.Debugf("resourceDiskReplicationCreate: replication between disk with ID: %d and replica with ID: %d, stoped", diskId, diskReplicaId) + } + return append(resourceDiskReplicationRead(ctx, d, m), warnings.Get()...) +} + +func resourceDiskReplicationRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceDiskReplicationRead: called for disk with ID: %s", d.Id()) + c := m.(*controller.ControllerCfg) + + req := disks.ReplicationStatusRequest{ + DiskID: uint64(d.Get("disk_id").(int)), + } + + status, err := c.CloudAPI().Disks().ReplicationStatus(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + diskReplica, err := utilityDiskReplicaCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + flattenDiskReplica(d, diskReplica, status) + + log.Debugf("resourceDiskReplicationRead: read complete for disk with ID: %s", d.Id()) + return nil +} + +func resourceDiskReplicationUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskId := uint64(d.Get("disk_id").(int)) + log.Debugf("resourceDiskReplicationUpdate: called for disk with ID: %d", diskId) + + err := existDiskID(ctx, diskId, m) + if err != nil { + return diag.FromErr(err) + } + + if d.HasChange("start") { + if err := utilityDiskReplicationUpdateStartStop(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("pause") { + if err := utilityDiskReplicationUpdatePause(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("reverse") { + if err := utilityDiskReplicationUpdateReverse(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + + log.Debugf("resourceDiskReplicationUpdate: read complete for disk with ID: %d", diskId) + return resourceDiskReplicationRead(ctx, d, m) +} + +func resourceDiskReplicationDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskId := uint64(d.Get("disk_id").(int)) + log.Debugf("resourceDiskReplicationDelete: called for disk with ID: %d", diskId) + + disk, err := utilityDiskReplicaCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + + if d.Get("start").(bool) { + reqStop := disks.ReplicationStopRequest{ + DiskID: uint64(d.Get("disk_id").(int)), + } + + log.Debugf("resourceDiskReplicationDelete: stop replication for disk with ID: %d", diskId) + _, err = c.CloudAPI().Disks().ReplicationStop(ctx, reqStop) + if err != nil { + return diag.FromErr(err) + } + log.Debugf("resourceDiskReplicationDelete: stop replication for disk with ID: %d, complete", diskId) + } + + reqDelete := disks.DeleteRequest{ + DiskID: disk.ID, + Detach: d.Get("detach").(bool), + Permanently: d.Get("permanently").(bool), + Reason: d.Get("reason").(string), + } + + log.Debugf("resourceDiskReplicationDelete: delete disk replica for disk with ID: %d", diskId) + _, err = c.CloudAPI().Disks().Delete(ctx, reqDelete) + if err != nil { + return diag.FromErr(err) + } + log.Debugf("resourceDiskReplicationDelete: delete disk replica for disk with ID: %d, complete", diskId) + + d.SetId("") + + return nil +} + +func resourceDiskReplicationSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Id of primary disk", + }, + "disk_name": { + Type: schema.TypeString, + Required: true, + Description: "Name of disk replica", + }, + "sep_id": { + Type: schema.TypeInt, + Required: true, + Description: "Storage endpoint provider ID to create disk replica", + }, + "pool_name": { + Type: schema.TypeString, + Required: true, + Description: "Pool for disk location", + }, + "pause": { + Type: schema.TypeBool, + Optional: true, + Description: "Resume replication", + }, + "reverse": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Reverse replication", + }, + "start": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "Start/Stop replication", + }, + "detach": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Detach disk from machine first", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Delete disk permanently", + }, + "reason": { + Type: schema.TypeString, + Optional: true, + Description: "Reason for disk deletion", + }, + "replica_disk_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Id of replica disk", + }, + "status_replication": { + Type: schema.TypeString, + Computed: true, + Description: "Status of replication", + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + Description: "The unique ID of the subscriber-owner of the disk", + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the subscriber '(account') to whom this disk belongs", + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + // "boot_partition": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Number of disk partitions", + // }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeString, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Created time", + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Deleted time", + }, + "desc": { + Type: schema.TypeString, + Computed: true, + Description: "Description of disk", + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Time of final deletion", + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the device", + }, + // "disk_path": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Disk path", + // }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the grid (platform)", + }, + // "guid": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Disk ID on the storage side", + // }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Image ID", + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "IDs of images using the disk", + }, + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of bytes to read per second", + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of bytes to read", + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of io read operations per second", + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of io read operations", + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Size of io operations", + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Total size bytes per second", + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum total size of bytes per second", + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Total number of io operations per second", + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum total number of io operations per second", + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of bytes to write per second", + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of bytes to write per second", + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of write operations per second", + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Maximum number of write operations per second", + }, + }, + }, + }, + // "iqn": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Disk IQN", + // }, + // "login": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Login to access the disk", + // }, + // "milestones": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Milestones", + // }, + "order": { + Type: schema.TypeInt, + Computed: true, + Description: "Disk order", + }, + "params": { + Type: schema.TypeString, + Computed: true, + Description: "Disk params", + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the parent disk", + }, + // "passwd": { + // Type: schema.TypeString, + // Computed: true, + // Description: "Password to access the disk", + // }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + Description: "ID of the pci slot to which the disk is connected", + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + // "purge_attempts": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Number of deletion attempts", + // }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Time of the last deletion attempt", + }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, + // "reality_device_number": { + // Type: schema.TypeInt, + // Computed: true, + // Description: "Reality device number", + // }, + // "reference_id": { + // Type: schema.TypeString, + // Computed: true, + // Description: "ID of the reference to the disk", + // }, + "res_id": { + Type: schema.TypeString, + Computed: true, + Description: "Resource ID", + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the resource", + }, + "role": { + Type: schema.TypeString, + Computed: true, + Description: "Disk role", + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + Description: "Type SEP. Defines the type of storage system and contains one of the values set in the cloud platform", + }, + "shareable": { + Type: schema.TypeBool, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + Description: "Size in GB", + }, + "size_used": { + Type: schema.TypeFloat, + Computed: true, + Description: "Number of used space, in GB", + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "ID of the snapshot", + }, + "label": { + Type: schema.TypeString, + Computed: true, + Description: "Name of the snapshot", + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + Description: "Reference to the snapshot", + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + Description: "The set snapshot ID", + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + Description: "The set time of the snapshot", + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + Description: "Snapshot time", + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "Disk status", + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + Description: "Technical status of the disk", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of disk in terms of its role in compute: 'B=Boot, D=Data, T=Temp'", + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + Description: "Virtual Machine ID (Deprecated)", + }, + } + + return rets +} + +func ResourceDiskReplication() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceDiskReplicationCreate, + ReadContext: resourceDiskReplicationRead, + UpdateContext: resourceDiskReplicationUpdate, + DeleteContext: resourceDiskReplicationDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: resourceDiskReplicationSchemaMake(), + } +} diff --git a/internal/service/cloudapi/disks/utility_disk_list.go b/internal/service/cloudapi/disks/utility_disk_list.go index cad7681..eab6d69 100644 --- a/internal/service/cloudapi/disks/utility_disk_list.go +++ b/internal/service/cloudapi/disks/utility_disk_list.go @@ -1,94 +1,97 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 disks - -import ( - "context" - "strings" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*disks.ListDisks, error) { - c := m.(*controller.ControllerCfg) - req := disks.ListRequest{} - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if account_name, ok := d.GetOk("account_name"); ok { - req.AccountName = account_name.(string) - } - if disk_max_size, ok := d.GetOk("disk_max_size"); ok { - req.DiskMaxSize = int64(disk_max_size.(int)) - } - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - if shared, ok := d.GetOk("shared"); ok { - req.Shared = shared.(bool) - } - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if diskType, ok := d.GetOk("type"); ok { - req.Type = strings.ToUpper(diskType.(string)) - } - if sepId, ok := d.GetOk("sep_id"); ok { - req.AccountID = uint64(sepId.(int)) - } - if pool_name, ok := d.GetOk("pool_name"); ok { - req.Pool = pool_name.(string) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityDiskListCheckPresence: load disk list") - diskList, err := c.CloudAPI().Disks().List(ctx, req) - if err != nil { - return nil, err - } - - return diskList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 disks + +import ( + "context" + "strings" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*disks.ListDisks, error) { + c := m.(*controller.ControllerCfg) + req := disks.ListRequest{} + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if account_name, ok := d.GetOk("account_name"); ok { + req.AccountName = account_name.(string) + } + if disk_max_size, ok := d.GetOk("disk_max_size"); ok { + req.DiskMaxSize = int64(disk_max_size.(int)) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if shared, ok := d.GetOk("shared"); ok { + req.Shared = shared.(bool) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if diskType, ok := d.GetOk("type"); ok { + req.Type = strings.ToUpper(diskType.(string)) + } + if sepId, ok := d.GetOk("sep_id"); ok { + req.AccountID = uint64(sepId.(int)) + } + if pool_name, ok := d.GetOk("pool_name"); ok { + req.Pool = pool_name.(string) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityDiskListCheckPresence: load disk list") + diskList, err := c.CloudAPI().Disks().List(ctx, req) + if err != nil { + return nil, err + } + + return diskList, nil +} diff --git a/internal/service/cloudapi/disks/utility_disk_list_deleted.go b/internal/service/cloudapi/disks/utility_disk_list_deleted.go index d44d17b..deee12c 100644 --- a/internal/service/cloudapi/disks/utility_disk_list_deleted.go +++ b/internal/service/cloudapi/disks/utility_disk_list_deleted.go @@ -54,6 +54,10 @@ func utilityDiskListDeletedCheckPresence(ctx context.Context, d *schema.Resource req.Type = typev.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/disks/utility_disk_list_unattached.go b/internal/service/cloudapi/disks/utility_disk_list_unattached.go index 458be05..8c9f59c 100644 --- a/internal/service/cloudapi/disks/utility_disk_list_unattached.go +++ b/internal/service/cloudapi/disks/utility_disk_list_unattached.go @@ -37,6 +37,9 @@ func utilityDiskListUnattachedCheckPresence(ctx context.Context, d *schema.Resou if pool_name, ok := d.GetOk("pool_name"); ok { req.Pool = pool_name.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/disks/utility_disk_replica.go b/internal/service/cloudapi/disks/utility_disk_replica.go new file mode 100644 index 0000000..0644c4a --- /dev/null +++ b/internal/service/cloudapi/disks/utility_disk_replica.go @@ -0,0 +1,174 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 disks + +import ( + "context" + "strconv" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityDiskReplicationUpdateStartStop(ctx context.Context, d *schema.ResourceData, m interface{}) error { + diskId := uint64(d.Get("disk_id").(int)) + targetDiskId, _ := strconv.ParseUint(d.Id(), 10, 64) + + log.Debugf("utilityDiskReplicationUpdateStartStop: start update for disk replica with ID: %d", diskId) + c := m.(*controller.ControllerCfg) + + start, ok := d.GetOk("start") + + if ok && start.(bool) { + log.Debugf("utilityDiskReplicationUpdateStartStop: start disk replication from Disk with ID: %d to Disk with ID: %d", diskId, targetDiskId) + req := disks.ReplicationStartRequest{ + DiskID: diskId, + TargetDiskID: targetDiskId, + } + _, err := c.CloudAPI().Disks().ReplicationStart(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdateStartStop: start disk replication from Disk with ID: %d to Disk with ID: %d, complete", diskId, targetDiskId) + } + + if ok && !start.(bool) { + log.Debugf("utilityDiskReplicationUpdateStartStop: stop disk replication from Disk with ID: %d to Disk with ID: %d", targetDiskId, diskId) + req := disks.ReplicationStopRequest{ + DiskID: targetDiskId, + } + _, err := c.CloudAPI().Disks().ReplicationStop(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdateStartStop: stop disk replication from Disk with ID: %d to Disk with ID: %d, complete", targetDiskId, diskId) + } + + log.Debugf("utilityDiskReplicationUpdateStartStop: complete update for disk replica with ID: %d", diskId) + return nil +} + +func utilityDiskReplicationUpdatePause(ctx context.Context, d *schema.ResourceData, m interface{}) error { + diskId := uint64(d.Get("disk_id").(int)) + log.Debugf("utilityDiskReplicationUpdatePause: start update for disk replica with ID: %d", diskId) + c := m.(*controller.ControllerCfg) + + pause, ok := d.GetOk("pause") + + if ok && pause.(bool) { + log.Debugf("utilityDiskReplicationUpdatePause: pause disk replication with ID: %d", diskId) + req := disks.ReplicationSuspendRequest{ + DiskID: diskId, + } + _, err := c.CloudAPI().Disks().ReplicationSuspend(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdatePause: pause disk replication with ID: %d, complete", diskId) + } + + if ok && !pause.(bool) { + log.Debugf("utilityDiskReplicationUpdatePause: resume disk replication with ID: %d", diskId) + req := disks.ReplicationResumeRequest{ + DiskID: diskId, + } + _, err := c.CloudAPI().Disks().ReplicationResume(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdatePause: resume disk replication with ID: %d, complete", diskId) + } + + log.Debugf("utilityDiskReplicationUpdatePause: complete update for disk replica with ID: %d", diskId) + return nil +} + +func utilityDiskReplicationUpdateReverse(ctx context.Context, d *schema.ResourceData, m interface{}) error { + diskId := uint64(d.Get("disk_id").(int)) + targetDiskId, _ := strconv.ParseUint(d.Id(), 10, 64) + + log.Debugf("utilityDiskReplicaUpdateReverse: start update for disk replica with ID: %d", diskId) + c := m.(*controller.ControllerCfg) + + reverse, ok := d.GetOk("reverse") + + if ok && reverse.(bool) { + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d", diskId, targetDiskId) + req := disks.ReplicationReverseRequest{ + DiskID: diskId, + } + _, err := c.CloudAPI().Disks().ReplicationReverse(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d, complete", diskId, targetDiskId) + } + + if ok && !reverse.(bool) { + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d", targetDiskId, diskId) + req := disks.ReplicationReverseRequest{ + DiskID: targetDiskId, + } + _, err := c.CloudAPI().Disks().ReplicationReverse(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d, complete", targetDiskId, diskId) + } + + log.Debugf("utilityDiskReplicaUpdateReverse: complete update for disk replica with ID: %d", diskId) + return nil +} + +func utilityDiskReplicaCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*disks.RecordDisk, error) { + c := m.(*controller.ControllerCfg) + + req := disks.GetRequest{} + + if d.Id() != "" { + diskId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.DiskID = diskId + } else { + req.DiskID = uint64(d.Get("replica_disk_id").(int)) + } + + log.Debugf("utilityDiskReplicaCheckPresence: load disk") + disk, err := c.CloudAPI().Disks().Get(ctx, req) + if err != nil { + return nil, err + } + + return disk, nil +} diff --git a/internal/service/cloudapi/disks/utility_disk_types_detailed_list.go b/internal/service/cloudapi/disks/utility_disk_types_detailed_list.go index cdd06bf..69665d4 100644 --- a/internal/service/cloudapi/disks/utility_disk_types_detailed_list.go +++ b/internal/service/cloudapi/disks/utility_disk_types_detailed_list.go @@ -46,7 +46,10 @@ func utilityDiskListTypesDetailedCheckPresence(ctx context.Context, d *schema.Re req := disks.ListTypesRequest{ Detailed: true, } - + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/disks/utility_disk_types_list.go b/internal/service/cloudapi/disks/utility_disk_types_list.go index e5093fe..4118344 100644 --- a/internal/service/cloudapi/disks/utility_disk_types_list.go +++ b/internal/service/cloudapi/disks/utility_disk_types_list.go @@ -47,6 +47,9 @@ func utilityDiskListTypesCheckPresence(ctx context.Context, d *schema.ResourceDa Detailed: false, } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go index 555ed10..8f4ad35 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_computes_list.go @@ -72,6 +72,11 @@ func dataSourceExtnetComputesListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by compute ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/extnet/data_source_extnet_list.go b/internal/service/cloudapi/extnet/data_source_extnet_list.go index 3442382..c104000 100644 --- a/internal/service/cloudapi/extnet/data_source_extnet_list.go +++ b/internal/service/cloudapi/extnet/data_source_extnet_list.go @@ -92,6 +92,11 @@ func dataSourceExtnetListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/extnet/utility_extnet_computes_list.go b/internal/service/cloudapi/extnet/utility_extnet_computes_list.go index 7f21314..4f9a2d8 100644 --- a/internal/service/cloudapi/extnet/utility_extnet_computes_list.go +++ b/internal/service/cloudapi/extnet/utility_extnet_computes_list.go @@ -1,72 +1,74 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityExtnetComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*extnet.ListExtNetComputes, error) { - c := m.(*controller.ControllerCfg) - req := extnet.ListComputesRequest{ - AccountID: uint64(d.Get("account_id").(int)), - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - if compute_id, ok := d.GetOk("compute_id"); ok { - req.ComputeID = uint64(compute_id.(int)) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - - log.Debugf("utilityExtnetComputesListCheckPresence") - extnetComputesList, err := c.CloudAPI().ExtNet().ListComputes(ctx, req) - if err != nil { - return nil, err - } - - return extnetComputesList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityExtnetComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*extnet.ListExtNetComputes, error) { + c := m.(*controller.ControllerCfg) + req := extnet.ListComputesRequest{ + AccountID: uint64(d.Get("account_id").(int)), + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + if compute_id, ok := d.GetOk("compute_id"); ok { + req.ComputeID = uint64(compute_id.(int)) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityExtnetComputesListCheckPresence") + extnetComputesList, err := c.CloudAPI().ExtNet().ListComputes(ctx, req) + if err != nil { + return nil, err + } + + return extnetComputesList, nil +} diff --git a/internal/service/cloudapi/extnet/utility_extnet_list.go b/internal/service/cloudapi/extnet/utility_extnet_list.go index ee45ea2..4f9b29b 100644 --- a/internal/service/cloudapi/extnet/utility_extnet_list.go +++ b/internal/service/cloudapi/extnet/utility_extnet_list.go @@ -1,84 +1,87 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityExtnetListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*extnet.ListExtNets, error) { - c := m.(*controller.ControllerCfg) - req := extnet.ListRequest{} - - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if network, ok := d.GetOk("network"); ok { - req.Network = network.(string) - } - if vlan_id, ok := d.GetOk("vlan_id"); ok { - req.VLANID = uint64(vlan_id.(int)) - } - if vnfdev_id, ok := d.GetOk("vnfdev_id"); ok { - req.VNFDevID = uint64(vnfdev_id.(int)) - } - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityExtnetListCheckPresence") - extnetList, err := c.CloudAPI().ExtNet().List(ctx, req) - if err != nil { - return nil, err - } - - return extnetList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityExtnetListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*extnet.ListExtNets, error) { + c := m.(*controller.ControllerCfg) + req := extnet.ListRequest{} + + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if network, ok := d.GetOk("network"); ok { + req.Network = network.(string) + } + if vlan_id, ok := d.GetOk("vlan_id"); ok { + req.VLANID = uint64(vlan_id.(int)) + } + if vnfdev_id, ok := d.GetOk("vnfdev_id"); ok { + req.VNFDevID = uint64(vnfdev_id.(int)) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityExtnetListCheckPresence") + extnetList, err := c.CloudAPI().ExtNet().List(ctx, req) + if err != nil { + return nil, err + } + + return extnetList, nil +} diff --git a/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go b/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go index fa0cde0..90aa3a7 100644 --- a/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go +++ b/internal/service/cloudapi/flipgroup/data_source_flipgroup_list.go @@ -95,6 +95,11 @@ func dataSourceFlipgroupListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by RG ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -105,6 +110,29 @@ func dataSourceFlipgroupListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Page size", }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Account id", + }, + "conn_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Conn id", + }, + "client_ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "client_ids", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Status", + }, "items": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudapi/flipgroup/utility_flipgroup.go b/internal/service/cloudapi/flipgroup/utility_flipgroup.go index 0151443..c423f9f 100644 --- a/internal/service/cloudapi/flipgroup/utility_flipgroup.go +++ b/internal/service/cloudapi/flipgroup/utility_flipgroup.go @@ -153,38 +153,48 @@ func utilityFlipgroupListCheckPresence(ctx context.Context, d *schema.ResourceDa if name, ok := d.GetOk("name"); ok { req.Name = name.(string) } - if vinsId, ok := d.GetOk("vins_id"); ok { req.VINSID = uint64(vinsId.(int)) } - if vinsName, ok := d.GetOk("vins_name"); ok { req.VINSName = vinsName.(string) } - if extNetId, ok := d.GetOk("extnet_id"); ok { req.ExtNetID = uint64(extNetId.(int)) } - if byIp, ok := d.GetOk("by_ip"); ok { req.ByIP = byIp.(string) } - if rgId, ok := d.GetOk("rg_id"); ok { req.RGID = uint64(rgId.(int)) } - if byId, ok := d.GetOk("by_id"); ok { req.ByID = uint64(byId.(int)) } - + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } - if size, ok := d.GetOk("size"); ok { req.Size = uint64(size.(int)) } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountId = uint64(accountId.(int)) + } + if connId, ok := d.GetOk("conn_id"); ok { + req.ConnId = uint64(connId.(int)) + } + if cliensId, ok := d.GetOk("client_ids"); ok { + cliensIds := cliensId.([]interface{}) + for _, elem := range cliensIds { + req.ClientIDs = append(req.ClientIDs, uint64(elem.(int))) + } + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } fg_list, err := c.CloudAPI().FLIPGroup().List(ctx, req) if err != nil { diff --git a/internal/service/cloudapi/image/data_source_image_list.go b/internal/service/cloudapi/image/data_source_image_list.go index 58438c6..4ad5494 100644 --- a/internal/service/cloudapi/image/data_source_image_list.go +++ b/internal/service/cloudapi/image/data_source_image_list.go @@ -117,6 +117,11 @@ func dataSourceImageListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find bootable images", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/image/flattens.go b/internal/service/cloudapi/image/flattens.go index 8288f99..916f777 100644 --- a/internal/service/cloudapi/image/flattens.go +++ b/internal/service/cloudapi/image/flattens.go @@ -1,9 +1,11 @@ package image import ( + "encoding/json" + "strconv" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image" - "strconv" ) func flattenHistory(history []image.History) []map[string]interface{} { @@ -21,6 +23,8 @@ func flattenHistory(history []image.History) []map[string]interface{} { } func flattenImage(d *schema.ResourceData, img *image.RecordImage) { + cdPresentedTo, _ := json.Marshal(img.CdPresentedTo) + d.Set("unc_path", img.UNCPath) d.Set("ckey", img.CKey) d.Set("account_id", img.AccountID) @@ -29,6 +33,7 @@ func flattenImage(d *schema.ResourceData, img *image.RecordImage) { d.Set("boot_type", img.BootType) d.Set("bootable", img.Bootable) d.Set("compute_ci_id", img.ComputeCIID) + d.Set("cd_presented_to", string(cdPresentedTo)) d.Set("deleted_time", img.DeletedTime) d.Set("desc", img.Description) d.Set("drivers", img.Drivers) @@ -42,6 +47,7 @@ func flattenImage(d *schema.ResourceData, img *image.RecordImage) { d.Set("link_to", img.LinkTo) d.Set("milestones", img.Milestones) d.Set("image_name", img.Name) + d.Set("network_interface_naming", img.NetworkInterfaceNaming) d.Set("password", img.Password) d.Set("pool_name", img.Pool) d.Set("provider_name", img.ProviderName) @@ -63,24 +69,25 @@ func flattenImageList(il *image.ListImages) []map[string]interface{} { res := make([]map[string]interface{}, 0) for _, img := range il.Data { temp := map[string]interface{}{ - "account_id": img.AccountID, - "architecture": img.Architecture, - "boot_type": img.BootType, - "bootable": img.Bootable, - "cdrom": img.CDROM, - "desc": img.Description, - "drivers": img.Drivers, - "hot_resize": img.HotResize, - "image_id": img.ID, - "link_to": img.LinkTo, - "image_name": img.Name, - "pool_name": img.Pool, - "sep_id": img.SepID, - "size": img.Size, - "status": img.Status, - "type": img.Type, - "username": img.Username, - "virtual": img.Virtual, + "account_id": img.AccountID, + "architecture": img.Architecture, + "boot_type": img.BootType, + "bootable": img.Bootable, + "cdrom": img.CDROM, + "desc": img.Description, + "drivers": img.Drivers, + "hot_resize": img.HotResize, + "image_id": img.ID, + "link_to": img.LinkTo, + "image_name": img.Name, + "network_interface_naming": img.NetworkInterfaceNaming, + "pool_name": img.Pool, + "sep_id": img.SepID, + "size": img.Size, + "status": img.Status, + "type": img.Type, + "username": img.Username, + "virtual": img.Virtual, } res = append(res, temp) } diff --git a/internal/service/cloudapi/image/image_ds_subresource.go b/internal/service/cloudapi/image/image_ds_subresource.go index c3323bd..e0fc599 100644 --- a/internal/service/cloudapi/image/image_ds_subresource.go +++ b/internal/service/cloudapi/image/image_ds_subresource.go @@ -1,216 +1,222 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 image - -import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - -func dataSourceImageExtendSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "image_id": { - Type: schema.TypeInt, - Required: true, - }, - "show_all": { - Type: schema.TypeBool, - Default: false, - Optional: true, - }, - - "unc_path": { - Type: schema.TypeString, - Computed: true, - }, - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "acl": { - Type: schema.TypeString, - Computed: true, - }, - "architecture": { - Type: schema.TypeString, - Computed: true, - }, - "boot_type": { - Type: schema.TypeString, - Computed: true, - }, - "bootable": { - Type: schema.TypeBool, - Computed: true, - }, - "compute_ci_id": { - Type: schema.TypeInt, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "desc": { - Type: schema.TypeString, - Computed: true, - }, - "drivers": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "history": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "id": { - Type: schema.TypeInt, - Computed: true, - }, - "timestamp": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "hot_resize": { - Type: schema.TypeBool, - Computed: true, - }, - - "last_modified": { - Type: schema.TypeInt, - Computed: true, - }, - "link_to": { - Type: schema.TypeInt, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "image_name": { - Type: schema.TypeString, - Computed: true, - }, - "password": { - Type: schema.TypeString, - Computed: true, - }, - "pool_name": { - Type: schema.TypeString, - Computed: true, - }, - "provider_name": { - Type: schema.TypeString, - Computed: true, - }, - "purge_attempts": { - Type: schema.TypeInt, - Computed: true, - }, - "present_to": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "res_id": { - Type: schema.TypeString, - Computed: true, - }, - "rescuecd": { - Type: schema.TypeBool, - Computed: true, - }, - "sep_id": { - Type: schema.TypeInt, - Computed: true, - }, - "shared_with": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "size": { - Type: schema.TypeInt, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "tech_status": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - "username": { - Type: schema.TypeString, - Computed: true, - }, - "version": { - Type: schema.TypeString, - Computed: true, - }, - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 image + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceImageExtendSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "image_id": { + Type: schema.TypeInt, + Required: true, + }, + "show_all": { + Type: schema.TypeBool, + Default: false, + Optional: true, + }, + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "architecture": { + Type: schema.TypeString, + Computed: true, + }, + "boot_type": { + Type: schema.TypeString, + Computed: true, + }, + "bootable": { + Type: schema.TypeBool, + Computed: true, + }, + "compute_ci_id": { + Type: schema.TypeInt, + Computed: true, + }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "drivers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "history": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "hot_resize": { + Type: schema.TypeBool, + Computed: true, + }, + "last_modified": { + Type: schema.TypeInt, + Computed: true, + }, + "link_to": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "image_name": { + Type: schema.TypeString, + Computed: true, + }, + "network_interface_naming": { + Type: schema.TypeString, + Computed: true, + }, + "password": { + Type: schema.TypeString, + Computed: true, + }, + "pool_name": { + Type: schema.TypeString, + Computed: true, + }, + "provider_name": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "rescuecd": { + Type: schema.TypeBool, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "shared_with": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "username": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + } +} diff --git a/internal/service/cloudapi/image/image_item_subresource.go b/internal/service/cloudapi/image/image_item_subresource.go index 6194f4d..65f7a10 100644 --- a/internal/service/cloudapi/image/image_item_subresource.go +++ b/internal/service/cloudapi/image/image_item_subresource.go @@ -94,6 +94,10 @@ func dataSourceImageSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Image name", }, + "network_interface_naming": { + Type: schema.TypeString, + Computed: true, + }, "pool_name": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/image/image_rs_subresource.go b/internal/service/cloudapi/image/image_rs_subresource.go index 5bdb158..14f277f 100644 --- a/internal/service/cloudapi/image/image_rs_subresource.go +++ b/internal/service/cloudapi/image/image_rs_subresource.go @@ -1,159 +1,160 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 image - -import ( - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" -) - -func resourceImageSchemaMake(sch map[string]*schema.Schema) map[string]*schema.Schema { - delete(sch, "show_all") - sch["name"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "Name of the rescue disk", - } - - sch["url"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "URL where to download media from", - } - - sch["gid"] = &schema.Schema{ - Type: schema.TypeInt, - Required: true, - Description: "grid (platform) ID where this template should be create in", - } - - sch["image_id"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Computed: true, - Description: "image id", - } - - sch["boot_type"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true), - Description: "Boot type of image bios or uefi", - } - - sch["type"] = &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "other"}, true), - Description: "Image type linux, windows or other", - } - - sch["hot_resize"] = &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - Computed: true, - Description: "Does this machine supports hot resize", - } - - sch["username"] = &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "Optional username for the image", - } - - sch["password"] = &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "Optional password for the image", - } - - sch["account_id"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Computed: true, - Description: "AccountId to make the image exclusive", - } - - sch["username_dl"] = &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "username for upload binary media", - } - - sch["password_dl"] = &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "password for upload binary media", - } - - sch["pool_name"] = &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - Description: "pool for image create", - } - - sch["sep_id"] = &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Computed: true, - Description: "storage endpoint provider ID", - } - - sch["architecture"] = &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{"X86_64", "PPC64_LE"}, true), - Description: "binary architecture of this image, one of X86_64 of PPC64_LE", - } - - sch["drivers"] = &schema.Schema{ - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - } - - sch["permanently"] = &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "whether to completely delete the image", - } - - return sch -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 image + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceImageSchemaMake(sch map[string]*schema.Schema) map[string]*schema.Schema { + delete(sch, "show_all") + sch["name"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Name of the rescue disk", + } + + sch["url"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "URL where to download media from", + } + + sch["image_id"] = &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "image id", + } + + sch["boot_type"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true), + Description: "Boot type of image bios or uefi", + } + + sch["type"] = &schema.Schema{ + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "other"}, true), + Description: "Image type linux, windows or other", + } + + sch["hot_resize"] = &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this machine supports hot resize", + } + + sch["username"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional username for the image", + } + + sch["password"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional password for the image", + } + + sch["account_id"] = &schema.Schema{ + Type: schema.TypeInt, + Required: true, + Description: "AccountId to make the image exclusive", + } + + sch["username_dl"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "username for upload binary media", + } + + sch["password_dl"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "password for upload binary media", + } + + sch["pool_name"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "pool for image create", + } + + sch["sep_id"] = &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "storage endpoint provider ID", + } + + sch["architecture"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"X86_64", "PPC64_LE"}, true), + Description: "binary architecture of this image, one of X86_64 of PPC64_LE", + } + + sch["drivers"] = &schema.Schema{ + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + } + + sch["permanently"] = &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the image", + } + + sch["network_interface_naming"] = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"eth", "ens"}, true), + Description: "select a network interface naming pattern for your Linux machine. eth - onboard, ens - pci slot naming", + } + + return sch +} diff --git a/internal/service/cloudapi/image/resource_check_input_values.go b/internal/service/cloudapi/image/resource_check_input_values.go index 8d34576..cc6d69a 100644 --- a/internal/service/cloudapi/image/resource_check_input_values.go +++ b/internal/service/cloudapi/image/resource_check_input_values.go @@ -2,9 +2,12 @@ package image import ( "context" + "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/account" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" ) @@ -34,3 +37,46 @@ func existGID(ctx context.Context, d *schema.ResourceData, m interface{}) (bool, return len(locationList.FilterByGID(gid).Data) != 0, nil } + +func existComputeID(ctx context.Context, computeId uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + req := compute.GetRequest{ComputeID: computeId} + + // check for compute existence + computeRecord, err := c.CloudAPI().Compute().Get(ctx, req) + if err != nil { + return fmt.Errorf("ComputeID %d is not allowed or does not exist", computeId) + } + + // check if compute was created as blank + computeImageId := computeRecord.ImageID + bootImageId := -1 + for _, d := range computeRecord.Disks { + if d.Type == "B" { + bootImageId = int(d.ImageID) + break + } + } + + if computeImageId != 0 && bootImageId != 0 { + return fmt.Errorf("ComputeID %d is not allowed because it is not blank compute (either compute imageId or boot imageId are not zero)", computeId) + } + + return nil +} + +func existDiskID(ctx context.Context, diskId uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + req := disks.ListRequest{ByID: diskId} + + diskList, err := c.CloudAPI().Disks().List(ctx, req) + if err != nil { + return err + } + + if len(diskList.Data) != 1 { + return fmt.Errorf("diskId %d is not allowed or doesn't exist", diskId) + } + + return nil +} diff --git a/internal/service/cloudapi/image/resource_image.go b/internal/service/cloudapi/image/resource_image.go index 035ef5e..1452fa4 100644 --- a/internal/service/cloudapi/image/resource_image.go +++ b/internal/service/cloudapi/image/resource_image.go @@ -48,34 +48,23 @@ import ( func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageCreate: called for image %s", d.Get("name").(string)) - haveGID, err := existGID(ctx, d, m) + haveAccountID, err := existAccountID(ctx, d, m) if err != nil { return diag.FromErr(err) } - if !haveGID { - return diag.Errorf("resourceImageCreate: can't create Image because GID %d is not allowed or does not exist", d.Get("gid").(int)) - } - - if _, ok := d.GetOk("account_id"); ok { - haveAccountID, err := existAccountID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveAccountID { - return diag.Errorf("resourceImageCreate: can't create Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) - } + if !haveAccountID { + return diag.Errorf("resourceImageCreate: can't create Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) } c := m.(*controller.ControllerCfg) - req := image.CreateRequest{} - - req.Name = d.Get("name").(string) - req.URL = d.Get("url").(string) - req.GID = uint64(d.Get("gid").(int)) - req.BootType = d.Get("boot_type").(string) - req.ImageType = d.Get("type").(string) + req := image.CreateRequest{ + AccountID: uint64(d.Get("account_id").(int)), + Name: d.Get("name").(string), + URL: d.Get("url").(string), + BootType: d.Get("boot_type").(string), + ImageType: d.Get("type").(string), + } drivers := []string{} for _, driver := range d.Get("drivers").([]interface{}) { @@ -93,9 +82,6 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac if password, ok := d.GetOk("password"); ok { req.Password = password.(string) } - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } if usernameDL, ok := d.GetOk("username_dl"); ok { req.UsernameDL = usernameDL.(string) } @@ -111,6 +97,9 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac if architecture, ok := d.GetOk("architecture"); ok { req.Architecture = architecture.(string) } + if networkInterfaceNaming, ok := d.GetOk("network_interface_naming"); ok { + req.NetworkInterfaceNaming = networkInterfaceNaming.(string) + } imageId, err := c.CloudAPI().Image().Create(ctx, req) if err != nil { @@ -210,15 +199,13 @@ func resourceImageUpdate(ctx context.Context, d *schema.ResourceData, m interfac return diag.Errorf("resourceImageUpdate: can't update Image because GID %d is not allowed or does not exist", d.Get("gid").(int)) } - if _, ok := d.GetOk("account_id"); ok { - haveAccountID, err := existAccountID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } + haveAccountID, err := existAccountID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } - if !haveAccountID { - return diag.Errorf("resourceImageUpdate: can't update Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) - } + if !haveAccountID { + return diag.Errorf("resourceImageUpdate: can't update Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) } image, err := utilityImageCheckPresence(ctx, d, m) diff --git a/internal/service/cloudapi/image/resource_image_from_blank_compute.go b/internal/service/cloudapi/image/resource_image_from_blank_compute.go new file mode 100644 index 0000000..c5e42c0 --- /dev/null +++ b/internal/service/cloudapi/image/resource_image_from_blank_compute.go @@ -0,0 +1,508 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 image + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/compute" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks" + "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/status" +) + +func resourceImageFromBlankComputeCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + computeId := uint64(d.Get("compute_id").(int)) + name := d.Get("name").(string) + + log.Debugf("resourceImageFromBlankComputeCreate: called for image %s", name) + + err := existComputeID(ctx, computeId, m) + if err != nil { + return diag.Errorf("resourceImageFromBlankComputeCreate: can't create Image: %v", err) + } + + if _, ok := d.GetOk("account_id"); ok { + haveAccountID, err := existAccountID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveAccountID { + return diag.Errorf("resourceImageFromBlankComputeCreate: can't create Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) + } + } + + c := m.(*controller.ControllerCfg) + req := compute.CreateTemplateFromBlankRequest{ + ComputeID: computeId, + Name: name, + BootType: d.Get("boot_type").(string), + ImageType: d.Get("type").(string), + } + + if username, ok := d.GetOk("username"); ok { + req.Username = username.(string) + } + if password, ok := d.GetOk("password"); ok { + req.Password = password.(string) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if sepId, ok := d.GetOk("sep_id"); ok { + req.SepID = uint64(sepId.(int)) + } + if poolName, ok := d.GetOk("pool_name"); ok { + req.PoolName = poolName.(string) + } + if hotresize, ok := d.GetOk("hot_resize"); ok { + req.HotResize = hotresize.(bool) + } + + var imageId uint64 + asyncMode := d.Get("async_mode").(bool) + if !asyncMode { + imageId, err = c.CloudAPI().Compute().CreateTemplateFromBlank(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } else { + taskId, err := c.CloudAPI().Compute().CreateTemplateFromBlankAsync(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + taskReq := tasks.GetRequest{ + AuditID: strings.Trim(taskId, `"`), + } + + for { + task, err := c.CloudAPI().Tasks().Get(ctx, taskReq) + if err != nil { + return diag.FromErr(err) + } + + log.Debugf("resourceImageFromBlankComputeCreate: instance creating - %s", task.Stage) + + if task.Completed { + if task.Error != "" { + return diag.FromErr(fmt.Errorf("cannot create image instance: %v", task.Error)) + } + + id, err := task.Result.ID() + imageId = uint64(id) + if err != nil { + return diag.FromErr(err) + } + break + } + + time.Sleep(time.Second * 20) + } + } + + d.SetId(strconv.FormatUint(imageId, 10)) + d.Set("image_id", imageId) + + _, err = utilityImageCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + return resourceImageFromBlankComputeRead(ctx, d, m) +} + +func resourceImageFromBlankComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromBlankComputeRead: called for %s id: %s", d.Get("name").(string), d.Id()) + + img, err := utilityImageCheckPresence(ctx, d, m) + if img == nil { + d.SetId("") + return diag.FromErr(err) + } + + switch img.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) + case status.Creating: + case status.Created: + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceImageCreate(ctx, d, m) + } + + flattenImage(d, img) + + return nil +} + +func resourceImageFromBlankComputeDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromBlankComputeDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) + + _, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := image.DeleteRequest{ + ImageID: uint64(d.Get("image_id").(int)), + } + + if permanently, ok := d.GetOk("permanently"); ok { + req.Permanently = permanently.(bool) + } + + _, err = c.CloudAPI().Image().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceImageFromBlankComputeRename(ctx context.Context, d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceImageFromBlankComputeRename: called for %s, id: %s", d.Get("name").(string), d.Id()) + c := m.(*controller.ControllerCfg) + req := image.RenameRequest{ + ImageID: uint64(d.Get("image_id").(int)), + Name: d.Get("name").(string), + } + + _, err := c.CloudAPI().Image().Rename(ctx, req) + if err != nil { + return err + } + + return nil +} + +func resourceImageFromBlankComputeUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromBlankComputeUpdate: called for %s, id: %s", d.Get("name").(string), d.Id()) + + // we do not allow change of compute_id, but allow resource update after import + old, _ := d.GetChange("compute_id") + if old.(int) != 0 && d.HasChange("compute_id") { + return diag.Errorf("resourceImageFromBlankComputeUpdate: can't update Image because compute_id is not allowed to be changed") + } + + image, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + switch image.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", image.Status) + case status.Creating: + case status.Created: + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceImageCreate(ctx, d, m) + } + + if d.HasChange("name") { + err := resourceImageFromBlankComputeRename(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + return resourceImageFromBlankComputeRead(ctx, d, m) +} + +func ResourceImageFromBlankCompute() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceImageFromBlankComputeCreate, + ReadContext: resourceImageFromBlankComputeRead, + UpdateContext: resourceImageFromBlankComputeUpdate, + DeleteContext: resourceImageFromBlankComputeDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout30m, + Read: &constants.Timeout900s, + Update: &constants.Timeout900s, + Delete: &constants.Timeout900s, + Default: &constants.Timeout900s, + }, + + Schema: resourceImageFromBlankComputeSchemaMake(), + } +} + +func resourceImageFromBlankComputeSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeInt, + Required: true, + Description: "Compute Id", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the rescue disk", + }, + "boot_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true), + Description: "Boot type of image BIOS or UEFI", + }, + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "other"}, true), + Description: "Image type linux, windows or other", + }, + + "username": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional username for the image", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional password for the image", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "AccountId to make the image exclusive", + }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "storage endpoint provider ID", + }, + "pool_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "pool for image create", + }, + "hot_resize": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this machine supports hot resize", + }, + "async_mode": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "create an image in async/sync mode", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the image", + }, + + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "architecture": { + Type: schema.TypeString, + Computed: true, + }, + "bootable": { + Type: schema.TypeBool, + Computed: true, + }, + "compute_ci_id": { + Type: schema.TypeInt, + Computed: true, + }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "drivers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "history": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "last_modified": { + Type: schema.TypeInt, + Computed: true, + }, + "link_to": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "image_name": { + Type: schema.TypeString, + Computed: true, + }, + "network_interface_naming": { + Type: schema.TypeString, + Computed: true, + }, + "provider_name": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "rescuecd": { + Type: schema.TypeBool, + Computed: true, + }, + "shared_with": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + } +} diff --git a/internal/service/cloudapi/image/resource_image_from_platform_disk.go b/internal/service/cloudapi/image/resource_image_from_platform_disk.go new file mode 100644 index 0000000..787a7ec --- /dev/null +++ b/internal/service/cloudapi/image/resource_image_from_platform_disk.go @@ -0,0 +1,506 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 image + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks" + "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/statefuncs" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" +) + +func resourceImageFromPlatformDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskId := uint64(d.Get("disk_id").(int)) + name := d.Get("name").(string) + + log.Debugf("resourceImageFromPlatformDiskCreate: called for image %s", name) + + err := existDiskID(ctx, diskId, m) + if err != nil { + return diag.Errorf("resourceImageFromPlatformDiskCreate: can't create Image: %v", err) + } + + if _, ok := d.GetOk("account_id"); ok { + haveAccountID, err := existAccountID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveAccountID { + return diag.Errorf("resourceImageFromPlatformDiskCreate: can't create Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int)) + } + } + + c := m.(*controller.ControllerCfg) + req := disks.FromPlatformDiskRequest{ + DiskID: diskId, + Name: name, + BootType: d.Get("boot_type").(string), + ImageType: d.Get("type").(string), + Architecture: d.Get("architecture").(string), + Bootable: d.Get("bootable").(bool), // default value - true + } + + if username, ok := d.GetOk("username"); ok { + req.Username = username.(string) + } + if password, ok := d.GetOk("password"); ok { + req.Password = password.(string) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if sepId, ok := d.GetOk("sep_id"); ok { + req.SepID = uint64(sepId.(int)) + } + if poolName, ok := d.GetOk("pool_name"); ok { + req.PoolName = poolName.(string) + } + if driversInterface, ok := d.GetOk("drivers"); ok { + for _, d := range driversInterface.([]interface{}) { + req.Drivers = append(req.Drivers, d.(string)) + } + } + if hotresize, ok := d.GetOk("hot_resize"); ok { + req.HotResize = hotresize.(bool) + } + + var imageId uint64 + asyncMode := d.Get("async_mode").(bool) + if !asyncMode { + imageId, err = c.CloudAPI().Disks().FromPlatformDisk(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } else { + taskId, err := c.CloudAPI().Disks().FromPlatformDiskAsync(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + taskReq := tasks.GetRequest{ + AuditID: strings.Trim(taskId, `"`), + } + + for { + task, err := c.CloudAPI().Tasks().Get(ctx, taskReq) + if err != nil { + return diag.FromErr(err) + } + + log.Debugf("resourceImageFromPlatformDiskCreate: instance creating - %s", task.Stage) + + if task.Completed { + if task.Error != "" { + return diag.FromErr(fmt.Errorf("cannot create image instance: %v", task.Error)) + } + + id, err := task.Result.ID() + imageId = uint64(id) + if err != nil { + return diag.FromErr(err) + } + break + } + + time.Sleep(time.Second * 20) + } + } + + d.SetId(strconv.FormatUint(imageId, 10)) + d.Set("image_id", imageId) + + _, err = utilityImageCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + return resourceImageFromPlatformDiskRead(ctx, d, m) +} + +func resourceImageFromPlatformDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromPlatformDiskRead: called for %s id: %s", d.Get("name").(string), d.Id()) + + img, err := utilityImageCheckPresence(ctx, d, m) + if img == nil { + d.SetId("") + return diag.FromErr(err) + } + + switch img.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) + case status.Creating: + case status.Created: + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + } + + flattenImage(d, img) + + return nil +} + +func resourceImageFromPlatformDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromPlatformDiskDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) + + _, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := image.DeleteRequest{ + ImageID: uint64(d.Get("image_id").(int)), + } + + if permanently, ok := d.GetOk("permanently"); ok { + req.Permanently = permanently.(bool) + } + + _, err = c.CloudAPI().Image().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceImageFromPlatformDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromPlatformDiskUpdate: called for %s, id: %s", d.Get("name").(string), d.Id()) + + // we do not allow change of disk_id, but allow resource update after import + old, _ := d.GetChange("disk_id") + if old.(int) != 0 && d.HasChange("disk_id") { + return diag.Errorf("resourceImageFromPlatformDiskUpdate: can't update Image because disk_id is not allowed to be changed") + } + + image, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + switch image.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", image.Status) + case status.Creating: + case status.Created: + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + } + + if d.HasChange("name") { + err := resourceImageRename(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + return resourceImageFromPlatformDiskRead(ctx, d, m) +} + +func ResourceImageFromPlatformDisk() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceImageFromPlatformDiskCreate, + ReadContext: resourceImageFromPlatformDiskRead, + UpdateContext: resourceImageFromPlatformDiskUpdate, + DeleteContext: resourceImageFromPlatformDiskDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout30m, + Read: &constants.Timeout900s, + Update: &constants.Timeout900s, + Delete: &constants.Timeout900s, + Default: &constants.Timeout900s, + }, + + Schema: resourceImageFromPlatformDiskSchemaMake(), + } +} + +func resourceImageFromPlatformDiskSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Disk Id", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the rescue disk", + }, + "boot_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true), + Description: "Boot type of image BIOS or UEFI", + }, + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "other"}, true), + Description: "Image type linux, windows or other", + }, + "architecture": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"X86_64", "PPC64_LE"}, true), + Description: "binary architecture of this image, one of X86_64 of PPC64_LE", + }, + + "username": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional username for the image", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional password for the image", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "AccountId to make the image exclusive", + }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "storage endpoint provider ID", + }, + "pool_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "pool for image create", + }, + "drivers": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + StateFunc: statefuncs.StateFuncToUpper, + ValidateFunc: validation.StringInSlice([]string{"SVA_KVM_X86", "KVM_X86", "KVM_PPC"}, false), // observe case while validating + Type: schema.TypeString, + }, + Description: "List of types of compute suitable for image. Example: [ \"KVM_X86\" ]", + }, + "bootable": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "bootable image", + }, + "hot_resize": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this machine supports hot resize", + }, + "async_mode": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "create an image in async/sync mode", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the image", + }, + + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "compute_ci_id": { + Type: schema.TypeInt, + Computed: true, + }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "history": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "last_modified": { + Type: schema.TypeInt, + Computed: true, + }, + "link_to": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "image_name": { + Type: schema.TypeString, + Computed: true, + }, + "network_interface_naming": { + Type: schema.TypeString, + Computed: true, + }, + "provider_name": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "rescuecd": { + Type: schema.TypeBool, + Computed: true, + }, + "shared_with": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + } +} diff --git a/internal/service/cloudapi/image/utility_image_list.go b/internal/service/cloudapi/image/utility_image_list.go index a4c1b71..b7f73a6 100644 --- a/internal/service/cloudapi/image/utility_image_list.go +++ b/internal/service/cloudapi/image/utility_image_list.go @@ -1,111 +1,115 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 image - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*image.ListImages, error) { - c := m.(*controller.ControllerCfg) - req := image.ListRequest{} - - if sep_id, ok := d.GetOk("sep_id"); ok { - req.SEPID = uint64(sep_id.(int)) - } - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - if architecture, ok := d.GetOk("architecture"); ok { - req.Architecture = architecture.(string) - } - - if type_image, ok := d.GetOk("type_image"); ok { - req.TypeImage = type_image.(string) - } - - if image_size, ok := d.GetOk("image_size"); ok { - req.ImageSize = uint64(image_size.(int)) - } - - if sep_name, ok := d.GetOk("sep_name"); ok { - req.SEPName = sep_name.(string) - } - - if pool, ok := d.GetOk("pool"); ok { - req.Pool = pool.(string) - } - - if public, ok := d.GetOk("public"); ok { - req.Public = public.(bool) - } - - if hot_resize, ok := d.GetOk("hot_resize"); ok { - req.HotResize = hot_resize.(bool) - } - - if bootable, ok := d.GetOk("bootable"); ok { - req.Bootable = bootable.(bool) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityImageListCheckPresence: load image list") - imageList, err := c.CloudAPI().Image().List(ctx, req) - if err != nil { - return nil, err - } - - return imageList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 image + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*image.ListImages, error) { + c := m.(*controller.ControllerCfg) + req := image.ListRequest{} + + if sep_id, ok := d.GetOk("sep_id"); ok { + req.SEPID = uint64(sep_id.(int)) + } + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + if architecture, ok := d.GetOk("architecture"); ok { + req.Architecture = architecture.(string) + } + + if type_image, ok := d.GetOk("type_image"); ok { + req.TypeImage = type_image.(string) + } + + if image_size, ok := d.GetOk("image_size"); ok { + req.ImageSize = uint64(image_size.(int)) + } + + if sep_name, ok := d.GetOk("sep_name"); ok { + req.SEPName = sep_name.(string) + } + + if pool, ok := d.GetOk("pool"); ok { + req.Pool = pool.(string) + } + + if public, ok := d.GetOk("public"); ok { + req.Public = public.(bool) + } + + if hot_resize, ok := d.GetOk("hot_resize"); ok { + req.HotResize = hot_resize.(bool) + } + + if bootable, ok := d.GetOk("bootable"); ok { + req.Bootable = bootable.(bool) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityImageListCheckPresence: load image list") + imageList, err := c.CloudAPI().Image().List(ctx, req) + if err != nil { + return nil, err + } + + return imageList, nil +} diff --git a/internal/service/cloudapi/k8s/data_source_k8ci_list.go b/internal/service/cloudapi/k8s/data_source_k8ci_list.go index ad68111..2a4a102 100644 --- a/internal/service/cloudapi/k8s/data_source_k8ci_list.go +++ b/internal/service/cloudapi/k8s/data_source_k8ci_list.go @@ -94,6 +94,11 @@ func dataSourceK8CIListSchemaMake() map[string]*schema.Schema { Default: false, Description: "Include deleted k8cis in result", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/k8s/data_source_k8s_list.go b/internal/service/cloudapi/k8s/data_source_k8s_list.go index 82f7852..bda432b 100644 --- a/internal/service/cloudapi/k8s/data_source_k8s_list.go +++ b/internal/service/cloudapi/k8s/data_source_k8s_list.go @@ -179,6 +179,11 @@ func createK8sListSchema() map[string]*schema.Schema { Type: schema.TypeBool, Optional: true, }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/k8s/node_subresource.go b/internal/service/cloudapi/k8s/node_subresource.go index d204f20..c448d34 100644 --- a/internal/service/cloudapi/k8s/node_subresource.go +++ b/internal/service/cloudapi/k8s/node_subresource.go @@ -75,8 +75,8 @@ func mastersSchemaMake() map[string]*schema.Schema { masters["num"] = &schema.Schema{ Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntInSlice([]int{1, 3}), - Description: "Number of nodes to create. Can be either 1 or 3", + ValidateFunc: validation.IntInSlice([]int{1, 3, 5}), + Description: "Number of nodes to create. Can be either 1, 3 or 5", } masters["sep_id"] = &schema.Schema{ Type: schema.TypeInt, @@ -97,8 +97,8 @@ func mastersSchemaMake() map[string]*schema.Schema { Required: true, //ForceNew: true, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), Description: "Node RAM in MB.", } @@ -125,8 +125,8 @@ func workersSchemaMake() map[string]*schema.Schema { "ram": { Type: schema.TypeInt, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), Required: true, }, diff --git a/internal/service/cloudapi/k8s/resource_k8s.go b/internal/service/cloudapi/k8s/resource_k8s.go index 75ac873..d8f4b2f 100644 --- a/internal/service/cloudapi/k8s/resource_k8s.go +++ b/internal/service/cloudapi/k8s/resource_k8s.go @@ -101,7 +101,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ } createReq.MasterNum = uint(masterNode.Num) createReq.MasterCPU = uint(masterNode.Cpu) - createReq.MasterRAM = uint(masterNode.Ram) + createReq.MasterRAM = uint64(masterNode.Ram) createReq.MasterDisk = uint(masterNode.Disk) createReq.MasterSEPID = uint64(masterNode.SepID) createReq.MasterSEPPool = masterNode.SepPool @@ -115,7 +115,7 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ createReq.WorkerNum = uint(workerNode.Num) createReq.WorkerCPU = uint(workerNode.Cpu) - createReq.WorkerRAM = uint(workerNode.Ram) + createReq.WorkerRAM = uint64(workerNode.Ram) createReq.WorkerDisk = uint(workerNode.Disk) createReq.WorkerSEPID = uint64(workerNode.SepID) createReq.WorkerSEPPool = workerNode.SepPool @@ -183,12 +183,26 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ } if lbSysctlParams, ok := d.GetOk("lb_sysctl_params"); ok { - createReq.LbSysctlParams = lbSysctlParams.(string) + syscrlSliceMaps := lbSysctlParams.([]map[string]string) + res := make([]map[string]interface{}, 0, len(syscrlSliceMaps)) + for _, syscrlMap := range syscrlSliceMaps { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + createReq.LbSysctlParams = res } if oidcCertificate, ok := d.GetOk("oidc_cert"); ok { createReq.OidcCertificate = oidcCertificate.(string) } + /// createReq.ExtNetOnly = d.Get("extnet_only").(bool) @@ -231,7 +245,11 @@ func resourceK8sCreate(ctx context.Context, d *schema.ResourceData, m interface{ return diag.FromErr(fmt.Errorf("cannot create k8s instance: %v", task.Error)) } - d.SetId(strconv.Itoa(int(task.Result))) + id, err := task.Result.ID() + if err != nil { + return diag.FromErr(err) + } + d.SetId(strconv.Itoa(id)) break } @@ -515,6 +533,31 @@ func resourceK8sUpdate(ctx context.Context, d *schema.ResourceData, m interface{ } } + if d.HasChange("lb_sysctl_params") && d.Get("with_lb").(bool) { + lbSysctlParams := d.Get("lb_sysctl_params").([]map[string]string) + res := make([]map[string]interface{}, 0, len(lbSysctlParams)) + for _, syscrlMap := range lbSysctlParams { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + + req := lb.UpdateSysctParamsRequest{ + LBID: cluster.LBID, + SysctlParams: res, + } + _, err := c.CloudAPI().LB().UpdateSysctlParams(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + return resourceK8sRead(ctx, d, m) } @@ -685,15 +728,22 @@ func resourceK8sSchemaMake() map[string]*schema.Schema { Description: "Use Highly Available schema for LB deploy", }, "lb_sysctl_params": { - Type: schema.TypeString, + Type: schema.TypeList, Optional: true, Description: "Custom sysctl values for Load Balancer instance. Applied on boot.", + Elem: &schema.Schema{ + Type: schema.TypeMap, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, }, "oidc_cert": { Type: schema.TypeString, Optional: true, Description: "insert ssl certificate in x509 pem format", }, + "desc": { Type: schema.TypeString, Optional: true, @@ -705,6 +755,7 @@ func resourceK8sSchemaMake() map[string]*schema.Schema { Default: true, Description: "Start k8s cluster", }, + "acl": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudapi/k8s/resource_k8s_cp.go b/internal/service/cloudapi/k8s/resource_k8s_cp.go index 7f1d222..a581ccf 100644 --- a/internal/service/cloudapi/k8s/resource_k8s_cp.go +++ b/internal/service/cloudapi/k8s/resource_k8s_cp.go @@ -109,7 +109,7 @@ func resourceK8sCPCreate(ctx context.Context, d *schema.ResourceData, m interfac } if ram, ok := d.GetOk("ram"); ok { - createReq.MasterRAM = uint(ram.(int)) + createReq.MasterRAM = uint64(ram.(int)) } else { createReq.MasterRAM = 2048 } @@ -168,7 +168,20 @@ func resourceK8sCPCreate(ctx context.Context, d *schema.ResourceData, m interfac } if lbSysctlParams, ok := d.GetOk("lb_sysctl_params"); ok { - createReq.LbSysctlParams = lbSysctlParams.(string) + syscrlSliceMaps := lbSysctlParams.([]map[string]string) + res := make([]map[string]interface{}, 0, len(syscrlSliceMaps)) + for _, syscrlMap := range syscrlSliceMaps { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + createReq.LbSysctlParams = res } if oidcCertificate, ok := d.GetOk("oidc_cert"); ok { @@ -176,6 +189,8 @@ func resourceK8sCPCreate(ctx context.Context, d *schema.ResourceData, m interfac log.Debug(createReq.OidcCertificate) } + /// + createReq.ExtNetOnly = d.Get("extnet_only").(bool) if extNet, ok := d.GetOk("extnet_id"); ok { @@ -217,7 +232,11 @@ func resourceK8sCPCreate(ctx context.Context, d *schema.ResourceData, m interfac return diag.FromErr(fmt.Errorf("cannot create k8s instance: %v", task.Error)) } - d.SetId(strconv.Itoa(int(task.Result))) + id, err := task.Result.ID() + if err != nil { + return diag.FromErr(err) + } + d.SetId(strconv.Itoa(id)) break } @@ -532,6 +551,31 @@ func resourceK8sCPUpdate(ctx context.Context, d *schema.ResourceData, m interfac } } + if d.HasChange("lb_sysctl_params") && d.Get("with_lb").(bool) { + lbSysctlParams := d.Get("lb_sysctl_params").([]map[string]string) + res := make([]map[string]interface{}, 0, len(lbSysctlParams)) + for _, syscrlMap := range lbSysctlParams { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + + req := lb.UpdateSysctParamsRequest{ + LBID: cluster.LBID, + SysctlParams: res, + } + _, err := c.CloudAPI().LB().UpdateSysctlParams(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + return resourceK8sCPRead(ctx, d, m) } @@ -592,8 +636,8 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.IntInSlice([]int{1, 3}), - Description: "Number of VMs to create. Can be either 1 or 3", + ValidateFunc: validation.IntInSlice([]int{1, 3, 5}), + Description: "Number of VMs to create. Can be either 1, 3 or 5", }, "cpu": { Type: schema.TypeInt, @@ -606,8 +650,8 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Optional: true, Computed: true, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), Description: "Node RAM in MB.", }, @@ -680,9 +724,15 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Description: "Use Highly Available schema for LB deploy", }, "lb_sysctl_params": { - Type: schema.TypeString, + Type: schema.TypeList, Optional: true, Description: "Custom sysctl values for Load Balancer instance. Applied on boot.", + Elem: &schema.Schema{ + Type: schema.TypeMap, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, }, "oidc_cert": { Type: schema.TypeString, @@ -724,6 +774,12 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Master group name.", }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Determines if cluster should be destroyed", + }, "acl": { Type: schema.TypeList, Computed: true, @@ -776,12 +832,6 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Computed: true, Description: "IP address of default load balancer.", }, - "permanently": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "Determines if cluster should be destroyed", - }, "rg_name": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/k8s/resource_k8s_wg.go b/internal/service/cloudapi/k8s/resource_k8s_wg.go index f8db4c5..b5213b1 100644 --- a/internal/service/cloudapi/k8s/resource_k8s_wg.go +++ b/internal/service/cloudapi/k8s/resource_k8s_wg.go @@ -267,8 +267,8 @@ func resourceK8sWgSchemaMake() map[string]*schema.Schema { //ForceNew: true, Default: 1024, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), Description: "Worker node RAM in MB.", }, diff --git a/internal/service/cloudapi/k8s/utility_k8ci.go b/internal/service/cloudapi/k8s/utility_k8ci.go index 4fad406..55fda58 100644 --- a/internal/service/cloudapi/k8s/utility_k8ci.go +++ b/internal/service/cloudapi/k8s/utility_k8ci.go @@ -67,6 +67,9 @@ func utilityK8CIListCheckPresence(ctx context.Context, d *schema.ResourceData, m if include_disabled, ok := d.GetOk("include_disabled"); ok { req.IncludeDisabled = include_disabled.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/k8s/utility_k8s.go b/internal/service/cloudapi/k8s/utility_k8s.go index 855c248..239cffb 100644 --- a/internal/service/cloudapi/k8s/utility_k8s.go +++ b/internal/service/cloudapi/k8s/utility_k8s.go @@ -265,6 +265,10 @@ func utilityK8sListCheckPresence(ctx context.Context, d *schema.ResourceData, m req.IncludeDeleted = includedeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } @@ -329,6 +333,10 @@ func utilityK8sListDeletedCheckPresence(ctx context.Context, d *schema.ResourceD req.TechStatus = tech_status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/kvmvm/data_source_compute.go b/internal/service/cloudapi/kvmvm/data_source_compute.go index df680a5..b2b5025 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute.go @@ -360,6 +360,39 @@ func computeListDisksSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, "reality_device_number": { Type: schema.TypeInt, Computed: true, @@ -489,6 +522,10 @@ func computeInterfacesSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, @@ -615,7 +652,11 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, }, }, - "boot_disk_size": { + "bootdisk_size": { + Type: schema.TypeInt, + Computed: true, + }, + "cd_image_id": { Type: schema.TypeInt, Computed: true, }, @@ -634,6 +675,10 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cpu_pin": { + Type: schema.TypeBool, + Computed: true, + }, "cpus": { Type: schema.TypeInt, Computed: true, @@ -685,6 +730,10 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "hp_backed": { + Type: schema.TypeBool, + Computed: true, + }, "image_id": { Type: schema.TypeInt, Computed: true, @@ -720,10 +769,18 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, - "need_reboot" : { + "need_reboot": { Type: schema.TypeBool, Computed: true, }, + "numa_affinity": { + Type: schema.TypeString, + Computed: true, + }, + "numa_node_id": { + Type: schema.TypeInt, + Computed: true, + }, "natable_vins_id": { Type: schema.TypeInt, Computed: true, @@ -771,6 +828,13 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "reserved_node_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "rg_id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_list.go index 55bbeb9..cf4786f 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_list.go @@ -124,7 +124,11 @@ func itemComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, }, }, - "boot_disk_size": { + "bootdisk_size": { + Type: schema.TypeInt, + Computed: true, + }, + "cd_image_id": { Type: schema.TypeInt, Computed: true, }, @@ -143,6 +147,10 @@ func itemComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cpu_pin": { + Type: schema.TypeBool, + Computed: true, + }, "cpus": { Type: schema.TypeInt, Computed: true, @@ -194,6 +202,10 @@ func itemComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "hp_backed": { + Type: schema.TypeBool, + Computed: true, + }, "compute_id": { Type: schema.TypeInt, Computed: true, @@ -237,6 +249,14 @@ func itemComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + "numa_affinity": { + Type: schema.TypeString, + Computed: true, + }, + "numa_node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pinned": { Type: schema.TypeBool, Computed: true, @@ -257,6 +277,13 @@ func itemComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "reserved_node_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "rg_id": { Type: schema.TypeInt, Computed: true, @@ -394,6 +421,11 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Optional: true, }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go b/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go index 5d68d52..009e0e5 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_list_deleted.go @@ -109,6 +109,11 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by Extnet ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go index d0573b8..b95ab76 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_pci_device_list.go @@ -80,6 +80,11 @@ func dataSourceComputePCIDeviceListSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Find by status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -93,8 +98,49 @@ func dataSourceComputePCIDeviceListSchemaMake() map[string]*schema.Schema { "items": { Type: schema.TypeList, Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeInt, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "hwpath": { + Type: schema.TypeString, + Computed: true, + }, + "device_id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "stack_id": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "system_name": { + Type: schema.TypeString, + Computed: true, + }, + }, }, }, "entry_count": { diff --git a/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go b/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go index dc789f6..03651d7 100644 --- a/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go +++ b/internal/service/cloudapi/kvmvm/data_source_compute_vgpu_list.go @@ -80,6 +80,11 @@ func dataSourceComputeVGPUListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Include deleted computes. If using field 'status', then includedeleted will be ignored", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -93,8 +98,81 @@ func dataSourceComputeVGPUListSchemaMake() map[string]*schema.Schema { "items": { Type: schema.TypeList, Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "vgpu_id": { + Type: schema.TypeInt, + Computed: true, + }, + "last_claimed_by": { + Type: schema.TypeInt, + Computed: true, + }, + "last_update_time": { + Type: schema.TypeInt, + Computed: true, + }, + "mode": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "pgpuid": { + Type: schema.TypeInt, + Computed: true, + }, + "profile_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, }, }, "entry_count": { diff --git a/internal/service/cloudapi/kvmvm/flattens.go b/internal/service/cloudapi/kvmvm/flattens.go index 59f59c1..77e46dc 100644 --- a/internal/service/cloudapi/kvmvm/flattens.go +++ b/internal/service/cloudapi/kvmvm/flattens.go @@ -33,7 +33,6 @@ Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/w package kvmvm import ( - "context" "encoding/json" "sort" "strconv" @@ -83,6 +82,7 @@ func flattenInterfaces(interfaces compute.ListInterfaces) []map[string]interface "net_id": interfaceItem.NetID, "netmask": interfaceItem.NetMask, "net_type": interfaceItem.NetType, + "node_id": interfaceItem.NodeID, "pci_slot": interfaceItem.PCISlot, "qos": flattenQOS(interfaceItem.QOS), "target": interfaceItem.Target, @@ -164,10 +164,12 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{} "anti_affinity_rules": flattenListRules(compute.AntiAffinityRules), "arch": compute.Architecture, "boot_order": compute.BootOrder, - "boot_disk_size": compute.BootDiskSize, + "bootdisk_size": compute.BootDiskSize, + "cd_image_id": compute.CdImageId, "clone_reference": compute.CloneReference, "clones": compute.Clones, "computeci_id": compute.ComputeCIID, + "cpu_pin": compute.CPUPin, "cpus": compute.CPU, "created_by": compute.CreatedBy, "created_time": compute.CreatedTime, @@ -180,6 +182,7 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{} "driver": compute.Driver, "gid": compute.GID, "guid": compute.GUID, + "hp_backed": compute.HPBacked, "compute_id": compute.ID, "image_id": compute.ImageID, "interfaces": flattenInterfaces(compute.Interfaces), @@ -190,11 +193,14 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{} "milestones": compute.Milestones, "name": compute.Name, "need_reboot": compute.NeedReboot, + "numa_affinity": compute.NumaAffinity, + "numa_node_id": compute.NumaNodeId, "pinned": compute.Pinned, "ram": compute.RAM, "reference_id": compute.ReferenceID, "registered": compute.Registered, "res_name": compute.ResName, + "reserved_node_cpus": compute.ReservedNodeCpus, "rg_id": compute.RGID, "rg_name": compute.RGName, "snap_sets": flattenSnapSets(compute.SnapSets), @@ -239,17 +245,25 @@ func flattenBootDisk(bootDisk *compute.ItemComputeDisk) []map[string]interface{} return res } -func flattenComputeDisksDemo(ctx context.Context, d *schema.ResourceData, disksList compute.ListComputeDisks, extraDisks []interface{}, bootDiskId uint64) []map[string]interface{} { +func flattenComputeDisksDemo(disksList compute.ListComputeDisks, disksBlocks, extraDisks []interface{}, bootDiskId uint64) []map[string]interface{} { res := make([]map[string]interface{}, 0, len(disksList)) + + if len(disksBlocks) == 0 { + return res + } + + sort.Slice(disksList, func(i, j int) bool { + return disksList[i].ID < disksList[j].ID + }) + + indexDataDisks := 0 + for _, disk := range disksList { if disk.ID == bootDiskId || findInExtraDisks(uint(disk.ID), extraDisks) { //skip main bootdisk and extraDisks continue } - permanently, ok := ctx.Value(DiskKey(strconv.Itoa(int(disk.ID)))).(bool) // get permamently from Create or Update context - if !ok { - permanently = getPermanentlyByDiskID(d, disk.ID) // get permanently from state when Read is not after Create/Update - } + pernamentlyValue := disksBlocks[indexDataDisks].(map[string]interface{})["permanently"].(bool) temp := map[string]interface{}{ "disk_name": disk.Name, @@ -263,32 +277,15 @@ func flattenComputeDisksDemo(ctx context.Context, d *schema.ResourceData, disksL "desc": disk.Description, "image_id": disk.ImageID, "size": disk.SizeMax, - "permanently": permanently, + "permanently": pernamentlyValue, } res = append(res, temp) + indexDataDisks++ } - sort.Slice(res, func(i, j int) bool { - return res[i]["disk_id"].(uint64) < res[j]["disk_id"].(uint64) - }) return res } -// getPermanentlyByDiskID gets permanently value of specific disk (by diskId) from disks current state -func getPermanentlyByDiskID(d *schema.ResourceData, diskId uint64) bool { - disks := d.Get("disks").([]interface{}) - - for _, diskItem := range disks { - disk := diskItem.(map[string]interface{}) - if uint64(disk["disk_id"].(int)) == diskId { - return disk["permanently"].(bool) - } - } - - log.Infof("getPermanentlyByDiskID: disk with id %d not found in state", diskId) - return false -} - func flattenNetwork(interfaces compute.ListInterfaces) []map[string]interface{} { res := make([]map[string]interface{}, 0, len(interfaces)) @@ -310,10 +307,10 @@ func findBootDisk(disks compute.ListComputeDisks) *compute.ItemComputeDisk { return &disk } } - return nil + return &compute.ItemComputeDisk{} } -func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec compute.RecordCompute) error { +func flattenCompute(d *schema.ResourceData, computeRec compute.RecordCompute) error { // This function expects that compFacts string contains response from API compute/get, // i.e. detailed information about compute instance. // @@ -336,6 +333,7 @@ func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec comp d.Set("boot_disk_size", bootDisk.SizeMax) d.Set("boot_disk", flattenBootDisk(bootDisk)) d.Set("boot_disk_id", bootDisk.ID) + d.Set("cd_image_id", computeRec.CdImageId) d.Set("sep_id", bootDisk.SepID) d.Set("pool", bootDisk.Pool) d.Set("clone_reference", computeRec.CloneReference) @@ -348,7 +346,7 @@ func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec comp d.Set("deleted_time", computeRec.DeletedTime) d.Set("description", computeRec.Description) d.Set("devices", string(devices)) - err := d.Set("disks", flattenComputeDisksDemo(ctx, d, computeRec.Disks, d.Get("extra_disks").(*schema.Set).List(), bootDisk.ID)) + err := d.Set("disks", flattenComputeDisksDemo(computeRec.Disks, d.Get("disks").([]interface{}), d.Get("extra_disks").(*schema.Set).List(), bootDisk.ID)) if err != nil { return err } @@ -370,6 +368,7 @@ func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec comp d.Set("milestones", computeRec.Milestones) d.Set("name", computeRec.Name) d.Set("need_reboot", computeRec.NeedReboot) + d.Set("numa_node_id", computeRec.NumaNodeId) d.Set("natable_vins_id", computeRec.NatableVINSID) d.Set("natable_vins_ip", computeRec.NatableVINSIP) d.Set("natable_vins_name", computeRec.NatableVINSName) @@ -383,6 +382,7 @@ func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec comp d.Set("reference_id", computeRec.ReferenceID) d.Set("registered", computeRec.Registered) d.Set("res_name", computeRec.ResName) + d.Set("reserved_node_cpus", computeRec.ReservedNodeCpus) d.Set("rg_id", computeRec.RGID) d.Set("rg_name", computeRec.RGName) d.Set("snap_sets", flattenSnapSets(computeRec.SnapSets)) @@ -513,6 +513,7 @@ func flattenListComputeDisks(disks compute.ListComputeDisks) []map[string]interf "pool": disk.Pool, "present_to": disk.PresentTo, "purge_time": disk.PurgeTime, + "replication": flattenDiskReplication(disk.Replication), "reality_device_number": disk.RealityDeviceNumber, "res_id": disk.ResID, "role": disk.Role, @@ -532,6 +533,20 @@ func flattenListComputeDisks(disks compute.ListComputeDisks) []map[string]interf return res } +func flattenDiskReplication(rep compute.ItemReplication) []map[string]interface{} { + res := []map[string]interface{}{ + { + "disk_id": rep.DiskID, + "pool_id": rep.PoolID, + "role": rep.Role, + "self_volume_id": rep.SelfVolumeID, + "storage_id": rep.StorageID, + "volume_id": rep.VolumeID, + }, + } + return res +} + func flattenCustomFields(customFields map[string]interface{}) string { encoded, _ := json.Marshal(customFields) return string(encoded) @@ -563,10 +578,12 @@ func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute d.Set("anti_affinity_rules", flattenListRules(computeRec.AntiAffinityRules)) d.Set("arch", computeRec.Architecture) d.Set("boot_order", computeRec.BootOrder) - d.Set("boot_disk_size", computeRec.BootDiskSize) + d.Set("bootdisk_size", computeRec.BootDiskSize) + d.Set("cd_image_id", computeRec.CdImageId) d.Set("clone_reference", computeRec.CloneReference) d.Set("clones", computeRec.Clones) d.Set("computeci_id", computeRec.ComputeCIID) + d.Set("cpu_pin", computeRec.CPUPin) d.Set("cpus", computeRec.CPU) d.Set("created_by", computeRec.CreatedBy) d.Set("created_time", computeRec.CreatedTime) @@ -579,6 +596,7 @@ func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute d.Set("driver", computeRec.Driver) d.Set("gid", computeRec.GID) d.Set("guid", computeRec.GUID) + d.Set("hp_backed", computeRec.HPBacked) d.Set("compute_id", computeRec.ID) d.Set("image_id", computeRec.ImageID) d.Set("image_name", computeRec.ImageName) @@ -590,6 +608,8 @@ func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute d.Set("milestones", computeRec.Milestones) d.Set("name", computeRec.Name) d.Set("need_reboot", computeRec.NeedReboot) + d.Set("numa_affinity", computeRec.NumaAffinity) + d.Set("numa_node_id", computeRec.NumaNodeId) d.Set("natable_vins_id", computeRec.NatableVINSID) d.Set("natable_vins_ip", computeRec.NatableVINSIP) d.Set("natable_vins_name", computeRec.NatableVINSName) @@ -601,6 +621,7 @@ func flattenDataCompute(d *schema.ResourceData, computeRec compute.RecordCompute d.Set("reference_id", computeRec.ReferenceID) d.Set("registered", computeRec.Registered) d.Set("res_name", computeRec.ResName) + d.Set("reserved_node_cpus", computeRec.ReservedNodeCpus) d.Set("rg_id", computeRec.RGID) d.Set("rg_name", computeRec.RGName) d.Set("snap_sets", flattenSnapSets(computeRec.SnapSets)) @@ -696,40 +717,50 @@ func flattenSnapshotUsage(computeSnapshotUsages compute.ListUsageSnapshots) []ma // return res // } -func flattenVGPU(m []interface{}) []string { - output := []string{} - for _, item := range m { - switch d := item.(type) { - case string: - output = append(output, d) - case int: - output = append(output, strconv.Itoa(d)) - case int64: - output = append(output, strconv.FormatInt(d, 10)) - case float64: - output = append(output, strconv.FormatInt(int64(d), 10)) - default: - output = append(output, "") +func flattenVGPU(vgpuList []compute.ItemVGPU) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vgpuList)) + for _, dev := range vgpuList { + temp := map[string]interface{}{ + "account_id": dev.AccountID, + "created_time": dev.CreatedTime, + "deleted_time": dev.DeletedTime, + "gid": dev.GID, + "guid": dev.GUID, + "vgpu_id": dev.ID, + "last_claimed_by": dev.LastClaimedBy, + "last_update_time": dev.LastUpdateTime, + "mode": dev.Mode, + "pci_slot": dev.PCISlot, + "pgpuid": dev.PGPUID, + "profile_id": dev.ProfileID, + "ram": dev.RAM, + "reference_id": dev.ReferenceID, + "rg_id": dev.RGID, + "status": dev.Status, + "type": dev.Type, + "vm_id": dev.VMID, } + res = append(res, temp) } - return output + return res } -func flattenPCIDevice(m []interface{}) []string { - output := []string{} - for _, item := range m { - switch d := item.(type) { - case string: - output = append(output, d) - case int: - output = append(output, strconv.Itoa(d)) - case int64: - output = append(output, strconv.FormatInt(d, 10)) - case float64: - output = append(output, strconv.FormatInt(int64(d), 10)) - default: - output = append(output, "") +func flattenPCIDevice(deviceList []compute.ItemPCIDevice) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(deviceList)) + for _, dev := range deviceList { + temp := map[string]interface{}{ + "compute_id": dev.ComputeID, + "description": dev.Description, + "guid": dev.GUID, + "hwpath": dev.HwPath, + "device_id": dev.ID, + "name": dev.Name, + "rg_id": dev.RGID, + "stack_id": dev.StackID, + "status": dev.Status, + "system_name": dev.SystemName, } + res = append(res, temp) } - return output + return res } diff --git a/internal/service/cloudapi/kvmvm/network_subresource.go b/internal/service/cloudapi/kvmvm/network_subresource.go index 6783bc2..e2df7e2 100644 --- a/internal/service/cloudapi/kvmvm/network_subresource.go +++ b/internal/service/cloudapi/kvmvm/network_subresource.go @@ -128,7 +128,7 @@ func networkSubresourceSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Required: true, StateFunc: statefuncs.StateFuncToUpper, - ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS"}, false), // observe case while validating + ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS", "VFNIC"}, false), // observe case while validating Description: "Type of the network for this connection, either EXTNET or VINS.", }, diff --git a/internal/service/cloudapi/kvmvm/old_schemas.go b/internal/service/cloudapi/kvmvm/old_schemas.go index 9f27776..07d0c8a 100644 --- a/internal/service/cloudapi/kvmvm/old_schemas.go +++ b/internal/service/cloudapi/kvmvm/old_schemas.go @@ -33,13 +33,13 @@ func resourceComputeResourceV1() *schema.Resource { "cpu": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntBetween(1, constants.MaxCpusPerCompute), + ValidateFunc: validation.IntBetween(1, constants.MAX_CPUS_PER_COMPUTE), Description: "Number of CPUs to allocate to this compute instance.", }, "ram": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntAtLeast(constants.MinRamPerCompute), + ValidateFunc: validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), Description: "Amount of RAM in MB to allocate to this compute instance.", }, "image_id": { @@ -191,7 +191,7 @@ func resourceComputeResourceV1() *schema.Resource { "extra_disks": { Type: schema.TypeSet, Optional: true, - MaxItems: constants.MaxExtraDisksPerCompute, + MaxItems: constants.MAX_EXTRA_DISKS_PER_COMPUTE, Elem: &schema.Schema{ Type: schema.TypeInt, }, @@ -202,7 +202,7 @@ func resourceComputeResourceV1() *schema.Resource { Type: schema.TypeSet, Optional: true, MinItems: 1, - MaxItems: constants.MaxNetworksPerCompute, + MaxItems: constants.MAX_NETWORKS_PER_COMPUTE, Elem: &schema.Resource{ Schema: networkSubresourceSchemaMake(), }, @@ -575,13 +575,13 @@ func resourceComputeResourceV2() *schema.Resource { "cpu": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntBetween(1, constants.MaxCpusPerCompute), + ValidateFunc: validation.IntBetween(1, constants.MAX_CPUS_PER_COMPUTE), Description: "Number of CPUs to allocate to this compute instance.", }, "ram": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntAtLeast(constants.MinRamPerCompute), + ValidateFunc: validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), Description: "Amount of RAM in MB to allocate to this compute instance.", }, "image_id": { @@ -853,7 +853,7 @@ func resourceComputeResourceV2() *schema.Resource { Type: schema.TypeSet, Optional: true, Computed: true, - MaxItems: constants.MaxExtraDisksPerCompute, + MaxItems: constants.MAX_EXTRA_DISKS_PER_COMPUTE, Elem: &schema.Schema{ Type: schema.TypeInt, }, @@ -864,7 +864,7 @@ func resourceComputeResourceV2() *schema.Resource { Type: schema.TypeSet, Optional: true, MinItems: 1, - MaxItems: constants.MaxNetworksPerCompute, + MaxItems: constants.MAX_NETWORKS_PER_COMPUTE, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "net_type": { diff --git a/internal/service/cloudapi/kvmvm/resource_check_input_values.go b/internal/service/cloudapi/kvmvm/resource_check_input_values.go index 04bac5d..c5ab3ad 100644 --- a/internal/service/cloudapi/kvmvm/resource_check_input_values.go +++ b/internal/service/cloudapi/kvmvm/resource_check_input_values.go @@ -41,6 +41,7 @@ import ( "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/extnet" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vfpool" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" ) @@ -128,3 +129,36 @@ func existExtNetId(ctx context.Context, m interface{}, id int) (int, bool) { return 0, true } + +func existVFPoolId(ctx context.Context, m interface{}, id int) (int, bool) { + c := m.(*controller.ControllerCfg) + req := vfpool.ListRequest{ByID: uint64(id)} + + vfpoolList, err := c.CloudAPI().VFPool().List(ctx, req) + if err != nil { + log.Debugf("Unable to retrieve vfpool list, %s", err) + return id, false + } + + if len(vfpoolList.Data) == 1 { + return 0, true + } + + return id, false +} + +func isMoreThanOneDisksTypeB(ctx context.Context, disks interface{}) bool { + count := 0 + + for _, elem := range disks.([]interface{}) { + diskVal := elem.(map[string]interface{}) + if diskVal["disk_type"].(string) == "B" { + count++ + } + if count > 1 { + return true + } + } + + return false +} diff --git a/internal/service/cloudapi/kvmvm/resource_compute.go b/internal/service/cloudapi/kvmvm/resource_compute.go index 00d509f..87ffe72 100644 --- a/internal/service/cloudapi/kvmvm/resource_compute.go +++ b/internal/service/cloudapi/kvmvm/resource_compute.go @@ -55,9 +55,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) -// DiskKey is custom string type to set up context Key for Disk ID -type DiskKey string - func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceComputeCreate: called for Compute name %q, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) c := m.(*controller.ControllerCfg) @@ -82,6 +79,12 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf return diag.Errorf("resourceComputeCreate: can't create Compute because imageID %d is not allowed or does not exist", d.Get("image_id").(int)) } + if disks, ok := d.GetOk("disks"); ok { + if isMoreThanOneDisksTypeB(ctx, disks) { + return diag.Errorf("resourceComputeCreate: can't create Compute because block disks have more 1 disk type 'B'") + } + } + if network, ok := d.GetOk("network"); ok { networkList := network.(*schema.Set).List() for _, elem := range networkList { @@ -96,7 +99,13 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf if extNetId, ok := existExtNetId(ctx, m, networkData["net_id"].(int)); !ok { return diag.Errorf("resourceComputeCreate: can't create compute because extnet ID %d is not allowed or does not exist", extNetId) } - + case "VFNIC": + if d.Get("driver").(string) == "KVM_PPC" { + return diag.Errorf("resourceComputeCreate: can't create compute because 'VFNIC' net_type is not allowed for driver 'KVM_PPC'") + } + if vfpoolId, ok := existVFPoolId(ctx, m, networkData["net_id"].(int)); !ok { + return diag.Errorf("resourceComputeCreate: can't create compute because vfpool ID %d is not allowed or does not exist", vfpoolId) + } default: continue } @@ -186,6 +195,57 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } + if disks, ok := d.GetOk("disks"); ok { + disksX86 := make([]kvmx86.DataDisk, 0) + disksPPC := make([]kvmppc.DataDisk, 0) + + for _, elem := range disks.([]interface{}) { + diskVal := elem.(map[string]interface{}) + reqDataDisk := kvmx86.DataDisk{ + DiskName: diskVal["disk_name"].(string), + Size: uint64(diskVal["size"].(int)), + } + if sepId, ok := diskVal["sep_id"]; ok { + reqDataDisk.SepID = uint64(sepId.(int)) + } + if pool, ok := diskVal["pool"]; ok { + reqDataDisk.Pool = pool.(string) + } + if desc, ok := diskVal["desc"]; ok { + reqDataDisk.Description = desc.(string) + } + if imageID, ok := diskVal["image_id"]; ok { + reqDataDisk.ImageID = uint64(imageID.(int)) + } + disksX86 = append(disksX86, reqDataDisk) + } + + createReqX86.DataDisks = disksX86 + + for _, elem := range disks.([]interface{}) { + diskVal := elem.(map[string]interface{}) + reqDataDisk := kvmppc.DataDisk{ + DiskName: diskVal["disk_name"].(string), + Size: uint64(diskVal["size"].(int)), + } + if sepId, ok := diskVal["sep_id"]; ok { + reqDataDisk.SepID = uint64(sepId.(int)) + } + if pool, ok := diskVal["pool"]; ok { + reqDataDisk.Pool = pool.(string) + } + if desc, ok := diskVal["desc"]; ok { + reqDataDisk.Description = desc.(string) + } + if imageID, ok := diskVal["image_id"]; ok { + reqDataDisk.ImageID = uint64(imageID.(int)) + } + disksPPC = append(disksPPC, reqDataDisk) + } + + createReqPPC.DataDisks = disksPPC + } + argVal, ok = d.GetOk("cloud_init") if ok { userdata := argVal.(string) @@ -217,10 +277,16 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf createReqX86.Name = d.Get("name").(string) createReqX86.CPU = uint64(d.Get("cpu").(int)) createReqX86.RAM = uint64(d.Get("ram").(int)) - createReqX86.ImageID = uint64(d.Get("image_id").(int)) createReqX86.Driver = driver + if image, ok := d.GetOk("image_id"); ok { + createReqX86.ImageID = uint64(image.(int)) + } + if withoutBootDisk, ok := d.GetOk("without_boot_disk"); ok { + createReqX86.WithoutBootDisk = withoutBootDisk.(bool) + } + if custom_fields, ok := d.GetOk("custom_fields"); ok { val := custom_fields.(string) val = strings.ReplaceAll(val, "\\", "") @@ -231,6 +297,12 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf createReqX86.CustomFields = val } + if numaAffinity, ok := d.GetOk("numa_affinity"); ok { + createReqX86.NumaAffinity = numaAffinity.(string) + } + createReqX86.CPUPin = d.Get("cpu_pin").(bool) + createReqX86.HPBacked = d.Get("hp_backed").(bool) + log.Debugf("resourceComputeCreate: creating Compute of type KVM VM x86") apiResp, err := c.CloudAPI().KVMX86().Create(ctx, createReqX86) if err != nil { @@ -273,46 +345,8 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } - if disks, ok := d.GetOk("disks"); ok { - log.Debugf("resourceComputeCreate: Create disks on ComputeID: %d", computeId) - addedDisks := disks.([]interface{}) - if len(addedDisks) > 0 { - for _, disk := range addedDisks { - diskConv := disk.(map[string]interface{}) - req := compute.DiskAddRequest{ - ComputeID: computeId, - DiskName: diskConv["disk_name"].(string), - Size: uint64(diskConv["size"].(int)), - } - - if diskConv["sep_id"].(int) != 0 { - req.SepID = uint64(diskConv["sep_id"].(int)) - } - if diskConv["disk_type"].(string) != "" { - req.DiskType = diskConv["disk_type"].(string) - } - if diskConv["pool"].(string) != "" { - req.Pool = diskConv["pool"].(string) - } - if diskConv["desc"].(string) != "" { - req.Description = diskConv["desc"].(string) - } - if diskConv["image_id"].(int) != 0 { - req.ImageID = uint64(diskConv["image_id"].(int)) - } - - diskId, err := c.CloudAPI().Compute().DiskAdd(ctx, req) - if err != nil { - cleanup = true - return diag.FromErr(err) - } - - ctx = context.WithValue(ctx, DiskKey(strconv.Itoa(int(diskId))), diskConv["permanently"].(bool)) - } - } - } - if !cleanup { + if enabled, ok := d.GetOk("enabled"); ok { if enabled.(bool) { req := compute.EnableRequest{ComputeID: computeId} @@ -435,9 +469,12 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf req := compute.PFWAddRequest{ ComputeID: computeId, PublicPortStart: uint64(pfwItem["public_port_start"].(int)), - LocalBasePort: uint64(pfwItem["local_port"].(int)), Proto: pfwItem["proto"].(string), } + + if pfwItem["local_port"].(int) != 0 { + req.LocalBasePort = uint64(pfwItem["local_port"].(int)) + } if pfwItem["public_port_end"].(int) != 0 { req.PublicPortEnd = int64(pfwItem["public_port_end"].(int)) } @@ -587,7 +624,7 @@ func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interfac } } - if err = flattenCompute(ctx, d, computeRec); err != nil { + if err = flattenCompute(d, computeRec); err != nil { return diag.FromErr(err) } @@ -621,6 +658,12 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf 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 { + if isMoreThanOneDisksTypeB(ctx, disks) { + return diag.Errorf("resourceComputeUpdate: can't update Compute because block disks have more 1 disk type 'B'") + } + } + if network, ok := d.GetOk("network"); ok { networkList := network.(*schema.Set).List() for _, elem := range networkList { @@ -629,13 +672,19 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf switch networkData["net_type"].(string) { case "VINS": if vinsId, ok := existVinsId(ctx, m, networkData["net_id"].(int)); !ok { - return diag.Errorf("resourceComputeCreate: can't update compute because vins ID %d is not allowed or does not exist", vinsId) + return diag.Errorf("resourceComputeUpdate: can't update compute because vins ID %d is not allowed or does not exist", vinsId) } case "EXTNET": if extNetId, ok := existExtNetId(ctx, m, networkData["net_id"].(int)); !ok { - return diag.Errorf("resourceComputeCreate: can't update compute because extnet ID %d is not allowed or does not exist", extNetId) + return diag.Errorf("resourceComputeUpdate: can't update compute because extnet ID %d is not allowed or does not exist", extNetId) + } + case "VFNIC": + if d.Get("driver").(string) == "KVM_PPC" { + return diag.Errorf("resourceComputeUpdate: can't create compute because 'VFNIC' net_type is not allowed for driver 'KVM_PPC'") + } + if vfpoolId, ok := existVFPoolId(ctx, m, networkData["net_id"].(int)); !ok { + return diag.Errorf("resourceComputeUpdate: can't create compute because vfpool ID %d is not allowed or does not exist", vfpoolId) } - default: continue } @@ -839,7 +888,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf } } - if d.HasChanges("description", "name") { + if d.HasChanges("description", "name", "numa_affinity", "cpu_pin", "hp_backed") { req := compute.UpdateRequest{ ComputeID: computeRec.ID, } @@ -850,10 +899,39 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf if d.HasChange("description") { req.Description = d.Get("description").(string) } + 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) + } + + // 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") && 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 d.HasChange("disks") { @@ -862,14 +940,6 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf resizedDisks := make([]interface{}, 0) renamedDisks := make([]interface{}, 0) - // save permanently in disks based on disk_id to context - for _, diskItemInterface := range d.Get("disks").([]interface{}) { - diskItem := diskItemInterface.(map[string]interface{}) - diskId := diskItem["disk_id"].(int) - permanently := diskItem["permanently"].(bool) - ctx = context.WithValue(ctx, DiskKey(strconv.Itoa(diskId)), permanently) - } - oldDisks, newDisks := d.GetChange("disks") oldConv := oldDisks.([]interface{}) newConv := newDisks.([]interface{}) @@ -975,12 +1045,10 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf if diskConv["image_id"].(int) != 0 { req.ImageID = uint64(diskConv["image_id"].(int)) } - diskId, err := c.CloudAPI().Compute().DiskAdd(ctx, req) + _, err := c.CloudAPI().Compute().DiskAdd(ctx, req) if err != nil { return diag.FromErr(err) } - - ctx = context.WithValue(ctx, DiskKey(strconv.Itoa(int(diskId))), diskConv["permanently"].(bool)) } } @@ -1244,10 +1312,11 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf req := compute.PFWDelRequest{ ComputeID: computeRec.ID, PublicPortStart: uint64(pfwItem["public_port_start"].(int)), - LocalBasePort: uint64(pfwItem["local_port"].(int)), Proto: pfwItem["proto"].(string), } - + if pfwItem["local_port"].(int) != 0 { + req.LocalBasePort = uint64(pfwItem["local_port"].(int)) + } if pfwItem["public_port_end"].(int) == -1 { req.PublicPortEnd = req.PublicPortStart } else { @@ -1269,10 +1338,11 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf ComputeID: computeRec.ID, PublicPortStart: uint64(pfwItem["public_port_start"].(int)), PublicPortEnd: int64(pfwItem["public_port_end"].(int)), - LocalBasePort: uint64(pfwItem["local_port"].(int)), Proto: pfwItem["proto"].(string), } - + if pfwItem["local_port"].(int) != 0 { + req.LocalBasePort = uint64(pfwItem["local_port"].(int)) + } _, err := c.CloudAPI().Compute().PFWAdd(ctx, req) if err != nil { return diag.FromErr(err) @@ -1711,7 +1781,7 @@ func portForwardingSubresourceSchemaMake() map[string]*schema.Schema { }, "local_port": { Type: schema.TypeInt, - Required: true, + Optional: true, }, "proto": { Type: schema.TypeString, @@ -1786,24 +1856,30 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { "cpu": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntBetween(1, constants.MaxCpusPerCompute), + ValidateFunc: validation.IntBetween(1, constants.MAX_CPUS_PER_COMPUTE), Description: "Number of CPUs to allocate to this compute instance.", }, "ram": { Type: schema.TypeInt, Required: true, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), Description: "Amount of RAM in MB to allocate to this compute instance.", }, "image_id": { Type: schema.TypeInt, - Required: true, + Optional: true, //ForceNew: true, //REDEPLOY Description: "ID of the OS image to base this compute instance on.", }, + "without_boot_disk": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "If True, the imageId, bootDisk, sepId, pool parameters are ignored and the compute is created without a boot disk in the stopped state.", + }, "boot_disk_size": { Type: schema.TypeInt, Optional: true, @@ -1926,29 +2002,26 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { // ForceNew: true, Description: "Pool to use if sepId is set, can be also empty if needed to be chosen by system.", }, - "extra_disks": { Type: schema.TypeSet, Optional: true, Computed: true, - MaxItems: constants.MaxExtraDisksPerCompute, + MaxItems: constants.MAX_EXTRA_DISKS_PER_COMPUTE, Elem: &schema.Schema{ Type: schema.TypeInt, }, Description: "Optional list of IDs of extra disks to attach to this compute. You may specify several extra disks.", }, - "network": { Type: schema.TypeSet, Optional: true, MinItems: 1, - MaxItems: constants.MaxNetworksPerCompute, + MaxItems: constants.MAX_NETWORKS_PER_COMPUTE, Elem: &schema.Resource{ Schema: networkSubresourceSchemaMake(), }, Description: "Optional network connection(s) for this compute. You may specify several network blocks, one for each connection.", }, - "tags": { Type: schema.TypeSet, Optional: true, @@ -1956,7 +2029,6 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Schema: tagsSubresourceSchemaMake(), }, }, - "port_forwarding": { Type: schema.TypeSet, Optional: true, @@ -1964,7 +2036,6 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Schema: portForwardingSubresourceSchemaMake(), }, }, - "user_access": { Type: schema.TypeSet, Optional: true, @@ -1972,7 +2043,6 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Schema: userAccessSubresourceSchemaMake(), }, }, - "snapshot": { Type: schema.TypeSet, Optional: true, @@ -1980,7 +2050,6 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Schema: snapshotSubresourceSchemaMake(), }, }, - "rollback": { Type: schema.TypeSet, MaxItems: 1, @@ -1989,7 +2058,6 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Schema: snapshotRollbackSubresourceSchemaMake(), }, }, - "cd": { Type: schema.TypeSet, Optional: true, @@ -1998,50 +2066,42 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Schema: cdSubresourceSchemaMake(), }, }, - "pin_to_stack": { Type: schema.TypeBool, Optional: true, Default: false, }, - "description": { Type: schema.TypeString, Optional: true, Description: "Optional text description of this compute instance.", }, - "cloud_init": { Type: schema.TypeString, Optional: true, Description: "Optional cloud_init parameters. Applied when creating new compute instance only, ignored in all other cases.", }, - "enabled": { Type: schema.TypeBool, Optional: true, Computed: true, Description: "If true - enable compute, else - disable", }, - "pause": { Type: schema.TypeBool, Optional: true, Default: false, }, - "reset": { Type: schema.TypeBool, Optional: true, Default: false, }, - "restore": { Type: schema.TypeBool, Optional: true, Default: false, }, - "auto_start": { Type: schema.TypeBool, Optional: true, @@ -2093,6 +2153,26 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Optional: true, Description: "compute purpose", }, + "numa_affinity": { + Type: schema.TypeString, + Optional: true, + Default: "none", + ValidateFunc: validation.StringInSlice([]string{"none", "strict", "loose"}, false), // observe case while validating + Description: "Rule for VM placement with NUMA affinity.", + }, + "cpu_pin": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Run VM on dedicated CPUs. To use this feature, the system must be pre-configured by allocating CPUs on the physical node.", + }, + "hp_backed": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Use Huge Pages to allocate RAM of the virtual machine. The system must be pre-configured by allocating Huge Pages on the physical node.", + }, + // The rest are Compute properties, which are "computed" once it is created "account_id": { Type: schema.TypeInt, @@ -2124,6 +2204,10 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Computed: true, Description: "This compute instance boot disk ID.", }, + "cd_image_id": { + Type: schema.TypeInt, + Computed: true, + }, "clone_reference": { Type: schema.TypeInt, Computed: true, @@ -2202,6 +2286,10 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + "numa_node_id": { + Type: schema.TypeInt, + Computed: true, + }, "natable_vins_id": { Type: schema.TypeInt, Computed: true, @@ -2246,6 +2334,13 @@ func ResourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "reserved_node_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "rg_name": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/kvmvm/utility_compute_list.go b/internal/service/cloudapi/kvmvm/utility_compute_list.go index 652a5ac..4bc4d59 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute_list.go +++ b/internal/service/cloudapi/kvmvm/utility_compute_list.go @@ -77,6 +77,9 @@ func utilityDataComputeListCheckPresence(ctx context.Context, d *schema.Resource if includeDeleted, ok := d.GetOk("includedeleted"); ok { req.IncludeDeleted = includeDeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/kvmvm/utility_compute_list_deleted.go b/internal/service/cloudapi/kvmvm/utility_compute_list_deleted.go index 0182eb6..08f5609 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute_list_deleted.go +++ b/internal/service/cloudapi/kvmvm/utility_compute_list_deleted.go @@ -71,6 +71,9 @@ func utilityDataComputeListDeletedCheckPresence(ctx context.Context, d *schema.R if extnetId, ok := d.GetOk("extnet_id"); ok { req.ExtNetID = uint64(extnetId.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/kvmvm/utility_compute_pci_device_list.go b/internal/service/cloudapi/kvmvm/utility_compute_pci_device_list.go index c8ee027..0ca7b5e 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute_pci_device_list.go +++ b/internal/service/cloudapi/kvmvm/utility_compute_pci_device_list.go @@ -57,6 +57,9 @@ func utilityComputePCIDeviceListCheckPresence(ctx context.Context, d *schema.Res if status, ok := d.GetOk("status"); ok { req.Status = status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/kvmvm/utility_compute_vgpu_list.go b/internal/service/cloudapi/kvmvm/utility_compute_vgpu_list.go index 7bce5f5..d1c4817 100644 --- a/internal/service/cloudapi/kvmvm/utility_compute_vgpu_list.go +++ b/internal/service/cloudapi/kvmvm/utility_compute_vgpu_list.go @@ -57,6 +57,9 @@ func utilityComputeVGPUListCheckPresence(ctx context.Context, d *schema.Resource if includeDeleted, ok := d.GetOk("includedeleted"); ok { req.IncludeDeleted = includeDeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/lb/data_source_lb.go b/internal/service/cloudapi/lb/data_source_lb.go index cb147fc..6d1a207 100644 --- a/internal/service/cloudapi/lb/data_source_lb.go +++ b/internal/service/cloudapi/lb/data_source_lb.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "strconv" - - "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 dataSourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - lb, err := utilityLBCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(lb.ID, 10)) - - flattenLB(d, lb) - - return nil -} - -func DataSourceLB() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLBRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dsLBSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "strconv" + + "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 dataSourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + lb, err := utilityLBCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(lb.ID, 10)) + + flattenLB(d, lb) + + return nil +} + +func DataSourceLB() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLBRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dsLBSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/data_source_lb_list.go b/internal/service/cloudapi/lb/data_source_lb_list.go index f997aa0..00aa6fd 100644 --- a/internal/service/cloudapi/lb/data_source_lb_list.go +++ b/internal/service/cloudapi/lb/data_source_lb_list.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -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 dataSourceLBListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - lbList, err := utilityLBListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenLBList(lbList)) - d.Set("entry_count", lbList.EntryCount) - - return nil -} - -func DataSourceLBList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLBListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dsLBListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +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 dataSourceLBListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + lbList, err := utilityLBListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenLBList(lbList)) + d.Set("entry_count", lbList.EntryCount) + + return nil +} + +func DataSourceLBList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLBListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dsLBListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/data_source_lb_list_deleted.go b/internal/service/cloudapi/lb/data_source_lb_list_deleted.go index 327af75..3965590 100644 --- a/internal/service/cloudapi/lb/data_source_lb_list_deleted.go +++ b/internal/service/cloudapi/lb/data_source_lb_list_deleted.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -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 dataSourceLBListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - lbList, err := utilityLBListDeletedCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenLBList(lbList)) - d.Set("entry_count", lbList.EntryCount) - - return nil -} - -func DataSourceLBListDeleted() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLBListDeletedRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dsLBListDeletedSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +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 dataSourceLBListDeletedRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + lbList, err := utilityLBListDeletedCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenLBList(lbList)) + d.Set("entry_count", lbList.EntryCount) + + return nil +} + +func DataSourceLBListDeleted() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLBListDeletedRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dsLBListDeletedSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/flattens.go b/internal/service/cloudapi/lb/flattens.go index 9ce3cb9..f1c813a 100644 --- a/internal/service/cloudapi/lb/flattens.go +++ b/internal/service/cloudapi/lb/flattens.go @@ -104,6 +104,8 @@ func flattenResourceLB(d *schema.ResourceData, lb *lb.RecordLB) { d.Set("frontends", flattenFrontends(lb.Frontends)) d.Set("gid", lb.GID) d.Set("guid", lb.GUID) + d.Set("manager_id", lb.ManagerId) + d.Set("manager_type", lb.ManagerType) d.Set("lb_id", lb.ID) d.Set("image_id", lb.ImageID) d.Set("milestones", lb.Milestones) @@ -117,6 +119,7 @@ func flattenResourceLB(d *schema.ResourceData, lb *lb.RecordLB) { d.Set("tech_status", lb.TechStatus) d.Set("updated_by", lb.UpdatedBy) d.Set("updated_time", lb.UpdatedTime) + d.Set("user_managed", lb.UserManaged) d.Set("vins_id", lb.VINSID) } @@ -136,6 +139,8 @@ func flattenLB(d *schema.ResourceData, lb *lb.RecordLB) { d.Set("frontends", flattenFrontends(lb.Frontends)) d.Set("gid", lb.GID) d.Set("guid", lb.GUID) + d.Set("manager_id", lb.ManagerId) + d.Set("manager_type", lb.ManagerType) d.Set("image_id", lb.ImageID) d.Set("milestones", lb.Milestones) d.Set("name", lb.Name) @@ -148,6 +153,7 @@ func flattenLB(d *schema.ResourceData, lb *lb.RecordLB) { d.Set("tech_status", lb.TechStatus) d.Set("updated_by", lb.UpdatedBy) d.Set("updated_time", lb.UpdatedTime) + d.Set("user_managed", lb.UserManaged) d.Set("vins_id", lb.VINSID) } @@ -266,9 +272,12 @@ func flattenLBList(lbl *lb.ListLB) []map[string]interface{} { "frontends": flattenFrontends(lb.Frontends), "gid": lb.GID, "guid": lb.GUID, + "manager_id": lb.ManagerId, + "manager_type": lb.ManagerType, "image_id": lb.ImageID, "milestones": lb.Milestones, "name": lb.Name, + "part_k8s": lb.PartK8s, "primary_node": flattenNode(lb.PrimaryNode), "rg_id": lb.RGID, "rg_name": lb.RGName, @@ -277,6 +286,7 @@ func flattenLBList(lbl *lb.ListLB) []map[string]interface{} { "tech_status": lb.TechStatus, "updated_by": lb.UpdatedBy, "updated_time": lb.UpdatedTime, + "user_managed": lb.UserManaged, "vins_id": lb.VINSID, "lb_id": lb.ID, } diff --git a/internal/service/cloudapi/lb/lb_data_subresource.go b/internal/service/cloudapi/lb/lb_data_subresource.go index 1e7b667..b4a4e9f 100644 --- a/internal/service/cloudapi/lb/lb_data_subresource.go +++ b/internal/service/cloudapi/lb/lb_data_subresource.go @@ -1,186 +1,195 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - -func dsLBSchemaMake() map[string]*schema.Schema { - sch := createLBSchema() - sch["lb_id"] = &schema.Schema{ - Type: schema.TypeInt, - Required: true, - } - return sch -} - -func dsLBListDeletedSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by Account ID", - }, - "rg_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by RG ID", - }, - "tech_status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by TechStatus", - }, - "front_ip": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by FrontIP", - }, - "back_ip": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by BackIP", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: dsLBItemSchemaMake(), - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } -} - -func dsLBListSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by Account ID", - }, - "rg_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by RG ID", - }, - "tech_status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by TechStatus", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by Status", - }, - "front_ip": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by FrontIP", - }, - "back_ip": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by BackIP", - }, - "includedeleted": { - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Default: 0, - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: dsLBItemSchemaMake(), - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } -} - -func dsLBItemSchemaMake() map[string]*schema.Schema { - sch := createLBSchema() - sch["dp_api_password"] = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - } - delete(sch, "part_k8s") - return sch -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dsLBSchemaMake() map[string]*schema.Schema { + sch := createLBSchema() + sch["lb_id"] = &schema.Schema{ + Type: schema.TypeInt, + Required: true, + } + return sch +} + +func dsLBListDeletedSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by Account ID", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by RG ID", + }, + "tech_status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by TechStatus", + }, + "front_ip": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by FrontIP", + }, + "back_ip": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by BackIP", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dsLBItemSchemaMake(), + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } +} + +func dsLBListSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by Account ID", + }, + "rg_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by RG ID", + }, + "tech_status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by TechStatus", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by Status", + }, + "front_ip": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by FrontIP", + }, + "back_ip": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by BackIP", + }, + "includedeleted": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Default: 0, + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dsLBItemSchemaMake(), + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } +} + +func dsLBItemSchemaMake() map[string]*schema.Schema { + sch := createLBSchema() + sch["dp_api_password"] = &schema.Schema{ + Type: schema.TypeString, + Computed: true, + } + return sch +} diff --git a/internal/service/cloudapi/lb/lb_resource_subresource.go b/internal/service/cloudapi/lb/lb_resource_subresource.go index 470d5eb..16753aa 100644 --- a/internal/service/cloudapi/lb/lb_resource_subresource.go +++ b/internal/service/cloudapi/lb/lb_resource_subresource.go @@ -94,9 +94,15 @@ func lbResourceSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Optional: true, } - sch["lb_sysctl_params"] = &schema.Schema{ - Type: schema.TypeString, + sch["sysctl_params"] = &schema.Schema{ + Type: schema.TypeList, Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeMap, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, } /// diff --git a/internal/service/cloudapi/lb/lb_schema.go b/internal/service/cloudapi/lb/lb_schema.go index 0d91c25..c725bb8 100644 --- a/internal/service/cloudapi/lb/lb_schema.go +++ b/internal/service/cloudapi/lb/lb_schema.go @@ -42,7 +42,7 @@ func createLBSchema() map[string]*schema.Schema { }, "backend_haip": { Type: schema.TypeString, - Computed: true, + Computed: true, }, "backends": { Type: schema.TypeList, @@ -210,7 +210,7 @@ func createLBSchema() map[string]*schema.Schema { }, "frontend_haip": { Type: schema.TypeString, - Computed: true, + Computed: true, }, "frontends": { Type: schema.TypeList, @@ -268,6 +268,14 @@ func createLBSchema() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "manager_id": { + Type: schema.TypeInt, + Computed: true, + }, + "manager_type": { + Type: schema.TypeString, + Computed: true, + }, "image_id": { Type: schema.TypeInt, Computed: true, @@ -372,6 +380,10 @@ func createLBSchema() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, "vins_id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/lb/resource_lb.go b/internal/service/cloudapi/lb/resource_lb.go index 07778b2..28c34bf 100644 --- a/internal/service/cloudapi/lb/resource_lb.go +++ b/internal/service/cloudapi/lb/resource_lb.go @@ -1,470 +1,510 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - "strconv" - - "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/cloudapi/lb" - "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" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" -) - -func resourceLBCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBCreate") - - haveRGID, err := existRGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveRGID { - return diag.Errorf("resourceLBCreate: can't create LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) - } - - haveExtNetID, err := existExtNetID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveExtNetID { - return diag.Errorf("resourceLBCreate: can't create LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) - } - - haveVins, err := existViNSID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveVins { - return diag.Errorf("resourceLBCreate: can't create LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) - } - - c := m.(*controller.ControllerCfg) - req := lb.CreateRequest{ - Name: d.Get("name").(string), - RGID: uint64(d.Get("rg_id").(int)), - ExtNetID: uint64(d.Get("extnet_id").(int)), - VINSID: uint64(d.Get("vins_id").(int)), - Start: d.Get("start").(bool), - } - - if desc, ok := d.GetOk("desc"); ok { - req.Description = desc.(string) - } - - if haMode, ok := d.GetOk("ha_mode"); ok { - req.HighlyAvailable = haMode.(bool) - } - - lbId, err := c.CloudAPI().LB().Create(ctx, req) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(lbId, 10)) - d.Set("lb_id", lbId) - - w := dc.Warnings{} - - if enable, ok := d.GetOk("enable"); ok { - req := lb.DisableEnableRequest{ - LBID: lbId, - } - - if enable.(bool) { - _, err := c.CloudAPI().LB().Enable(ctx, req) - if err != nil { - w.Add(err) - } - } else { - _, err := c.CloudAPI().LB().Disable(ctx, req) - if err != nil { - w.Add(err) - } - } - - if start, ok := d.GetOk("start"); ok && enable.(bool) { - if start.(bool) { - req := lb.StartRequest{LBID: lbId} - _, err := c.CloudAPI().LB().Start(ctx, req) - if err != nil { - w.Add(err) - } - } else { - req := lb.StopRequest{LBID: lbId} - _, err := c.CloudAPI().LB().Stop(ctx, req) - if err != nil { - w.Add(err) - } - } - } - } - - return append(w.Get(), resourceLBRead(ctx, d, m)...) -} - -func resourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBRead") - - // c := m.(*controller.ControllerCfg) - - lbRec, err := utilityLBCheckPresence(ctx, d, m) - if lbRec == nil { - d.SetId("") - return diag.FromErr(err) - } - - hasChanged := false - - switch lbRec.Status { - case status.Modeled: - return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) - case status.Creating: - case status.Created: - case status.Deleting: - case status.Deleted: - // lbId, _ := strconv.ParseUint(d.Id(), 10, 64) - // restoreReq := lb.RestoreRequest{LBID: lbId} - // enableReq := lb.DisableEnableRequest{LBID: lbId} - - // _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) - // if err != nil { - // return diag.FromErr(err) - // } - // _, err = c.CloudAPI().LB().Enable(ctx, enableReq) - // if err != nil { - // return diag.FromErr(err) - // } - - // hasChanged = true - case status.Destroying: - return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceLBCreate(ctx, d, m) - case status.Enabled: - case status.Enabling: - case status.Disabling: - case status.Disabled: - log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) - case status.Restoring: - } - - if hasChanged { - lbRec, err = utilityLBCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - flattenResourceLB(d, lbRec) - - return nil -} - -func resourceLBDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBDelete") - - c := m.(*controller.ControllerCfg) - lbId, _ := strconv.ParseUint(d.Id(), 10, 64) - req := lb.DeleteRequest{ - LBID: lbId, - } - - if permanently, ok := d.GetOk("permanently"); ok { - req.Permanently = permanently.(bool) - } - - _, err := c.CloudAPI().LB().Delete(ctx, req) - if err != nil { - return diag.FromErr(err) - } - - d.SetId("") - - return nil -} - -func resourceLBUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - log.Debugf("resourceLBUpdate") - c := m.(*controller.ControllerCfg) - - haveRGID, err := existRGID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveRGID { - return diag.Errorf("resourceLBUpdate: can't update LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) - } - - haveExtNetID, err := existExtNetID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveExtNetID { - return diag.Errorf("resourceLBUpdate: can't update LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) - } - - haveVins, err := existViNSID(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - - if !haveVins { - return diag.Errorf("resourceLBUpdate: can't update LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) - } - - lbRec, err := utilityLBCheckPresence(ctx, d, m) - if lbRec == nil { - d.SetId("") - return diag.FromErr(err) - } - - hasChanged := false - - switch lbRec.Status { - case status.Modeled: - return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) - case status.Creating: - case status.Created: - case status.Deleting: - case status.Deleted: - if restore, ok := d.GetOk("restore"); ok && restore.(bool) { - restoreReq := lb.RestoreRequest{LBID: lbRec.ID} - - _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) - if err != nil { - return diag.FromErr(err) - } - } - if enable, ok := d.GetOk("enable"); ok { - req := lb.DisableEnableRequest{ - LBID: lbRec.ID, - } - - if enable.(bool) { - _, err := c.CloudAPI().LB().Enable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else { - _, err := c.CloudAPI().LB().Disable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - - if start, ok := d.GetOk("start"); ok && enable.(bool) { - if start.(bool) { - req := lb.StartRequest{LBID: lbRec.ID} - _, err := c.CloudAPI().LB().Start(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else { - req := lb.StopRequest{LBID: lbRec.ID} - _, err := c.CloudAPI().LB().Stop(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - } - hasChanged = true - case status.Destroying: - return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) - case status.Destroyed: - d.SetId("") - return diag.Errorf("The resource cannot be updated because it has been destroyed") - // return resourceLBCreate(ctx, d, m) - case status.Enabled: - case status.Enabling: - case status.Disabling: - case status.Disabled: - log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) - case status.Restoring: - } - - if hasChanged { - _, err = utilityLBCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - } - - if d.HasChange("ha_mode") { - hamode := d.Get("ha_mode").(bool) - if hamode { - req := lb.HighlyAvailableRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - _, err := c.CloudAPI().LB().HighlyAvailable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("enable") { - enable := d.Get("enable").(bool) - req := lb.DisableEnableRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - if enable { - _, err := c.CloudAPI().LB().Enable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else { - _, err := c.CloudAPI().LB().Disable(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("start") { - start := d.Get("start").(bool) - lbId := uint64(d.Get("lb_id").(int)) - if start { - req := lb.StartRequest{LBID: lbId} - _, err := c.CloudAPI().LB().Start(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } else { - req := lb.StopRequest{LBID: lbId} - _, err := c.CloudAPI().LB().Stop(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("desc") { - req := lb.UpdateRequest{ - LBID: uint64(d.Get("lb_id").(int)), - Description: d.Get("desc").(string), - } - - _, err := c.CloudAPI().LB().Update(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - - if d.HasChange("restart") { - restart := d.Get("restart").(bool) - if restart { - req := lb.RestartRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - if safe, ok:= d.GetOk("safe"); ok { - req.Safe = safe.(bool) - } - - _, err := c.CloudAPI().LB().Restart(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("restore") { - restore := d.Get("restore").(bool) - if restore { - req := lb.RestoreRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - - _, err := c.CloudAPI().LB().Restore(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - if d.HasChange("config_reset") { - cfgReset := d.Get("config_reset").(bool) - if cfgReset { - req := lb.ConfigResetRequest{ - LBID: uint64(d.Get("lb_id").(int)), - } - - _, err := c.CloudAPI().LB().ConfigReset(ctx, req) - if err != nil { - return diag.FromErr(err) - } - } - } - - return resourceLBRead(ctx, d, m) -} - -func ResourceLB() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - CreateContext: resourceLBCreate, - ReadContext: resourceLBRead, - UpdateContext: resourceLBUpdate, - DeleteContext: resourceLBDelete, - - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: &constants.Timeout600s, - Read: &constants.Timeout300s, - Update: &constants.Timeout300s, - Delete: &constants.Timeout300s, - Default: &constants.Timeout300s, - }, - - Schema: lbResourceSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + "strconv" + + "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/cloudapi/lb" + "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" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" +) + +func resourceLBCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBCreate") + + haveRGID, err := existRGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveRGID { + return diag.Errorf("resourceLBCreate: can't create LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) + } + + haveExtNetID, err := existExtNetID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveExtNetID { + return diag.Errorf("resourceLBCreate: can't create LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) + } + + haveVins, err := existViNSID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveVins { + return diag.Errorf("resourceLBCreate: can't create LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) + } + + c := m.(*controller.ControllerCfg) + req := lb.CreateRequest{ + Name: d.Get("name").(string), + RGID: uint64(d.Get("rg_id").(int)), + ExtNetID: uint64(d.Get("extnet_id").(int)), + VINSID: uint64(d.Get("vins_id").(int)), + Start: d.Get("start").(bool), + } + + if desc, ok := d.GetOk("desc"); ok { + req.Description = desc.(string) + } + if haMode, ok := d.GetOk("ha_mode"); ok { + req.HighlyAvailable = haMode.(bool) + } + if sysctlParams, ok := d.GetOk("sysctl_params"); ok { + syscrlSliceMaps := sysctlParams.([]map[string]string) + res := make([]map[string]interface{}, 0, len(syscrlSliceMaps)) + for _, syscrlMap := range syscrlSliceMaps { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + req.SysctlParams = res + } + + lbId, err := c.CloudAPI().LB().Create(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(lbId, 10)) + d.Set("lb_id", lbId) + + w := dc.Warnings{} + + if enable, ok := d.GetOk("enable"); ok { + req := lb.DisableEnableRequest{ + LBID: lbId, + } + + if enable.(bool) { + _, err := c.CloudAPI().LB().Enable(ctx, req) + if err != nil { + w.Add(err) + } + } else { + _, err := c.CloudAPI().LB().Disable(ctx, req) + if err != nil { + w.Add(err) + } + } + + if start, ok := d.GetOk("start"); ok && enable.(bool) { + if start.(bool) { + req := lb.StartRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Start(ctx, req) + if err != nil { + w.Add(err) + } + } else { + req := lb.StopRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Stop(ctx, req) + if err != nil { + w.Add(err) + } + } + } + } + + return append(w.Get(), resourceLBRead(ctx, d, m)...) +} + +func resourceLBRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBRead") + + // c := m.(*controller.ControllerCfg) + + lbRec, err := utilityLBCheckPresence(ctx, d, m) + if lbRec == nil { + d.SetId("") + return diag.FromErr(err) + } + + hasChanged := false + + switch lbRec.Status { + case status.Modeled: + return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) + case status.Creating: + case status.Created: + case status.Deleting: + case status.Deleted: + // lbId, _ := strconv.ParseUint(d.Id(), 10, 64) + // restoreReq := lb.RestoreRequest{LBID: lbId} + // enableReq := lb.DisableEnableRequest{LBID: lbId} + + // _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) + // if err != nil { + // return diag.FromErr(err) + // } + // _, err = c.CloudAPI().LB().Enable(ctx, enableReq) + // if err != nil { + // return diag.FromErr(err) + // } + + // hasChanged = true + case status.Destroying: + return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceLBCreate(ctx, d, m) + case status.Enabled: + case status.Enabling: + case status.Disabling: + case status.Disabled: + log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) + case status.Restoring: + } + + if hasChanged { + lbRec, err = utilityLBCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + flattenResourceLB(d, lbRec) + + return nil +} + +func resourceLBDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBDelete") + + c := m.(*controller.ControllerCfg) + lbId, _ := strconv.ParseUint(d.Id(), 10, 64) + req := lb.DeleteRequest{ + LBID: lbId, + } + + if permanently, ok := d.GetOk("permanently"); ok { + req.Permanently = permanently.(bool) + } + + _, err := c.CloudAPI().LB().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceLBUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceLBUpdate") + c := m.(*controller.ControllerCfg) + + haveRGID, err := existRGID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveRGID { + return diag.Errorf("resourceLBUpdate: can't update LB because RGID %d is not allowed or does not exist", d.Get("rg_id").(int)) + } + + haveExtNetID, err := existExtNetID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveExtNetID { + return diag.Errorf("resourceLBUpdate: can't update LB because ExtNetID %d is not allowed or does not exist", d.Get("extnet_id").(int)) + } + + haveVins, err := existViNSID(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + + if !haveVins { + return diag.Errorf("resourceLBUpdate: can't update LB because ViNSID %d is not allowed or does not exist", d.Get("vins_id").(int)) + } + + lbRec, err := utilityLBCheckPresence(ctx, d, m) + if lbRec == nil { + d.SetId("") + return diag.FromErr(err) + } + + hasChanged := false + + switch lbRec.Status { + case status.Modeled: + return diag.Errorf("The LB is in status: %s, please, contact support for more information", lbRec.Status) + case status.Creating: + case status.Created: + case status.Deleting: + case status.Deleted: + if restore, ok := d.GetOk("restore"); ok && restore.(bool) { + restoreReq := lb.RestoreRequest{LBID: lbRec.ID} + + _, err := c.CloudAPI().LB().Restore(ctx, restoreReq) + if err != nil { + return diag.FromErr(err) + } + } + if enable, ok := d.GetOk("enable"); ok { + req := lb.DisableEnableRequest{ + LBID: lbRec.ID, + } + + if enable.(bool) { + _, err := c.CloudAPI().LB().Enable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + _, err := c.CloudAPI().LB().Disable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + + if start, ok := d.GetOk("start"); ok && enable.(bool) { + if start.(bool) { + req := lb.StartRequest{LBID: lbRec.ID} + _, err := c.CloudAPI().LB().Start(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + req := lb.StopRequest{LBID: lbRec.ID} + _, err := c.CloudAPI().LB().Stop(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + } + hasChanged = true + case status.Destroying: + return diag.Errorf("The LB is in progress with status: %s", lbRec.Status) + case status.Destroyed: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + // return resourceLBCreate(ctx, d, m) + case status.Enabled: + case status.Enabling: + case status.Disabling: + case status.Disabled: + log.Debugf("The LB is in status: %s, troubles may occur with update. Please, enable LB first.", lbRec.Status) + case status.Restoring: + } + + if hasChanged { + _, err = utilityLBCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } + + if d.HasChange("ha_mode") { + hamode := d.Get("ha_mode").(bool) + if hamode { + req := lb.HighlyAvailableRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + _, err := c.CloudAPI().LB().HighlyAvailable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("sysctl_params") { + syscrlSliceMaps := d.Get("sysctl_params").([]map[string]string) + res := make([]map[string]interface{}, 0, len(syscrlSliceMaps)) + for _, syscrlMap := range syscrlSliceMaps { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + + req := lb.UpdateSysctParamsRequest{ + LBID: uint64(d.Get("lb_id").(int)), + SysctlParams: res, + } + _, err := c.CloudAPI().LB().UpdateSysctlParams(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("enable") { + enable := d.Get("enable").(bool) + req := lb.DisableEnableRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + if enable { + _, err := c.CloudAPI().LB().Enable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + _, err := c.CloudAPI().LB().Disable(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("start") { + start := d.Get("start").(bool) + lbId := uint64(d.Get("lb_id").(int)) + if start { + req := lb.StartRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Start(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } else { + req := lb.StopRequest{LBID: lbId} + _, err := c.CloudAPI().LB().Stop(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("desc") { + req := lb.UpdateRequest{ + LBID: uint64(d.Get("lb_id").(int)), + Description: d.Get("desc").(string), + } + + _, err := c.CloudAPI().LB().Update(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("restart") { + restart := d.Get("restart").(bool) + if restart { + req := lb.RestartRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + if safe, ok := d.GetOk("safe"); ok { + req.Safe = safe.(bool) + } + + _, err := c.CloudAPI().LB().Restart(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("restore") { + restore := d.Get("restore").(bool) + if restore { + req := lb.RestoreRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + + _, err := c.CloudAPI().LB().Restore(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + if d.HasChange("config_reset") { + cfgReset := d.Get("config_reset").(bool) + if cfgReset { + req := lb.ConfigResetRequest{ + LBID: uint64(d.Get("lb_id").(int)), + } + + _, err := c.CloudAPI().LB().ConfigReset(ctx, req) + if err != nil { + return diag.FromErr(err) + } + } + } + + return resourceLBRead(ctx, d, m) +} + +func ResourceLB() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceLBCreate, + ReadContext: resourceLBRead, + UpdateContext: resourceLBUpdate, + DeleteContext: resourceLBDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: lbResourceSchemaMake(), + } +} diff --git a/internal/service/cloudapi/lb/utility_lb_list.go b/internal/service/cloudapi/lb/utility_lb_list.go index 63299a1..501752f 100644 --- a/internal/service/cloudapi/lb/utility_lb_list.go +++ b/internal/service/cloudapi/lb/utility_lb_list.go @@ -1,99 +1,103 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityLBListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*lb.ListLB, error) { - c := m.(*controller.ControllerCfg) - req := lb.ListRequest{} - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if account_id, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(account_id.(int)) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if tech_status, ok := d.GetOk("tech_status"); ok { - req.TechStatus = tech_status.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - if front_ip, ok := d.GetOk("front_ip"); ok { - req.FrontIP = front_ip.(string) - } - - if back_ip, ok := d.GetOk("back_ip"); ok { - req.BackIP = back_ip.(string) - } - - if includedeleted, ok := d.GetOk("includedeleted"); ok { - req.IncludeDeleted = includedeleted.(bool) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityLBListCheckPresence: load lb list") - lbList, err := c.CloudAPI().LB().List(ctx, req) - if err != nil { - return nil, err - } - - return lbList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityLBListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*lb.ListLB, error) { + c := m.(*controller.ControllerCfg) + req := lb.ListRequest{} + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if account_id, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(account_id.(int)) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if tech_status, ok := d.GetOk("tech_status"); ok { + req.TechStatus = tech_status.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + if front_ip, ok := d.GetOk("front_ip"); ok { + req.FrontIP = front_ip.(string) + } + + if back_ip, ok := d.GetOk("back_ip"); ok { + req.BackIP = back_ip.(string) + } + + if includedeleted, ok := d.GetOk("includedeleted"); ok { + req.IncludeDeleted = includedeleted.(bool) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityLBListCheckPresence: load lb list") + lbList, err := c.CloudAPI().LB().List(ctx, req) + if err != nil { + return nil, err + } + + return lbList, nil +} diff --git a/internal/service/cloudapi/lb/utility_lb_list_deleted.go b/internal/service/cloudapi/lb/utility_lb_list_deleted.go index e4a49b9..a5be51b 100644 --- a/internal/service/cloudapi/lb/utility_lb_list_deleted.go +++ b/internal/service/cloudapi/lb/utility_lb_list_deleted.go @@ -1,91 +1,95 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 lb - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityLBListDeletedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*lb.ListLB, error) { - c := m.(*controller.ControllerCfg) - req := lb.ListDeletedRequest{} - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if account_id, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(account_id.(int)) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if tech_status, ok := d.GetOk("tech_status"); ok { - req.TechStatus = tech_status.(string) - } - - if front_ip, ok := d.GetOk("front_ip"); ok { - req.FrontIP = front_ip.(string) - } - - if back_ip, ok := d.GetOk("back_ip"); ok { - req.BackIP = back_ip.(string) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityLBListDeletedCheckPresence: load lb list") - lbList, err := c.CloudAPI().LB().ListDeleted(ctx, req) - if err != nil { - return nil, err - } - - return lbList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 lb + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/lb" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityLBListDeletedCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*lb.ListLB, error) { + c := m.(*controller.ControllerCfg) + req := lb.ListDeletedRequest{} + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if account_id, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(account_id.(int)) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if tech_status, ok := d.GetOk("tech_status"); ok { + req.TechStatus = tech_status.(string) + } + + if front_ip, ok := d.GetOk("front_ip"); ok { + req.FrontIP = front_ip.(string) + } + + if back_ip, ok := d.GetOk("back_ip"); ok { + req.BackIP = back_ip.(string) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityLBListDeletedCheckPresence: load lb list") + lbList, err := c.CloudAPI().LB().ListDeleted(ctx, req) + if err != nil { + return nil, err + } + + return lbList, nil +} diff --git a/internal/service/cloudapi/locations/data_source_locations_list.go b/internal/service/cloudapi/locations/data_source_locations_list.go index 114a0a9..04c3968 100644 --- a/internal/service/cloudapi/locations/data_source_locations_list.go +++ b/internal/service/cloudapi/locations/data_source_locations_list.go @@ -1,190 +1,195 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 locations - -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/decort-golang-sdk/pkg/cloudapi/locations" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens" -) - -func flattenLocationsList(ll *locations.ListLocations) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len(ll.Data)) - for _, l := range ll.Data { - temp := map[string]interface{}{ - "ckey": l.CKey, - "meta": flattens.FlattenMeta(l.Meta), - "auth_broker": l.AuthBroker, - "flag": l.Flag, - "gid": l.GID, - "guid": l.GUID, - "id": l.ID, - "location_code": l.LocationCode, - "name": l.Name, - } - res = append(res, temp) - } - return res - -} - -func dataSourceLocationsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - locations, err := utilityLocationsListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - - d.Set("items", flattenLocationsList(locations)) - d.Set("entry_count", locations.EntryCount) - - return nil -} - -func dataSourceLocationsListSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "flag": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by flag", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by name", - }, - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by ID", - }, - "location_code": { - Type: schema.TypeString, - Optional: true, - Description: "Filter by location code", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "Locations list", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "meta": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "auth_broker": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "flag": { - Type: schema.TypeString, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - Description: "Grid id", - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - Description: "location id", - }, - "id": { - Type: schema.TypeInt, - Computed: true, - Description: "location id", - }, - "location_code": { - Type: schema.TypeString, - Computed: true, - Description: "Location code", - }, - "name": { - Type: schema.TypeString, - Computed: true, - Description: "Location name", - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } -} - -func DataSourceLocationsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLocationsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceLocationsListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 locations + +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/decort-golang-sdk/pkg/cloudapi/locations" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens" +) + +func flattenLocationsList(ll *locations.ListLocations) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(ll.Data)) + for _, l := range ll.Data { + temp := map[string]interface{}{ + "ckey": l.CKey, + "meta": flattens.FlattenMeta(l.Meta), + "auth_broker": l.AuthBroker, + "flag": l.Flag, + "gid": l.GID, + "guid": l.GUID, + "id": l.ID, + "location_code": l.LocationCode, + "name": l.Name, + } + res = append(res, temp) + } + return res + +} + +func dataSourceLocationsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + locations, err := utilityLocationsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + d.Set("items", flattenLocationsList(locations)) + d.Set("entry_count", locations.EntryCount) + + return nil +} + +func dataSourceLocationsListSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "flag": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by flag", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by name", + }, + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Filter by ID", + }, + "location_code": { + Type: schema.TypeString, + Optional: true, + Description: "Filter by location code", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "Locations list", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ckey": { + Type: schema.TypeString, + Computed: true, + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "auth_broker": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "flag": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "Grid id", + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + Description: "location id", + }, + "id": { + Type: schema.TypeInt, + Computed: true, + Description: "location id", + }, + "location_code": { + Type: schema.TypeString, + Computed: true, + Description: "Location code", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Location name", + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } +} + +func DataSourceLocationsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLocationsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceLocationsListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/locations/data_source_locations_url.go b/internal/service/cloudapi/locations/data_source_locations_url.go index 8d6a09d..3a35681 100644 --- a/internal/service/cloudapi/locations/data_source_locations_url.go +++ b/internal/service/cloudapi/locations/data_source_locations_url.go @@ -1,85 +1,85 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 locations - -import ( - "context" - "strings" - - "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 dataSourceLocationUrlRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - url, err := utilityLocationUrlCheckPresence(ctx, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - - url = strings.ReplaceAll(url, "\\", "") - url = strings.ReplaceAll(url, "\"", "") - d.Set("url", url) - - return nil -} - -func dataSourceLocationUrlSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "url": { - Type: schema.TypeString, - Computed: true, - Description: "Location url", - }, - } -} - -func DataSourceLocationUrl() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceLocationUrlRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceLocationUrlSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 locations + +import ( + "context" + "strings" + + "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 dataSourceLocationUrlRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + url, err := utilityLocationUrlCheckPresence(ctx, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + url = strings.ReplaceAll(url, "\\", "") + url = strings.ReplaceAll(url, "\"", "") + d.Set("url", url) + + return nil +} + +func dataSourceLocationUrlSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "url": { + Type: schema.TypeString, + Computed: true, + Description: "Location url", + }, + } +} + +func DataSourceLocationUrl() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceLocationUrlRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceLocationUrlSchemaMake(), + } +} diff --git a/internal/service/cloudapi/locations/utility_locations_list.go b/internal/service/cloudapi/locations/utility_locations_list.go index e45f0f0..dc01539 100644 --- a/internal/service/cloudapi/locations/utility_locations_list.go +++ b/internal/service/cloudapi/locations/utility_locations_list.go @@ -1,80 +1,84 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 locations - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityLocationsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*locations.ListLocations, error) { - c := m.(*controller.ControllerCfg) - req := locations.ListRequest{} - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if flag, ok := d.GetOk("flag"); ok { - req.Flag = flag.(string) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if location_code, ok := d.GetOk("location_code"); ok { - req.LocationCode = location_code.(string) - } - - log.Debugf("utilityLocationsListCheckPresence: load locations list") - locationsList, err := c.CloudAPI().Locations().List(ctx, req) - if err != nil { - return nil, err - } - - return locationsList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 locations + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/locations" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityLocationsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*locations.ListLocations, error) { + c := m.(*controller.ControllerCfg) + req := locations.ListRequest{} + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if flag, ok := d.GetOk("flag"); ok { + req.Flag = flag.(string) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if location_code, ok := d.GetOk("location_code"); ok { + req.LocationCode = location_code.(string) + } + + log.Debugf("utilityLocationsListCheckPresence: load locations list") + locationsList, err := c.CloudAPI().Locations().List(ctx, req) + if err != nil { + return nil, err + } + + return locationsList, nil +} diff --git a/internal/service/cloudapi/rg/data_source_rg.go b/internal/service/cloudapi/rg/data_source_rg.go index 74b3040..2dc46d1 100644 --- a/internal/service/cloudapi/rg/data_source_rg.go +++ b/internal/service/cloudapi/rg/data_source_rg.go @@ -68,7 +68,6 @@ func DataSourceResgroup() *schema.Resource { } } - // func sepsSchemaMake() map[string]*schema.Schema { // res := map[string]*schema.Schema{ // "sep_id": { @@ -300,6 +299,13 @@ func dataSourceRgSchemaMake() map[string]*schema.Schema { Schema: aclSchemaMake(), }, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "created_by": { Type: schema.TypeString, Computed: true, @@ -418,5 +424,3 @@ func dataSourceRgSchemaMake() map[string]*schema.Schema { } return res } - - diff --git a/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go b/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go index 9e78203..5bf5947 100644 --- a/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_affinity_groups_list.go @@ -83,8 +83,17 @@ func dataSourceRgAffinityGroupsListSchemaMake() map[string]*schema.Schema { "ids": { 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, + }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, }, }, }, diff --git a/internal/service/cloudapi/rg/data_source_rg_list.go b/internal/service/cloudapi/rg/data_source_rg_list.go index 06be1fe..dcbecce 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list.go +++ b/internal/service/cloudapi/rg/data_source_rg_list.go @@ -1,280 +1,292 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 rg - -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 dataSourceRgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - rgList, err := utilityRgListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenRgList(rgList)) - d.Set("entry_count", rgList.EntryCount) - - return nil -} - -func dataSourceRgListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "by_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by ID", - }, - "name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by name", - }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Find by account ID", - }, - "account_name": { - Type: schema.TypeString, - Optional: true, - Description: "Find by account name", - }, - "created_after": { - Type: schema.TypeInt, - Optional: true, - Description: "Find RGs created after specific time (unix timestamp)", - }, - "created_before": { - Type: schema.TypeInt, - Optional: true, - Description: "Find RGs created before specific time (unix timestamp)", - }, - "status": { - Type: schema.TypeString, - Optional: true, - Description: "Find by status", - }, - "lock_status": { - Type: schema.TypeString, - Optional: true, - Description: "Find by lock status", - }, - "includedeleted": { - Type: schema.TypeBool, - Optional: true, - Default: false, - Description: "included deleted resource groups", - }, - "page": { - Type: schema.TypeInt, - Optional: true, - Description: "Page number", - }, - "size": { - Type: schema.TypeInt, - Optional: true, - Description: "Page size", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "account_acl": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: aclSchemaMake(), - }, - }, - "account_id": { - Type: schema.TypeInt, - Computed: true, - }, - "account_name": { - Type: schema.TypeString, - Computed: true, - }, - "created_by": { - Type: schema.TypeString, - Computed: true, - }, - "created_time": { - Type: schema.TypeInt, - Computed: true, - }, - "def_net_id": { - Type: schema.TypeInt, - Computed: true, - }, - "def_net_type": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_by": { - Type: schema.TypeString, - Computed: true, - }, - "deleted_time": { - Type: schema.TypeInt, - Computed: true, - }, - "desc": { - Type: schema.TypeString, - Computed: true, - }, - "dirty": { - Type: schema.TypeBool, - Computed: true, - }, - "gid": { - Type: schema.TypeInt, - Computed: true, - }, - "guid": { - Type: schema.TypeInt, - Computed: true, - }, - "rg_id": { - Type: schema.TypeInt, - Computed: true, - }, - "lock_status": { - Type: schema.TypeString, - Computed: true, - }, - "milestones": { - Type: schema.TypeInt, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "register_computes": { - Type: schema.TypeBool, - Computed: true, - }, - "resource_limits": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: resourceLimitsSchemaMake(), - }, - }, - "secret": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "updated_by": { - Type: schema.TypeString, - Computed: true, - }, - "updated_time": { - Type: schema.TypeInt, - Computed: true, - }, - "vins": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "vms": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "resource_types": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "cpu_allocation_parameter": { - Type: schema.TypeString, - Computed: true, - }, - "cpu_allocation_ratio": { - Type: schema.TypeFloat, - Computed: true, - }, - "uniq_pools": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceRgList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceRgListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceRgListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 rg + +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 dataSourceRgListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + rgList, err := utilityRgListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenRgList(rgList)) + d.Set("entry_count", rgList.EntryCount) + + return nil +} + +func dataSourceRgListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by account ID", + }, + "account_name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by account name", + }, + "created_after": { + Type: schema.TypeInt, + Optional: true, + Description: "Find RGs created after specific time (unix timestamp)", + }, + "created_before": { + Type: schema.TypeInt, + Optional: true, + Description: "Find RGs created before specific time (unix timestamp)", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by status", + }, + "lock_status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by lock status", + }, + "includedeleted": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "included deleted resource groups", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: aclSchemaMake(), + }, + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_id": { + Type: schema.TypeInt, + Computed: true, + }, + "def_net_type": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_by": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "dirty": { + Type: schema.TypeBool, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "lock_status": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "register_computes": { + Type: schema.TypeBool, + Computed: true, + }, + "resource_limits": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: resourceLimitsSchemaMake(), + }, + }, + "secret": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vins": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "vms": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "resource_types": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "cpu_allocation_parameter": { + Type: schema.TypeString, + Computed: true, + }, + "cpu_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + "uniq_pools": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceRgList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceRgListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceRgListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/rg/data_source_rg_list_computes.go b/internal/service/cloudapi/rg/data_source_rg_list_computes.go index a8b68b9..37d6889 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_computes.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_computes.go @@ -135,6 +135,11 @@ func dataSourceRgListComputesSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by extnet ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/rg/data_source_rg_list_deleted.go b/internal/service/cloudapi/rg/data_source_rg_list_deleted.go index 34e7240..3a207b3 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_deleted.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_deleted.go @@ -93,6 +93,11 @@ func dataSourceRgListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by lock status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -123,6 +128,13 @@ func dataSourceRgListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "cpu_allocation_parameter": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/rg/data_source_rg_list_lb.go b/internal/service/cloudapi/rg/data_source_rg_list_lb.go index 280ee4f..2a91776 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_lb.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_lb.go @@ -257,11 +257,6 @@ func dataSourceRgListLbSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by name", }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by account ID", - }, "tech_status": { Type: schema.TypeString, Optional: true, @@ -282,6 +277,11 @@ func dataSourceRgListLbSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by backend IP", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/rg/data_source_rg_list_vins.go b/internal/service/cloudapi/rg/data_source_rg_list_vins.go index fe449e5..28e7c77 100644 --- a/internal/service/cloudapi/rg/data_source_rg_list_vins.go +++ b/internal/service/cloudapi/rg/data_source_rg_list_vins.go @@ -82,6 +82,11 @@ func dataSourceRgListVinsSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by ViNS ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -129,6 +134,14 @@ func dataSourceRgListVinsSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "extnet_id": { + Type: schema.TypeInt, + Computed: true, + }, + "free_ips": { + Type: schema.TypeInt, + Computed: true, + }, "id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/rg/flattens.go b/internal/service/cloudapi/rg/flattens.go index c4d83e4..0f20842 100644 --- a/internal/service/cloudapi/rg/flattens.go +++ b/internal/service/cloudapi/rg/flattens.go @@ -91,9 +91,10 @@ func flattenResgroup(d *schema.ResourceData, details rg.RecordResourceGroup) err d.Set("gid", details.GID) d.Set("def_net_type", details.DefNetType) d.Set("name", details.Name) - // d.Set("resources", flattenRgResource(details.Resources)) + d.Set("quota", flattenQuota(details.ResourceLimits)) d.Set("account_name", details.AccountName) d.Set("acl", flattenRgAcl(details.ACL)) + d.Set("compute_features", details.ComputeFeatures) d.Set("vms", details.Computes) d.Set("created_by", details.CreatedBy) d.Set("created_time", details.CreatedTime) @@ -137,6 +138,23 @@ func flattenRgSeps(seps map[string]map[string]rg.DiskUsage) []map[string]interfa return res } +func flattenQuota(resource rg.ResourceLimits) []map[string]interface{} { + res := make([]map[string]interface{}, 0) + temp := map[string]interface{}{ + "cpu": resource.CUC, + "ram": resource.CUM, + "disk": resource.CUDM, + "ext_ips": resource.CUI, + "ext_traffic": resource.CUNP, + "gpu_units": resource.GPUUnits, + "cu_d": resource.CUD, + } + + res = append(res, temp) + + return res +} + func flattenResource(resource rg.Resource) []map[string]interface{} { res := make([]map[string]interface{}, 0) temp := map[string]interface{}{ @@ -161,6 +179,7 @@ func flattenRg(d *schema.ResourceData, itemRg rg.RecordResourceGroup) { d.Set("account_name", itemRg.AccountName) d.Set("acl", flattenRgAcl(itemRg.ACL)) d.Set("computes", itemRg.Computes) + d.Set("compute_features", itemRg.ComputeFeatures) d.Set("created_by", itemRg.CreatedBy) d.Set("created_time", itemRg.CreatedTime) d.Set("def_net_id", itemRg.DefNetID) @@ -212,6 +231,7 @@ func flattenRgList(rgl *rg.ListResourceGroups) []map[string]interface{} { "account_acl": flattenRgAcl(rg.ACL), "account_id": rg.AccountID, "account_name": rg.AccountName, + "compute_features": rg.ComputeFeatures, "created_by": rg.CreatedBy, "created_time": rg.CreatedTime, "def_net_id": rg.DefNetID, @@ -242,7 +262,6 @@ func flattenRgList(rgl *rg.ListResourceGroups) []map[string]interface{} { res = append(res, temp) } return res - } func flattenRgAcl(rgAcls rg.ListACL) []map[string]interface{} { @@ -491,6 +510,8 @@ func flattenRgListVins(lv *rg.ListVINS) []map[string]interface{} { "deleted_by": vins.DeletedBy, "deleted_time": vins.DeletedTime, "external_ip": vins.ExternalIP, + "extnet_id": vins.ExtnetId, + "free_ips": vins.FreeIPs, "id": vins.ID, "name": vins.Name, "network": vins.Network, @@ -542,7 +563,7 @@ func flattenRgListGroups(list *rg.ListAffinityGroups) []map[string]interface{} { for label, ag := range groupVal { temp := map[string]interface{}{ "label": label, - "ids": ag, + "ids": flattenRgAffinityListGroup(ag), } res = append(res, temp) } @@ -551,6 +572,19 @@ func flattenRgListGroups(list *rg.ListAffinityGroups) []map[string]interface{} { return res } +func flattenRgAffinityListGroup(list rg.ListAffinityGroup) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(list)) + for _, ag := range list { + temp := map[string]interface{}{ + "id": ag.ID, + "node_id": ag.NodeID, + } + res = append(res, temp) + } + + return res +} + func flattenRgUsageResource(d *schema.ResourceData, usage rg.RecordResourceUsage) { d.Set("cpu", usage.CPU) d.Set("disk_size", usage.DiskSize) diff --git a/internal/service/cloudapi/rg/resource_rg.go b/internal/service/cloudapi/rg/resource_rg.go index a804cc5..2fa6dff 100644 --- a/internal/service/cloudapi/rg/resource_rg.go +++ b/internal/service/cloudapi/rg/resource_rg.go @@ -92,26 +92,51 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter // Owner: c.GetDecortUsername(), } - setQuota := false - var quotaRecord QuotaRecord - if argValue, ok := d.GetOk("quota"); ok { - log.Debugf("resourceResgroupCreate: setting Quota on RG requested") - quotaRecord = makeQuotaRecord(argValue.([]interface{})) - setQuota = true - } - - log.Debugf("resourceResgroupCreate: called for RG name %s, account ID %d", - // c.GetDecortUsername(), - rgName.(string), d.Get("account_id").(int)) - - if setQuota { - req.MaxCPUCapacity = int64(quotaRecord.Cpu) - req.MaxVDiskCapacity = int64(quotaRecord.Disk) - req.MaxMemoryCapacity = int64(quotaRecord.Ram) - req.MaxNetworkPeerTransfer = int64(quotaRecord.ExtTraffic) - req.MaxNumPublicIP = int64(quotaRecord.ExtIPs) + if quota, ok := d.GetOk("quota"); ok { + quotaBlocks := quota.([]interface{})[0] + quotaMap := quotaBlocks.(map[string]interface{}) + + if quotaMap["ram"] != nil { + maxMemCap := int64(quotaMap["ram"].(int)) + if maxMemCap == 0 { + req.MaxMemoryCapacity = -1 + } else { + req.MaxMemoryCapacity = maxMemCap + } + } + if quotaMap["disk"] != nil { + maxDiskCap := int64(quotaMap["disk"].(int)) + if maxDiskCap == 0 { + req.MaxVDiskCapacity = -1 + } else { + req.MaxVDiskCapacity = maxDiskCap + } + } + if quotaMap["cpu"] != nil { + maxCPUCap := int64(quotaMap["cpu"].(int)) + if maxCPUCap == 0 { + req.MaxCPUCapacity = -1 + } else { + req.MaxCPUCapacity = maxCPUCap + } + } + if quotaMap["ext_ips"] != nil { + maxNumPublicIP := int64(quotaMap["ext_ips"].(int)) + if maxNumPublicIP == 0 { + req.MaxNumPublicIP = -1 + } else { + req.MaxNumPublicIP = maxNumPublicIP + } + } + if quotaMap["ext_traffic"] != nil { + maxNP := int64(quotaMap["ext_traffic"].(int)) + if maxNP == 0 { + req.MaxNetworkPeerTransfer = -1 + } else { + req.MaxNetworkPeerTransfer = maxNP + } + } } - if defNetType, ok := d.GetOk("def_net_type"); ok { req.DefNet = defNetType.(string) // NOTE: in API default network type is set by "def_net" parameter } else { @@ -297,6 +322,7 @@ func resourceResgroupRead(ctx context.Context, d *schema.ResourceData, m interfa return diag.FromErr(err) } } + return diag.FromErr(flattenResgroup(d, *rgData)) } @@ -557,8 +583,8 @@ func ResourceRgSchemaMake() map[string]*schema.Schema { }, "gid": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, // ForceNew: true, Description: "Unique ID of the grid, where this resource group is deployed.", }, @@ -603,57 +629,57 @@ func ResourceRgSchemaMake() map[string]*schema.Schema { }, "owner": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, }, "quota": { Type: schema.TypeList, Optional: true, + Computed: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cpu": { Type: schema.TypeInt, Optional: true, - Default: -1, + Computed: true, Description: "Limit on the total number of CPUs in this resource group.", }, - "ram": { Type: schema.TypeInt, // NB: API expects and returns this as float in units of MB! This may be changed in the future. Optional: true, - Default: -1, + Computed: true, Description: "Limit on the total amount of RAM in this resource group, specified in MB.", }, - "disk": { Type: schema.TypeInt, Optional: true, - Default: -1, - Description: "Limit on the total volume of storage resources in this resource group, specified in GB.", + Computed: true, + Description: "Limit on the total volume of virtual storage resources in this resource group, specified in GB.", }, - "ext_traffic": { Type: schema.TypeInt, Optional: true, - Default: -1, + Computed: true, Description: "Limit on the total ingress network traffic for this resource group, specified in GB.", }, - "ext_ips": { Type: schema.TypeInt, Optional: true, - Default: -1, + Computed: true, Description: "Limit on the total number of external IP addresses this resource group can use.", }, - "gpu_units": { Type: schema.TypeInt, - Optional: true, - Default: -1, + Computed: true, Description: "Limit on the total number of virtual GPUs this resource group can use.", }, + "cu_d": { + Type: schema.TypeInt, + Computed: true, + Description: "Limit on the total volume of storage resources in this resource group, specified in GB.", + }, }, }, Description: "Quota settings for this resource group.", @@ -771,6 +797,13 @@ func ResourceRgSchemaMake() map[string]*schema.Schema { Schema: aclSchemaMake(), }, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "deleted_by": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/cloudapi/rg/state_upgraders.go b/internal/service/cloudapi/rg/state_upgraders.go index 32afcde..0eee669 100644 --- a/internal/service/cloudapi/rg/state_upgraders.go +++ b/internal/service/cloudapi/rg/state_upgraders.go @@ -8,10 +8,21 @@ import ( func resourceRGStateUpgradeV1(ctx context.Context, rawState map[string]interface{}, meta any) (map[string]interface{}, error) { log.Debug("resourceRGStateUpgradeV1: upgrading state") - oldQuotaList := rawState["quota"].([]interface{}) - if len(oldQuotaList) != 0 { - oldQuota := oldQuotaList[0].(map[string]interface{}) - oldQuota["ram"] = int64(oldQuota["ram"].(float64)) + quota, ok := rawState["quota"] + if !ok || quota == nil { + rawState["quota"] = QuotaRecord{ + Cpu: -1, + Ram: -1, + Disk: -1, + ExtTraffic: -1, + ExtIPs: -1, + GpuUnits: -1, + } + return rawState, nil } + + oldQuotaList := quota.([]interface{}) + oldQuota := oldQuotaList[0].(map[string]interface{}) + oldQuota["ram"] = int64(oldQuota["ram"].(float64)) return rawState, nil } diff --git a/internal/service/cloudapi/rg/utility_rg.go b/internal/service/cloudapi/rg/utility_rg.go index 0ce9371..01247c5 100644 --- a/internal/service/cloudapi/rg/utility_rg.go +++ b/internal/service/cloudapi/rg/utility_rg.go @@ -78,20 +78,52 @@ func utilityUpdateRG(ctx context.Context, d *schema.ResourceData, m interface{}, if d.HasChange("quota") { log.Debugf("resourceResgroupUpdate: quota specified - looking for deltas from the old quota.") - quotaList := d.Get("quota").([]interface{}) - if len(quotaList) != 0 { - quota := quotaList[0].(map[string]interface{}) - req.MaxCPUCapacity = int64(quota["cpu"].(int)) - req.MaxVDiskCapacity = int64(quota["disk"].(int)) - req.MaxMemoryCapacity = int64(quota["ram"].(int)) - req.MaxNetworkPeerTransfer = int64(quota["ext_traffic"].(int)) - req.MaxNumPublicIP = int64(quota["ext_ips"].(int)) - } else { - req.MaxCPUCapacity = -1 - req.MaxVDiskCapacity = -1 - req.MaxMemoryCapacity = -1 - req.MaxNetworkPeerTransfer = -1 - req.MaxNumPublicIP = -1 + + if quota, ok := d.GetOk("quota"); ok { + resLimits := quota.([]interface{})[0] + resLimitsConv := resLimits.(map[string]interface{}) + + if resLimitsConv["ram"] != nil { + maxMemCap := int64(resLimitsConv["ram"].(int)) + if maxMemCap == 0 { + req.MaxMemoryCapacity = -1 + } else { + req.MaxMemoryCapacity = maxMemCap + } + } + + if resLimitsConv["disk"] != nil { + maxDiskCap := int64(resLimitsConv["disk"].(int)) + if maxDiskCap == 0 { + req.MaxVDiskCapacity = -1 + } else { + req.MaxVDiskCapacity = maxDiskCap + } + } + if resLimitsConv["cpu"] != nil { + maxCPUCap := int64(resLimitsConv["cpu"].(int)) + if maxCPUCap == 0 { + req.MaxCPUCapacity = -1 + } else { + req.MaxCPUCapacity = maxCPUCap + } + } + if resLimitsConv["ext_ips"] != nil { + maxNumPublicIP := int64(resLimitsConv["ext_ips"].(int)) + if maxNumPublicIP == 0 { + req.MaxNumPublicIP = -1 + } else { + req.MaxNumPublicIP = maxNumPublicIP + } + } + if resLimitsConv["ext_traffic"] != nil { + maxNP := int64(resLimitsConv["ext_traffic"].(int)) + if maxNP == 0 { + req.MaxNetworkPeerTransfer = -1 + } else { + req.MaxNetworkPeerTransfer = maxNP + } + } } } diff --git a/internal/service/cloudapi/rg/utility_rg_list.go b/internal/service/cloudapi/rg/utility_rg_list.go index 4791ddd..c13cfc6 100644 --- a/internal/service/cloudapi/rg/utility_rg_list.go +++ b/internal/service/cloudapi/rg/utility_rg_list.go @@ -1,90 +1,93 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 rg - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityRgListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*rg.ListResourceGroups, error) { - c := m.(*controller.ControllerCfg) - req := rg.ListRequest{} - - if byId, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(byId.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if accountName, ok := d.GetOk("account_name"); ok { - req.AccountName = accountName.(string) - } - if createdAfter, ok := d.GetOk("created_after"); ok { - req.CreatedAfter = uint64(createdAfter.(int)) - } - if createdBefore, ok := d.GetOk("created_before"); ok { - req.CreatedBefore = uint64(createdBefore.(int)) - } - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - if lockStatus, ok := d.GetOk("lock_status"); ok { - req.LockStatus = lockStatus.(string) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if includedeleted, ok := d.GetOk("includedeleted"); ok { - req.IncludeDeleted = includedeleted.(bool) - } - - log.Debugf("utilityRgListCheckPresence: load rg list") - rgList, err := c.CloudAPI().RG().List(ctx, req) - if err != nil { - return nil, err - } - - return rgList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 rg + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/rg" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityRgListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*rg.ListResourceGroups, error) { + c := m.(*controller.ControllerCfg) + req := rg.ListRequest{} + + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byId.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if accountName, ok := d.GetOk("account_name"); ok { + req.AccountName = accountName.(string) + } + if createdAfter, ok := d.GetOk("created_after"); ok { + req.CreatedAfter = uint64(createdAfter.(int)) + } + if createdBefore, ok := d.GetOk("created_before"); ok { + req.CreatedBefore = uint64(createdBefore.(int)) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if lockStatus, ok := d.GetOk("lock_status"); ok { + req.LockStatus = lockStatus.(string) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if includedeleted, ok := d.GetOk("includedeleted"); ok { + req.IncludeDeleted = includedeleted.(bool) + } + + log.Debugf("utilityRgListCheckPresence: load rg list") + rgList, err := c.CloudAPI().RG().List(ctx, req) + if err != nil { + return nil, err + } + + return rgList, nil +} diff --git a/internal/service/cloudapi/rg/utility_rg_list_computes.go b/internal/service/cloudapi/rg/utility_rg_list_computes.go index d3c66df..b1565b4 100644 --- a/internal/service/cloudapi/rg/utility_rg_list_computes.go +++ b/internal/service/cloudapi/rg/utility_rg_list_computes.go @@ -78,6 +78,10 @@ func utilityRgListComputesCheckPresence(ctx context.Context, d *schema.ResourceD req.ExtNetID = uint64(extnet_id.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/rg/utility_rg_list_deleted.go b/internal/service/cloudapi/rg/utility_rg_list_deleted.go index 2044f76..b801ce5 100644 --- a/internal/service/cloudapi/rg/utility_rg_list_deleted.go +++ b/internal/service/cloudapi/rg/utility_rg_list_deleted.go @@ -72,6 +72,10 @@ func utilityRgListDeletedCheckPresence(ctx context.Context, d *schema.ResourceDa req.LockStatus = lock_status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if size, ok := d.GetOk("size"); ok { req.Size = uint64(size.(int)) } diff --git a/internal/service/cloudapi/rg/utility_rg_list_lb.go b/internal/service/cloudapi/rg/utility_rg_list_lb.go index 54ed90a..161b1a7 100644 --- a/internal/service/cloudapi/rg/utility_rg_list_lb.go +++ b/internal/service/cloudapi/rg/utility_rg_list_lb.go @@ -54,10 +54,6 @@ func utilityRgListLbCheckPresence(ctx context.Context, d *schema.ResourceData, m req.Name = name.(string) } - if account_id, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(account_id.(int)) - } - if tech_status, ok := d.GetOk("tech_status"); ok { req.TechStatus = tech_status.(string) } @@ -74,6 +70,10 @@ func utilityRgListLbCheckPresence(ctx context.Context, d *schema.ResourceData, m req.BackIP = back_ip.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/rg/utility_rg_list_vins.go b/internal/service/cloudapi/rg/utility_rg_list_vins.go index 2befba8..ee78c79 100644 --- a/internal/service/cloudapi/rg/utility_rg_list_vins.go +++ b/internal/service/cloudapi/rg/utility_rg_list_vins.go @@ -62,6 +62,10 @@ func utilityRgListVinsCheckPresence(ctx context.Context, d *schema.ResourceData, req.VINSID = uint64(vins_id.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudapi/snapshot/data_source_snapshot_list.go b/internal/service/cloudapi/snapshot/data_source_snapshot_list.go index 0a1cc78..5f43d7a 100644 --- a/internal/service/cloudapi/snapshot/data_source_snapshot_list.go +++ b/internal/service/cloudapi/snapshot/data_source_snapshot_list.go @@ -1,121 +1,121 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 snapshot - -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 dataSourceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - snapshotList, err := utilitySnapshotListCheckPresence(ctx, d, m) - if err != nil { - return diag.FromErr(err) - } - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenSnapshotList(snapshotList)) - d.Set("entry_count", snapshotList.EntryCount) - return nil -} - -func dataSourceSnapshotListSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "compute_id": { - Type: schema.TypeInt, - Required: true, - ForceNew: true, - Description: "ID of the compute instance to create snapshot for.", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Description: "snapshot list", - Elem: &schema.Resource{ - Schema: dataSourceSnapshotSchemaMake(), - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - - return rets -} - -func dataSourceSnapshotSchemaMake() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "label": { - Type: schema.TypeString, - Computed: true, - Description: "text label for snapshot. Must be unique among this compute snapshots.", - }, - "disks": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - Description: "guid of the snapshot", - }, - "timestamp": { - Type: schema.TypeInt, - Computed: true, - Description: "timestamp", - }, - } -} - -func DataSourceSnapshotList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceSnapshotListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceSnapshotListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 snapshot + +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 dataSourceSnapshotListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + snapshotList, err := utilitySnapshotListCheckPresence(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenSnapshotList(snapshotList)) + d.Set("entry_count", snapshotList.EntryCount) + return nil +} + +func dataSourceSnapshotListSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + Description: "ID of the compute instance to create snapshot for.", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Description: "snapshot list", + Elem: &schema.Resource{ + Schema: dataSourceSnapshotSchemaMake(), + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return rets +} + +func dataSourceSnapshotSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "label": { + Type: schema.TypeString, + Computed: true, + Description: "text label for snapshot. Must be unique among this compute snapshots.", + }, + "disks": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "guid of the snapshot", + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + Description: "timestamp", + }, + } +} + +func DataSourceSnapshotList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceSnapshotListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceSnapshotListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/stack/data_source_stack.go b/internal/service/cloudapi/stack/data_source_stack.go index 7e516b0..10bd1bd 100644 --- a/internal/service/cloudapi/stack/data_source_stack.go +++ b/internal/service/cloudapi/stack/data_source_stack.go @@ -1,110 +1,110 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 stack - -import ( - "context" - "strconv" - - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func dataSourceStackRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - stack, err := utilityStackCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") // ensure ID is empty in this case - return diag.FromErr(err) - } - d.SetId(strconv.Itoa(d.Get("stack_id").(int))) - flattenStack(d, stack) - return nil -} - -func dataSourceStackSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "stack_id": { - Type: schema.TypeInt, - Required: true, - }, - "cpu_allocation_ratio": { - Type: schema.TypeFloat, - Computed: true, - }, - "descr": { - Type: schema.TypeString, - Computed: true, - }, - "drivers": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - "mem_allocation_ratio": { - Type: schema.TypeFloat, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "status": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - } - return res -} - -func DataSourceStack() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceStackRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceStackSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 stack + +import ( + "context" + "strconv" + + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceStackRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + stack, err := utilityStackCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + d.SetId(strconv.Itoa(d.Get("stack_id").(int))) + flattenStack(d, stack) + return nil +} + +func dataSourceStackSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "stack_id": { + Type: schema.TypeInt, + Required: true, + }, + "cpu_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + "descr": { + Type: schema.TypeString, + Computed: true, + }, + "drivers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "mem_allocation_ratio": { + Type: schema.TypeFloat, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + } + return res +} + +func DataSourceStack() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceStackRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceStackSchemaMake(), + } +} diff --git a/internal/service/cloudapi/stack/data_source_stack_list.go b/internal/service/cloudapi/stack/data_source_stack_list.go index a50988d..2cd9f7b 100644 --- a/internal/service/cloudapi/stack/data_source_stack_list.go +++ b/internal/service/cloudapi/stack/data_source_stack_list.go @@ -78,6 +78,11 @@ func dataSourceStackListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/stack/utility_stack_list.go b/internal/service/cloudapi/stack/utility_stack_list.go index c8ea467..e868d82 100644 --- a/internal/service/cloudapi/stack/utility_stack_list.go +++ b/internal/service/cloudapi/stack/utility_stack_list.go @@ -1,77 +1,82 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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 stack - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/stack" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityStackListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*stack.ListStacks, error) { - c := m.(*controller.ControllerCfg) - req := stack.ListRequest{} - - if byId, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(byId.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - if stackType, ok := d.GetOk("type"); ok { - req.Type = stackType.(string) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - log.Debugf("utilityStackListCheckPresence: load stack list") - stackList, err := c.CloudAPI().Stack().List(ctx, req) - if err != nil { - return nil, err - } - - return stackList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 stack + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/stack" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityStackListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*stack.ListStacks, error) { + c := m.(*controller.ControllerCfg) + req := stack.ListRequest{} + + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byId.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + if stackType, ok := d.GetOk("type"); ok { + req.Type = stackType.(string) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + log.Debugf("utilityStackListCheckPresence: load stack list") + stackList, err := c.CloudAPI().Stack().List(ctx, req) + if err != nil { + return nil, err + } + + return stackList, nil +} diff --git a/internal/service/cloudapi/vfpool/data_source_vfpool.go b/internal/service/cloudapi/vfpool/data_source_vfpool.go new file mode 100644 index 0000000..9fd6c0e --- /dev/null +++ b/internal/service/cloudapi/vfpool/data_source_vfpool.go @@ -0,0 +1,165 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 vfpool + +import ( + "context" + "strconv" + + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceVFPoolRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vfpool, err := utilityVFpoolCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + d.SetId(strconv.Itoa(d.Get("vfpool_id").(int))) + flattenVFPool(d, vfpool) + return nil +} + +func dataSourceVFPoolSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "vfpool_id": { + Type: schema.TypeInt, + Required: true, + }, + "account_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "rg_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vfs": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vf_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "nic_name": { + Type: schema.TypeString, + Computed: true, + }, + "vfs_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "claimed": { + Type: schema.TypeBool, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + return res +} + +func DataSourceVFPool() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceVFPoolRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceVFPoolSchemaMake(), + } +} diff --git a/internal/service/cloudapi/vfpool/data_source_vfpool_list.go b/internal/service/cloudapi/vfpool/data_source_vfpool_list.go new file mode 100644 index 0000000..6238a29 --- /dev/null +++ b/internal/service/cloudapi/vfpool/data_source_vfpool_list.go @@ -0,0 +1,229 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 vfpool + +import ( + "context" + + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceVFPoolListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vfpoolList, err := utilityVFpoolListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenVFPoolList(vfpoolList)) + d.Set("entry_count", vfpoolList.EntryCount) + return nil +} + +func dataSourceVFPoolListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by ID", + }, + "gid": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by Grid ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: "Find by description", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by status", + }, + "account_access": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by accountAccess", + }, + "rg_access": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by rgAccess", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "vfpool_id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "rg_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vfs": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vf_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "nic_name": { + Type: schema.TypeString, + Computed: true, + }, + "vfs_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "claimed": { + Type: schema.TypeBool, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return res +} + +func DataSourceVFPoolList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceVFPoolListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceVFPoolListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/vfpool/flattens.go b/internal/service/cloudapi/vfpool/flattens.go new file mode 100644 index 0000000..84815f1 --- /dev/null +++ b/internal/service/cloudapi/vfpool/flattens.go @@ -0,0 +1,120 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vfpool + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vfpool" +) + +func flattenVFPoolList(vfpooll *vfpool.ListVFPool) []map[string]interface{} { + log.Debugf("flattenVFPoolList start") + res := make([]map[string]interface{}, 0, len(vfpooll.Data)) + for _, vfpool := range vfpooll.Data { + temp := map[string]interface{}{ + "account_access": vfpool.AccountAccess, + "created_time": vfpool.CreatedTime, + "description": vfpool.Description, + "gid": vfpool.GID, + "guid": vfpool.GUID, + "vfpool_id": vfpool.ID, + "name": vfpool.Name, + "rg_access": vfpool.RGAccess, + "status": vfpool.Status, + "updated_time": vfpool.UpdatedTime, + "vfs": flattenVFSList(vfpool.VFS), + } + res = append(res, temp) + } + log.Debugf("flattenVFPoolList end") + return res + +} + +func flattenVFPool(d *schema.ResourceData, item *vfpool.RecordVFPool) error { + log.Debugf("flattenVFPool: start decoded VFPool name %q / ID %d", + item.Name, item.ID) + + d.Set("account_access", item.AccountAccess) + d.Set("created_time", item.CreatedTime) + d.Set("description", item.Description) + d.Set("gid", item.GID) + d.Set("guid", item.GUID) + d.Set("name", item.Name) + d.Set("rg_access", item.RGAccess) + d.Set("status", item.Status) + d.Set("updated_time", item.UpdatedTime) + d.Set("vfs", flattenVFSList(item.VFS)) + + log.Debugf("flattenVFPool: decoded VFPool name %q / ID %d, complete", + item.Name, item.ID) + return nil +} + +func flattenVFSList(vfsItem []vfpool.VFS) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vfsItem)) + for _, item := range vfsItem { + temp := map[string]interface{}{ + "node_id": item.NodeID, + "vf_list": flattenVFList(item.VFList), + } + res = append(res, temp) + } + return res +} + +func flattenVFList(vfItem vfpool.VFList) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vfItem)) + for _, item := range vfItem { + temp := map[string]interface{}{ + "nic_name": item.NicName, + "vfs_info": flattenVFInfoList(item.VFSInfo), + } + res = append(res, temp) + } + return res +} + +func flattenVFInfoList(vfInfo vfpool.VFSInfoList) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vfInfo)) + for _, item := range vfInfo { + temp := map[string]interface{}{ + "id": item.ID, + "claimed": item.Claimed, + "vm_id": item.VMID, + } + res = append(res, temp) + } + return res +} diff --git a/internal/service/cloudapi/vfpool/utility_vfpool.go b/internal/service/cloudapi/vfpool/utility_vfpool.go new file mode 100644 index 0000000..3428e72 --- /dev/null +++ b/internal/service/cloudapi/vfpool/utility_vfpool.go @@ -0,0 +1,62 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vfpool + +import ( + "context" + "strconv" + + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vfpool" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityVFpoolCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vfpool.RecordVFPool, error) { + c := m.(*controller.ControllerCfg) + req := vfpool.GetRequest{} + + if d.Id() != "" { + vfpoolId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.VFPoolID = vfpoolId + } else { + req.VFPoolID = uint64(d.Get("vfpool_id").(int)) + } + + vfpoolData, err := c.CloudAPI().VFPool().Get(ctx, req) + if err != nil { + return nil, err + } + + return vfpoolData, nil +} diff --git a/internal/service/cloudapi/vfpool/utility_vfpool_list.go b/internal/service/cloudapi/vfpool/utility_vfpool_list.go new file mode 100644 index 0000000..acc251c --- /dev/null +++ b/internal/service/cloudapi/vfpool/utility_vfpool_list.go @@ -0,0 +1,85 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vfpool + +import ( + "context" + + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vfpool" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityVFpoolListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vfpool.ListVFPool, error) { + c := m.(*controller.ControllerCfg) + req := vfpool.ListRequest{} + + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byId.(int)) + } + if gid, ok := d.GetOk("gid"); ok { + req.GID = uint64(gid.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if description, ok := d.GetOk("description"); ok { + req.Description = description.(string) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if accountAccess, ok := d.GetOk("account_access"); ok { + req.AccountAccess = uint64(accountAccess.(int)) + } + if rgAccess, ok := d.GetOk("rg_access"); ok { + req.RGAccess = uint64(rgAccess.(int)) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + vfpoolList, err := c.CloudAPI().VFPool().List(ctx, req) + if err != nil { + return nil, err + } + + return vfpoolList, nil +} diff --git a/internal/service/cloudapi/vins/data_source_static_route.go b/internal/service/cloudapi/vins/data_source_static_route.go index 2e5bc56..a54b67a 100644 --- a/internal/service/cloudapi/vins/data_source_static_route.go +++ b/internal/service/cloudapi/vins/data_source_static_route.go @@ -1,108 +1,108 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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" - "strconv" - - "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 dataSourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - staticRoute, err := utilityDataStaticRouteCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - d.SetId(strconv.FormatUint(staticRoute.ID, 10)) - flattenStaticRouteData(d, staticRoute) - return nil -} - -func dataSourceStaticRouteSchemaMake() map[string]*schema.Schema { - rets := map[string]*schema.Schema{ - "vins_id": { - Type: schema.TypeInt, - Required: true, - Description: "Unique ID of the ViNS", - }, - "route_id": { - Type: schema.TypeInt, - Required: true, - Description: "Unique ID of the static route", - }, - "compute_ids": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "destination": { - Type: schema.TypeString, - Computed: true, - }, - "gateway": { - Type: schema.TypeString, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "netmask": { - Type: schema.TypeString, - Computed: true, - }, - } - return rets -} - -func DataSourceStaticRoute() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceStaticRouteRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceStaticRouteSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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" + "strconv" + + "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 dataSourceStaticRouteRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + staticRoute, err := utilityDataStaticRouteCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(staticRoute.ID, 10)) + flattenStaticRouteData(d, staticRoute) + return nil +} + +func dataSourceStaticRouteSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "vins_id": { + Type: schema.TypeInt, + Required: true, + Description: "Unique ID of the ViNS", + }, + "route_id": { + Type: schema.TypeInt, + Required: true, + Description: "Unique ID of the static route", + }, + "compute_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "destination": { + Type: schema.TypeString, + Computed: true, + }, + "gateway": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeString, + Computed: true, + }, + } + return rets +} + +func DataSourceStaticRoute() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceStaticRouteRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceStaticRouteSchemaMake(), + } +} diff --git a/internal/service/cloudapi/vins/data_source_static_route_list.go b/internal/service/cloudapi/vins/data_source_static_route_list.go index 1f06efb..f36106d 100644 --- a/internal/service/cloudapi/vins/data_source_static_route_list.go +++ b/internal/service/cloudapi/vins/data_source_static_route_list.go @@ -1,122 +1,122 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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" - - "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 dataSourceStaticRouteListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - staticRouteList, err := utilityStaticRouteListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenStaticRouteList(staticRouteList)) - d.Set("entry_count", staticRouteList.EntryCount) - - return nil -} - -func dataSourceStaticRouteListSchemaMake() map[string]*schema.Schema { - res := map[string]*schema.Schema{ - "vins_id": { - Type: schema.TypeInt, - Required: true, - Description: "ID of VINS", - }, - "items": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "compute_ids": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeInt, - }, - }, - "destination": { - Type: schema.TypeString, - Computed: true, - }, - "gateway": { - Type: schema.TypeString, - Computed: true, - }, - "guid": { - Type: schema.TypeString, - Computed: true, - }, - "netmask": { - Type: schema.TypeString, - Computed: true, - }, - "route_id": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "entry_count": { - Type: schema.TypeInt, - Computed: true, - }, - } - return res -} - -func DataSourceStaticRouteList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceStaticRouteListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceStaticRouteListSchemaMake(), - } -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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" + + "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 dataSourceStaticRouteListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + staticRouteList, err := utilityStaticRouteListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenStaticRouteList(staticRouteList)) + d.Set("entry_count", staticRouteList.EntryCount) + + return nil +} + +func dataSourceStaticRouteListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "vins_id": { + Type: schema.TypeInt, + Required: true, + Description: "ID of VINS", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "destination": { + Type: schema.TypeString, + Computed: true, + }, + "gateway": { + Type: schema.TypeString, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "netmask": { + Type: schema.TypeString, + Computed: true, + }, + "route_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + return res +} + +func DataSourceStaticRouteList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceStaticRouteListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceStaticRouteListSchemaMake(), + } +} diff --git a/internal/service/cloudapi/vins/data_source_vins.go b/internal/service/cloudapi/vins/data_source_vins.go index 0e60992..3664d88 100644 --- a/internal/service/cloudapi/vins/data_source_vins.go +++ b/internal/service/cloudapi/vins/data_source_vins.go @@ -170,6 +170,10 @@ func vnfInterfaceSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "node_id" : { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, @@ -545,7 +549,6 @@ func routesSchemaMake() map[string]*schema.Schema { } } - func gwConfigSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ "default_gw": { diff --git a/internal/service/cloudapi/vins/data_source_vins_list.go b/internal/service/cloudapi/vins/data_source_vins_list.go index 08a7dba..62c16a5 100644 --- a/internal/service/cloudapi/vins/data_source_vins_list.go +++ b/internal/service/cloudapi/vins/data_source_vins_list.go @@ -89,6 +89,11 @@ func dataSourceVinsListSchemaMake() map[string]*schema.Schema { Default: false, Description: "Include deleted computes", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -132,6 +137,14 @@ func dataSourceVinsListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "extnet_id": { + Type: schema.TypeInt, + Computed: true, + }, + "free_ips": { + Type: schema.TypeInt, + Computed: true, + }, "vins_id": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/vins/data_source_vins_list_deleted.go b/internal/service/cloudapi/vins/data_source_vins_list_deleted.go index bfda239..187418e 100644 --- a/internal/service/cloudapi/vins/data_source_vins_list_deleted.go +++ b/internal/service/cloudapi/vins/data_source_vins_list_deleted.go @@ -50,7 +50,7 @@ func dataSourceVinsListDeletedRead(ctx context.Context, d *schema.ResourceData, id := uuid.New() d.SetId(id.String()) - d.Set("items", flattenVinsList(vinsList)) + d.Set("items", flattenVinsListDeleted(vinsList)) d.Set("entry_count", vinsList.EntryCount) return nil @@ -83,6 +83,16 @@ func dataSourceVinsListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by external IP", }, + "vnfdev_id": { + Type: schema.TypeInt, + Optional: true, + Description: "find by VNF Device id", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudapi/vins/flattens.go b/internal/service/cloudapi/vins/flattens.go index 0fb1226..e74792d 100644 --- a/internal/service/cloudapi/vins/flattens.go +++ b/internal/service/cloudapi/vins/flattens.go @@ -100,6 +100,7 @@ func flattenInterfaces(interfaces []vins.ItemVNFInterface) []map[string]interfac "net_id": vnfInterface.NetID, "net_mask": vnfInterface.NetMask, "net_type": vnfInterface.NetType, + "node_id": vnfInterface.NodeID, "pci_slot": vnfInterface.PCISlot, "qos": flattenQOS(vnfInterface.QOS), "target": vnfInterface.Target, @@ -485,6 +486,34 @@ func flattenVinsIpList(ips *vins.ListIPs) []map[string]interface{} { } func flattenVinsList(vl *vins.ListVINS) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vl.Data)) + for _, v := range vl.Data { + temp := map[string]interface{}{ + "account_id": v.AccountID, + "account_name": v.AccountName, + "created_by": v.CreatedBy, + "created_time": v.CreatedTime, + "deleted_by": v.DeletedBy, + "deleted_time": v.DeletedTime, + "external_ip": v.ExternalIP, + "extnet_id": v.ExtnetId, + "free_ips": v.FreeIPs, + "vins_id": v.ID, + "vins_name": v.Name, + "network": v.Network, + "rg_id": v.RGID, + "rg_name": v.RGName, + "status": v.Status, + "updated_by": v.UpdatedBy, + "updated_time": v.UpdatedTime, + "vxlan_id": v.VXLANID, + } + res = append(res, temp) + } + return res +} + +func flattenVinsListDeleted(vl *vins.ListVINS) []map[string]interface{} { res := make([]map[string]interface{}, 0, len(vl.Data)) for _, v := range vl.Data { temp := map[string]interface{}{ diff --git a/internal/service/cloudapi/vins/resource_vins.go b/internal/service/cloudapi/vins/resource_vins.go index aa68e4c..5fc166d 100644 --- a/internal/service/cloudapi/vins/resource_vins.go +++ b/internal/service/cloudapi/vins/resource_vins.go @@ -132,6 +132,13 @@ func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface if preReservationsNum, ok := d.GetOk("pre_reservations_num"); ok { req.PreReservationsNum = uint64(preReservationsNum.(int)) } + if dns, ok := d.GetOk("dns"); ok { + dnsInterface := dns.(*schema.Set).List() + req.DNSList = make([]string, 0, len(dnsInterface)) + for _, item := range dnsInterface { + req.DNSList = append(req.DNSList, item.(string)) + } + } id, err := c.CloudAPI().VINS().CreateInRG(ctx, req) if err != nil { @@ -158,6 +165,13 @@ func resourceVinsCreate(ctx context.Context, d *schema.ResourceData, m interface if preReservationsNum, ok := d.GetOk("pre_reservations_num"); ok { req.PreReservationsNum = uint64(preReservationsNum.(int)) } + if dns, ok := d.GetOk("dns"); ok { + dnsInterface := dns.(*schema.Set).List() + req.DNSList = make([]string, 0, len(dnsInterface)) + for _, item := range dnsInterface { + req.DNSList = append(req.DNSList, item.(string)) + } + } id, err := c.CloudAPI().VINS().CreateInAccount(ctx, req) if err != nil { @@ -388,7 +402,7 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface return diag.Errorf("The resource cannot be updated because it has been destroyed") // return resourceVinsCreate(ctx, d, m) case status.Deleted: - if restore, ok:= d.GetOk("restore"); ok && restore.(bool) { + if restore, ok := d.GetOk("restore"); ok && restore.(bool) { req := vins.RestoreRequest{ VINSID: vinsData.ID, } @@ -623,6 +637,25 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface } } + if d.HasChange("dns") { + // empty "dns" is allowed, it will update vnfs.dhcp.config.dns from current values to empty list + dnsInterface := d.Get("dns").(*schema.Set).List() + dnsList := make([]string, 0, len(dnsInterface)) + for _, item := range dnsInterface { + dnsList = append(dnsList, item.(string)) + } + + req := vins.DNSApplyRequest{ + VINSID: vinsData.ID, + DNSList: dnsList, + } + + _, err := c.CloudAPI().VINS().DNSApply(ctx, req) + if err != nil { + warnings.Add(err) + } + } + if d.HasChange("vnfdev_restart") { if oldRestart, newRestart := d.GetChange("vnfdev_restart"); oldRestart == false && newRestart == true { req := vins.VNFDevRestartRequest{VINSID: vinsData.ID} @@ -835,6 +868,13 @@ func resourceVinsSchemaMake() map[string]*schema.Schema { Optional: true, Default: false, } + rets["dns"] = &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + } rets["vins_id"] = &schema.Schema{ Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudapi/vins/utility_vins_list.go b/internal/service/cloudapi/vins/utility_vins_list.go index 92af2b4..320328b 100644 --- a/internal/service/cloudapi/vins/utility_vins_list.go +++ b/internal/service/cloudapi/vins/utility_vins_list.go @@ -1,86 +1,91 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Kasim Baybikov, - -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" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vins.ListVINS, error) { - c := m.(*controller.ControllerCfg) - req := vins.ListRequest{} - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if account_id, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(account_id.(int)) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if ext_ip, ok := d.GetOk("ext_ip"); ok { - req.ExtIP = ext_ip.(string) - } - - if includeDeleted, ok := d.GetOk("include_deleted"); ok { - req.IncludeDeleted = includeDeleted.(bool) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityVinsListCheckPresence") - vinsList, err := c.CloudAPI().VINS().List(ctx, req) - if err != nil { - return nil, err - } - - return vinsList, nil -} +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/vins" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vins.ListVINS, error) { + c := m.(*controller.ControllerCfg) + req := vins.ListRequest{} + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if account_id, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(account_id.(int)) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if ext_ip, ok := d.GetOk("ext_ip"); ok { + req.ExtIP = ext_ip.(string) + } + + if includeDeleted, ok := d.GetOk("include_deleted"); ok { + req.IncludeDeleted = includeDeleted.(bool) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityVinsListCheckPresence") + vinsList, err := c.CloudAPI().VINS().List(ctx, req) + if err != nil { + return nil, err + } + + return vinsList, nil +} diff --git a/internal/service/cloudapi/vins/utility_vins_list_deleted.go b/internal/service/cloudapi/vins/utility_vins_list_deleted.go index 520cb0a..4946e8f 100644 --- a/internal/service/cloudapi/vins/utility_vins_list_deleted.go +++ b/internal/service/cloudapi/vins/utility_vins_list_deleted.go @@ -52,6 +52,10 @@ func utilityVinsListDeletedCheckPresence(ctx context.Context, d *schema.Resource req.Size = uint64(size.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if by_id, ok := d.GetOk("by_id"); ok { req.ByID = uint64(by_id.(int)) } @@ -71,6 +75,9 @@ func utilityVinsListDeletedCheckPresence(ctx context.Context, d *schema.Resource if ext_ip, ok := d.GetOk("ext_ip"); ok { req.ExtIP = ext_ip.(string) } + if VNFDevId, ok := d.GetOk("vnfdev_id"); ok { + req.VNFDevID = uint64(VNFDevId.(int)) + } log.Debugf("utilityVinsListDeletedCheckPresence") vinsList, err := c.CloudAPI().VINS().ListDeleted(ctx, req) diff --git a/internal/service/cloudbroker/account/data_source_account_audits_list.go b/internal/service/cloudbroker/account/data_source_account_audits_list.go index 510e768..2f5e3c9 100644 --- a/internal/service/cloudbroker/account/data_source_account_audits_list.go +++ b/internal/service/cloudbroker/account/data_source_account_audits_list.go @@ -1,70 +1,70 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -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 dataSourceAccountAuditsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountAuditsList, err := utilityAccountAuditsListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountAuditsList(accountAuditsList)) - - return nil -} - -func DataSourceAccountAuditsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountAuditsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountAuditsListSchemaMake(), - } -} \ No newline at end of file +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +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 dataSourceAccountAuditsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountAuditsList, err := utilityAccountAuditsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountAuditsList(accountAuditsList)) + + return nil +} + +func DataSourceAccountAuditsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountAuditsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountAuditsListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_available_templates_list.go b/internal/service/cloudbroker/account/data_source_account_available_templates_list.go new file mode 100644 index 0000000..888ecf4 --- /dev/null +++ b/internal/service/cloudbroker/account/data_source_account_available_templates_list.go @@ -0,0 +1,71 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +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 dataSourceAccountAvailableTemplatesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountAvailableTemplatesList, err := utilityAccountAvailableTemplatesListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", accountAvailableTemplatesList) + + return nil +} + +func DataSourceAccountAvailableTemplatesList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountAvailableTemplatesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountAvailableTemplatesListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_computes_list.go b/internal/service/cloudbroker/account/data_source_account_computes_list.go index 7aa251c..62b21a6 100644 --- a/internal/service/cloudbroker/account/data_source_account_computes_list.go +++ b/internal/service/cloudbroker/account/data_source_account_computes_list.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -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 dataSourceAccountComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountComputesList, err := utilityAccountComputesListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountComputesList(accountComputesList)) - d.Set("entry_count", accountComputesList.EntryCount) - - return nil -} - -func DataSourceAccountComputesList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountComputesListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountComputesListSchemaMake(), - } -} \ No newline at end of file +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +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 dataSourceAccountComputesListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountComputesList, err := utilityAccountComputesListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountComputesList(accountComputesList)) + d.Set("entry_count", accountComputesList.EntryCount) + + return nil +} + +func DataSourceAccountComputesList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountComputesListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountComputesListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_deleted_list.go b/internal/service/cloudbroker/account/data_source_account_deleted_list.go index 558da1a..87043f4 100644 --- a/internal/service/cloudbroker/account/data_source_account_deleted_list.go +++ b/internal/service/cloudbroker/account/data_source_account_deleted_list.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -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 dataSourceAccountDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountDeletedList, err := utilityAccountDeletedListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenListDeleted(accountDeletedList)) - d.Set("entry_count", accountDeletedList.EntryCount) - - return nil -} - -func DataSourceAccountDeletedList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountDeletedListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountListDeletedSchemaMake(), - } -} \ No newline at end of file +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +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 dataSourceAccountDeletedListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountDeletedList, err := utilityAccountDeletedListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenListDeleted(accountDeletedList)) + d.Set("entry_count", accountDeletedList.EntryCount) + + return nil +} + +func DataSourceAccountDeletedList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountDeletedListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountListDeletedSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_disks_list.go b/internal/service/cloudbroker/account/data_source_account_disks_list.go index 942afa7..09b86f8 100644 --- a/internal/service/cloudbroker/account/data_source_account_disks_list.go +++ b/internal/service/cloudbroker/account/data_source_account_disks_list.go @@ -1,70 +1,70 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -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 dataSourceAccountDisksListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountDisksList, err := utilityAccountDisksListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountDisksList(accountDisksList)) - d.Set("entry_count", accountDisksList.EntryCount) - - return nil -} - -func DataSourceAccountDisksList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountDisksListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountDisksListSchemaMake(), - } -} +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +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 dataSourceAccountDisksListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountDisksList, err := utilityAccountDisksListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountDisksList(accountDisksList)) + d.Set("entry_count", accountDisksList.EntryCount) + + return nil +} + +func DataSourceAccountDisksList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountDisksListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountDisksListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_flipgroups_list.go b/internal/service/cloudbroker/account/data_source_account_flipgroups_list.go index 868ae21..b124cb0 100644 --- a/internal/service/cloudbroker/account/data_source_account_flipgroups_list.go +++ b/internal/service/cloudbroker/account/data_source_account_flipgroups_list.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -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 dataSourceAccountFlipGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountFlipGroupsList(accountFlipGroupsList)) - d.Set("entry_count", accountFlipGroupsList.EntryCount) - - return nil -} - -func DataSourceAccountFlipGroupsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountFlipGroupsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountFlipGroupsListSchemaMake(), - } -} \ No newline at end of file +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +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 dataSourceAccountFlipGroupsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountFlipGroupsList, err := utilityAccountFlipGroupsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountFlipGroupsList(accountFlipGroupsList)) + d.Set("entry_count", accountFlipGroupsList.EntryCount) + + return nil +} + +func DataSourceAccountFlipGroupsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountFlipGroupsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountFlipGroupsListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_list.go b/internal/service/cloudbroker/account/data_source_account_list.go index bc437a8..e506c44 100644 --- a/internal/service/cloudbroker/account/data_source_account_list.go +++ b/internal/service/cloudbroker/account/data_source_account_list.go @@ -1,72 +1,72 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, -Nikita Sorokin, - -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 account - -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 dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountList, err := utilityAccountListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountList(accountList)) - d.Set("entry_count", accountList.EntryCount) - - return nil -} - -func DataSourceAccountList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountListSchemaMake(), - } -} \ No newline at end of file +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Nikita Sorokin, + +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 account + +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 dataSourceAccountListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountList, err := utilityAccountListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountList(accountList)) + d.Set("entry_count", accountList.EntryCount) + + return nil +} + +func DataSourceAccountList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_rg_list.go b/internal/service/cloudbroker/account/data_source_account_rg_list.go index 3d94c4c..a2dfda5 100644 --- a/internal/service/cloudbroker/account/data_source_account_rg_list.go +++ b/internal/service/cloudbroker/account/data_source_account_rg_list.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -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 dataSourceAccountRGListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountRGList, err := utilityAccountRGListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountRGList(accountRGList)) - d.Set("entry_count", accountRGList.EntryCount) - - return nil -} - -func DataSourceAccountRGList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountRGListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountRGListSchemaMake(), - } -} \ No newline at end of file +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +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 dataSourceAccountRGListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountRGList, err := utilityAccountRGListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountRGList(accountRGList)) + d.Set("entry_count", accountRGList.EntryCount) + + return nil +} + +func DataSourceAccountRGList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountRGListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountRGListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/data_source_account_vins_list.go b/internal/service/cloudbroker/account/data_source_account_vins_list.go index 5df1f81..391c79a 100644 --- a/internal/service/cloudbroker/account/data_source_account_vins_list.go +++ b/internal/service/cloudbroker/account/data_source_account_vins_list.go @@ -1,71 +1,71 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -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 dataSourceAccountVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { - accountVinsList, err := utilityAccountVinsListCheckPresence(ctx, d, m) - if err != nil { - d.SetId("") - return diag.FromErr(err) - } - - id := uuid.New() - d.SetId(id.String()) - d.Set("items", flattenAccountVinsList(accountVinsList)) - d.Set("entry_count", accountVinsList.EntryCount) - - return nil -} - -func DataSourceAccountVinsList() *schema.Resource { - return &schema.Resource{ - SchemaVersion: 1, - - ReadContext: dataSourceAccountVinsListRead, - - Timeouts: &schema.ResourceTimeout{ - Read: &constants.Timeout30s, - Default: &constants.Timeout60s, - }, - - Schema: dataSourceAccountVinsListSchemaMake(), - } -} \ No newline at end of file +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +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 dataSourceAccountVinsListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + accountVinsList, err := utilityAccountVinsListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenAccountVinsList(accountVinsList)) + d.Set("entry_count", accountVinsList.EntryCount) + + return nil +} + +func DataSourceAccountVinsList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceAccountVinsListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceAccountVinsListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/account/flattens.go b/internal/service/cloudbroker/account/flattens.go index 73da951..bd5eb99 100644 --- a/internal/service/cloudbroker/account/flattens.go +++ b/internal/service/cloudbroker/account/flattens.go @@ -12,6 +12,7 @@ func flattenResourceAccount(d *schema.ResourceData, acc *account.RecordAccount) d.Set("acl", flattenAccAcl(acc.ACL)) d.Set("company", acc.Company) d.Set("companyurl", acc.CompanyURL) + d.Set("compute_features", acc.ComputeFeatures) d.Set("cpu_allocation_parameter", acc.CPUAllocationParameter) d.Set("cpu_allocation_ratio", acc.CPUAllocationRatio) d.Set("created_by", acc.CreatedBy) @@ -39,6 +40,7 @@ func flattenDataAccount(d *schema.ResourceData, acc *account.RecordAccount) { d.Set("acl", flattenAccAcl(acc.ACL)) d.Set("company", acc.Company) d.Set("companyurl", acc.CompanyURL) + d.Set("compute_features", acc.ComputeFeatures) d.Set("cpu_allocation_parameter", acc.CPUAllocationParameter) d.Set("cpu_allocation_ratio", acc.CPUAllocationRatio) d.Set("created_by", acc.CreatedBy) @@ -187,7 +189,7 @@ func flattenRgAcl(rgAcls []account.ACL) []map[string]interface{} { } func flattenListDeleted(al *account.ListAccounts) []map[string]interface{} { - res := make([]map[string]interface{}, 0, len (al.Data)) + res := make([]map[string]interface{}, 0, len(al.Data)) for _, acc := range al.Data { temp := map[string]interface{}{ "dc_location": acc.DCLocation, @@ -196,6 +198,7 @@ func flattenListDeleted(al *account.ListAccounts) []map[string]interface{} { "acl": flattenRgAcl(acc.ACL), "company": acc.Company, "companyurl": acc.CompanyURL, + "compute_features": acc.ComputeFeatures, "cpu_allocation_parameter": acc.CPUAllocationParameter, "cpu_allocation_ratio": acc.CPUAllocationRatio, "created_by": acc.CreatedBy, @@ -231,6 +234,7 @@ func flattenAccountList(al *account.ListAccounts) []map[string]interface{} { "acl": flattenRgAcl(acc.ACL), "company": acc.Company, "companyurl": acc.CompanyURL, + "compute_features": acc.ComputeFeatures, "cpu_allocation_parameter": acc.CPUAllocationParameter, "cpu_allocation_ratio": acc.CPUAllocationRatio, "created_by": acc.CreatedBy, @@ -361,6 +365,8 @@ func flattenAccountVinsList(avl *account.ListVINS) []map[string]interface{} { "deleted_by": av.DeletedBy, "deleted_time": av.DeletedTime, "external_ip": av.ExternalIP, + "extnet_id": av.ExtnetId, + "free_ips": av.FreeIPs, "vin_id": av.ID, "vin_name": av.Name, "network": av.Network, diff --git a/internal/service/cloudbroker/account/resource_account.go b/internal/service/cloudbroker/account/resource_account.go index 18ab45d..50ee97a 100644 --- a/internal/service/cloudbroker/account/resource_account.go +++ b/internal/service/cloudbroker/account/resource_account.go @@ -123,6 +123,18 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf } } + if compFeaturesInterface, ok := d.GetOk("compute_features"); ok { + compFeaturesInterfaces := compFeaturesInterface.(*schema.Set).List() + + compFeatures := make([]string, 0, len(compFeaturesInterfaces)) + + for _, item := range compFeaturesInterfaces { + compFeatures = append(compFeatures, item.(string)) + } + + req.ComputeFeatures = compFeatures + } + accountId, err := c.CloudBroker().Account().Create(ctx, req) if err != nil { return diag.FromErr(err) @@ -191,6 +203,12 @@ func resourceAccountCreate(ctx context.Context, d *schema.ResourceData, m interf } } + if _, ok := d.GetOk("available_templates"); ok { + if err := utilityAccountAvailiableTemplatesUpdate(ctx, d, m, true); err != nil { + w.Add(err) + } + } + return append(resourceAccountRead(ctx, d, m), w.Get()...) } @@ -235,6 +253,7 @@ func resourceAccountDelete(ctx context.Context, d *schema.ResourceData, m interf func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceAccountUpdate") + c := m.(*controller.ControllerCfg) acc, err := utilityAccountCheckPresence(ctx, d, m) @@ -313,6 +332,18 @@ func resourceAccountUpdate(ctx context.Context, d *schema.ResourceData, m interf } } + if d.HasChange("available_templates") { + if err := utilityAccountAvailiableTemplatesUpdate(ctx, d, m, false); err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("compute_features") { + if err := utilityAccountComputeFeaturesUpdate(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + return resourceAccountRead(ctx, d, m) } diff --git a/internal/service/cloudbroker/account/schema.go b/internal/service/cloudbroker/account/schema.go index 2c359a5..8ac0fc6 100644 --- a/internal/service/cloudbroker/account/schema.go +++ b/internal/service/cloudbroker/account/schema.go @@ -1,6 +1,9 @@ package account -import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) func resourceAccountSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ @@ -66,6 +69,14 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { Computed: true, Description: "set cpu allocation ratio", }, + "available_templates": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "Share images with account", + }, "restore": { Type: schema.TypeBool, Optional: true, @@ -127,6 +138,14 @@ func resourceAccountSchemaMake() map[string]*schema.Schema { }, }, }, + "compute_features": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{"hugepages", "numa", "cpupin", "vfnic"}, true), + }, + }, "account_id": { Type: schema.TypeInt, Optional: true, @@ -331,6 +350,11 @@ func dataSourceAccountComputesListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by extnet ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -455,6 +479,11 @@ func dataSourceAccountListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by ACL", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -525,6 +554,13 @@ func dataSourceAccountListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "cpu_allocation_parameter": { Type: schema.TypeString, Computed: true, @@ -679,6 +715,11 @@ func dataSourceAccountDisksListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by disk type", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -771,6 +812,11 @@ func dataSourceAccountFlipGroupsListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by flipgroup ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1071,6 +1117,11 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1141,6 +1192,13 @@ func dataSourceAccountListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "cpu_allocation_parameter": { Type: schema.TypeString, Computed: true, @@ -1418,6 +1476,11 @@ func dataSourceAccountRGListSchemaMake() map[string]*schema.Schema { Required: true, Description: "ID of the account", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1726,6 +1789,11 @@ func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by external IP", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1774,6 +1842,14 @@ func dataSourceAccountVinsListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "extnet_id": { + Type: schema.TypeInt, + Computed: true, + }, + "free_ips": { + Type: schema.TypeInt, + Computed: true, + }, "vin_id": { Type: schema.TypeInt, Computed: true, @@ -1875,6 +1951,13 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "cpu_allocation_parameter": { Type: schema.TypeString, Computed: true, @@ -1990,3 +2073,20 @@ func dataSourceAccountSchemaMake() map[string]*schema.Schema { }, } } + +func dataSourceAccountAvailableTemplatesListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Required: true, + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + } + return res +} diff --git a/internal/service/cloudbroker/account/utility_account.go b/internal/service/cloudbroker/account/utility_account.go index 4737d6d..b9c2e55 100644 --- a/internal/service/cloudbroker/account/utility_account.go +++ b/internal/service/cloudbroker/account/utility_account.go @@ -33,12 +33,14 @@ package account import ( "context" + "fmt" "strconv" "strings" log "github.com/sirupsen/logrus" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -291,6 +293,111 @@ func utilityAccountUpdate(ctx context.Context, d *schema.ResourceData, m interfa return nil } +func utilityAccountAvailiableTemplatesUpdate(ctx context.Context, d *schema.ResourceData, m interface{}, afterCreate bool) error { + c := m.(*controller.ControllerCfg) + + accountId, _ := strconv.ParseUint(d.Id(), 10, 64) + + if afterCreate { + addedAT := d.Get("available_templates").(*schema.Set).List() + imageIds := make([]uint64, 0, len(addedAT)) + + for _, imageId := range addedAT { + imageIds = append(imageIds, uint64(imageId.(int))) + } + + if err := ic.ExistImages(ctx, imageIds, c); err != nil { + return fmt.Errorf("can not grant access for available templates: %w", err) + } + + req := account.GrantAccessTemplatesRequest{ + AccountID: accountId, + ImageIDs: imageIds, + } + + _, err := c.CloudBroker().Account().GrantAccessTemplates(ctx, req) + if err != nil { + return err + } + + return nil + } + + oldSet, newSet := d.GetChange("available_templates") + + revokeAT := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List() + if len(revokeAT) > 0 { + imageIds := make([]uint64, 0, len(revokeAT)) + + for _, imageId := range revokeAT { + imageIds = append(imageIds, uint64(imageId.(int))) + } + + if err := ic.ExistImages(ctx, imageIds, c); err != nil { + return fmt.Errorf("can not revoke access for available templates: %w", err) + } + + req := account.RevokeAccessTemplatesRequest{ + AccountID: accountId, + ImageIDs: imageIds, + } + + _, err := c.CloudBroker().Account().RevokeAccessTemplates(ctx, req) + if err != nil { + return err + } + } + + addedAT := (newSet.(*schema.Set).Difference(oldSet.(*schema.Set))).List() + if len(addedAT) > 0 { + imageIds := make([]uint64, 0, len(addedAT)) + + for _, imageId := range addedAT { + imageIds = append(imageIds, uint64(imageId.(int))) + } + + if err := ic.ExistImages(ctx, imageIds, c); err != nil { + return fmt.Errorf("can not grant access for available templates: %w", err) + } + + req := account.GrantAccessTemplatesRequest{ + AccountID: accountId, + ImageIDs: imageIds, + } + + _, err := c.CloudBroker().Account().GrantAccessTemplates(ctx, req) + if err != nil { + return err + } + } + + return nil +} + +func utilityAccountComputeFeaturesUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) error { + c := m.(*controller.ControllerCfg) + + accountId, _ := strconv.ParseUint(d.Id(), 10, 64) + compFeaturesInterface := d.Get("compute_features").(*schema.Set).List() + + compFeatures := make([]string, 0, len(compFeaturesInterface)) + for _, item := range compFeaturesInterface { + compFeatures = append(compFeatures, item.(string)) + } + + req := account.UpdateComputeFeaturesRequest{ + AccountID: accountId, + ComputeFeatures: compFeatures, + } + + _, err := c.CloudBroker().Account().UpdateComputeFeatures(ctx, req) + if err != nil { + return err + } + + return nil +} + func isContainsUser(els []interface{}, el interface{}) bool { for _, elOld := range els { elOldConv := elOld.(map[string]interface{}) @@ -313,4 +420,4 @@ func isChangedUser(els []interface{}, el interface{}) bool { } } return false -} \ No newline at end of file +} diff --git a/internal/service/cloudbroker/account/utility_account_available_templates_list.go b/internal/service/cloudbroker/account/utility_account_available_templates_list.go new file mode 100644 index 0000000..27d3b62 --- /dev/null +++ b/internal/service/cloudbroker/account/utility_account_available_templates_list.go @@ -0,0 +1,61 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountAvailableTemplatesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) ([]uint64, error) { + c := m.(*controller.ControllerCfg) + + id := uint64(d.Get("account_id").(int)) + + req := account.ListAvailableTemplatesRequest{ + AccountID: id, + } + + log.Debugf("utilityAccountAvailableTemplatesListCheckPresence: load list") + accountAvailableTemplatesList, err := c.CloudBroker().Account().ListAvailableTemplates(ctx, req) + if err != nil { + return nil, err + } + + return accountAvailableTemplatesList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_computes_list.go b/internal/service/cloudbroker/account/utility_account_computes_list.go index 12b7cd7..49b10fc 100644 --- a/internal/service/cloudbroker/account/utility_account_computes_list.go +++ b/internal/service/cloudbroker/account/utility_account_computes_list.go @@ -1,97 +1,101 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListComputes, error) { - c := m.(*controller.ControllerCfg) - req := account.ListComputesRequest{ - AccountID: uint64(d.Get("account_id").(int)), - } - - if compute_id, ok := d.GetOk("compute_id"); ok { - req.ComputeID = uint64(compute_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if rg_name, ok := d.GetOk("rg_name"); ok { - req.RGName = rg_name.(string) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if tech_status, ok := d.GetOk("tech_status"); ok { - req.TechStatus = tech_status.(string) - } - - if ip_address, ok := d.GetOk("ip_address"); ok { - req.IPAddress = ip_address.(string) - } - - if extnet_name, ok := d.GetOk("extnet_name"); ok { - req.ExtNetName = extnet_name.(string) - } - - if extnet_id, ok := d.GetOk("extnet_id"); ok { - req.ExtNetID = uint64(extnet_id.(int)) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityAccountComputesListCheckPresence: load account list") - accountComputesList, err := c.CloudBroker().Account().ListComputes(ctx, req) - if err != nil { - return nil, err - } - - return accountComputesList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountComputesListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListComputes, error) { + c := m.(*controller.ControllerCfg) + req := account.ListComputesRequest{ + AccountID: uint64(d.Get("account_id").(int)), + } + + if compute_id, ok := d.GetOk("compute_id"); ok { + req.ComputeID = uint64(compute_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if rg_name, ok := d.GetOk("rg_name"); ok { + req.RGName = rg_name.(string) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if tech_status, ok := d.GetOk("tech_status"); ok { + req.TechStatus = tech_status.(string) + } + + if ip_address, ok := d.GetOk("ip_address"); ok { + req.IPAddress = ip_address.(string) + } + + if extnet_name, ok := d.GetOk("extnet_name"); ok { + req.ExtNetName = extnet_name.(string) + } + + if extnet_id, ok := d.GetOk("extnet_id"); ok { + req.ExtNetID = uint64(extnet_id.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityAccountComputesListCheckPresence: load account list") + accountComputesList, err := c.CloudBroker().Account().ListComputes(ctx, req) + if err != nil { + return nil, err + } + + return accountComputesList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_deleted_list.go b/internal/service/cloudbroker/account/utility_account_deleted_list.go index 500c275..2a4702b 100644 --- a/internal/service/cloudbroker/account/utility_account_deleted_list.go +++ b/internal/service/cloudbroker/account/utility_account_deleted_list.go @@ -1,75 +1,79 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { - c := m.(*controller.ControllerCfg) - req := account.ListDeletedRequest{} - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if acl, ok := d.GetOk("acl"); ok { - req.ACL = acl.(string) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - log.Debugf("utilityAccountDeletedListCheckPresence: load") - accountDeletedList, err := c.CloudBroker().Account().ListDeleted(ctx, req) - if err != nil { - return nil, err - } - - return accountDeletedList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountDeletedListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { + c := m.(*controller.ControllerCfg) + req := account.ListDeletedRequest{} + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if acl, ok := d.GetOk("acl"); ok { + req.ACL = acl.(string) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + log.Debugf("utilityAccountDeletedListCheckPresence: load") + accountDeletedList, err := c.CloudBroker().Account().ListDeleted(ctx, req) + if err != nil { + return nil, err + } + + return accountDeletedList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_disks_list.go b/internal/service/cloudbroker/account/utility_account_disks_list.go index c28b083..a74deae 100644 --- a/internal/service/cloudbroker/account/utility_account_disks_list.go +++ b/internal/service/cloudbroker/account/utility_account_disks_list.go @@ -1,81 +1,85 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListDisks, error) { - c := m.(*controller.ControllerCfg) - req := account.ListDisksRequest{ - AccountID: uint64(d.Get("account_id").(int)), - } - - if disk_id, ok := d.GetOk("disk_id"); ok { - req.DiskID = uint64(disk_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if disk_max_size, ok := d.GetOk("disk_max_size"); ok { - req.DiskMaxSize = uint64(disk_max_size.(int)) - } - - if typeVal, ok := d.GetOk("type"); ok { - req.Type = typeVal.(string) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityAccountDisksListCheckPresence: load account list") - accountDisksList, err := c.CloudBroker().Account().ListDisks(ctx, req) - if err != nil { - return nil, err - } - - return accountDisksList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountDisksListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListDisks, error) { + c := m.(*controller.ControllerCfg) + req := account.ListDisksRequest{ + AccountID: uint64(d.Get("account_id").(int)), + } + + if disk_id, ok := d.GetOk("disk_id"); ok { + req.DiskID = uint64(disk_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if disk_max_size, ok := d.GetOk("disk_max_size"); ok { + req.DiskMaxSize = uint64(disk_max_size.(int)) + } + + if typeVal, ok := d.GetOk("type"); ok { + req.Type = typeVal.(string) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityAccountDisksListCheckPresence: load account list") + accountDisksList, err := c.CloudBroker().Account().ListDisks(ctx, req) + if err != nil { + return nil, err + } + + return accountDisksList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_flip_groups.go b/internal/service/cloudbroker/account/utility_account_flip_groups.go index c3f9d04..b2dd4e1 100644 --- a/internal/service/cloudbroker/account/utility_account_flip_groups.go +++ b/internal/service/cloudbroker/account/utility_account_flip_groups.go @@ -1,89 +1,93 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountFlipGroupsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListFLIPGroups, error) { - c := m.(*controller.ControllerCfg) - req := account.ListFLIPGroupsRequest{ - AccountID: uint64(d.Get("account_id").(int)), - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if vins_id, ok := d.GetOk("vins_id"); ok { - req.VINSID = uint64(vins_id.(int)) - } - - if vins_name, ok := d.GetOk("vins_name"); ok { - req.VINSName = vins_name.(string) - } - - if extnet_id, ok := d.GetOk("extnet_id"); ok { - req.ExtNetID = uint64(extnet_id.(int)) - } - - if by_ip, ok := d.GetOk("by_ip"); ok { - req.ByIP = by_ip.(string) - } - - if flipgroup_id, ok := d.GetOk("flipgroup_id"); ok { - req.FLIPGroupID = uint64(flipgroup_id.(int)) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityAccountFlipGroupsListCheckPresence") - accountFlipGroupsList, err := c.CloudBroker().Account().ListFLIPGroups(ctx, req) - if err != nil { - return nil, err - } - - return accountFlipGroupsList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountFlipGroupsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListFLIPGroups, error) { + c := m.(*controller.ControllerCfg) + req := account.ListFLIPGroupsRequest{ + AccountID: uint64(d.Get("account_id").(int)), + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if vins_id, ok := d.GetOk("vins_id"); ok { + req.VINSID = uint64(vins_id.(int)) + } + + if vins_name, ok := d.GetOk("vins_name"); ok { + req.VINSName = vins_name.(string) + } + + if extnet_id, ok := d.GetOk("extnet_id"); ok { + req.ExtNetID = uint64(extnet_id.(int)) + } + + if by_ip, ok := d.GetOk("by_ip"); ok { + req.ByIP = by_ip.(string) + } + + if flipgroup_id, ok := d.GetOk("flipgroup_id"); ok { + req.FLIPGroupID = uint64(flipgroup_id.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityAccountFlipGroupsListCheckPresence") + accountFlipGroupsList, err := c.CloudBroker().Account().ListFLIPGroups(ctx, req) + if err != nil { + return nil, err + } + + return accountFlipGroupsList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_list.go b/internal/service/cloudbroker/account/utility_account_list.go index ab26381..1811a34 100644 --- a/internal/service/cloudbroker/account/utility_account_list.go +++ b/internal/service/cloudbroker/account/utility_account_list.go @@ -1,78 +1,82 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { - c := m.(*controller.ControllerCfg) - req := account.ListRequest{} - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if acl, ok := d.GetOk("acl"); ok { - req.ACL = acl.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - log.Debugf("utilityAccountListCheckPresence: load account list") - accountList, err := c.CloudBroker().Account().List(ctx, req) - if err != nil { - return nil, err - } - - return accountList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListAccounts, error) { + c := m.(*controller.ControllerCfg) + req := account.ListRequest{} + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if acl, ok := d.GetOk("acl"); ok { + req.ACL = acl.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + log.Debugf("utilityAccountListCheckPresence: load account list") + accountList, err := c.CloudBroker().Account().List(ctx, req) + if err != nil { + return nil, err + } + + return accountList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_rg_list.go b/internal/service/cloudbroker/account/utility_account_rg_list.go index da55500..b58cd98 100644 --- a/internal/service/cloudbroker/account/utility_account_rg_list.go +++ b/internal/service/cloudbroker/account/utility_account_rg_list.go @@ -1,85 +1,89 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListRG, error) { - c := m.(*controller.ControllerCfg) - req := account.ListRGRequest{ - AccountID: uint64(d.Get("account_id").(int)), - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if vins_id, ok := d.GetOk("vins_id"); ok { - req.VINSID = uint64(vins_id.(int)) - } - - if vm_id, ok := d.GetOk("vm_id"); ok { - req.VMID = uint64(vm_id.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - - log.Debugf("utilityAccountRGListCheckPresence: load account list") - accountRGList, err := c.CloudBroker().Account().ListRG(ctx, req) - if err != nil { - return nil, err - } - - return accountRGList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountRGListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListRG, error) { + c := m.(*controller.ControllerCfg) + req := account.ListRGRequest{ + AccountID: uint64(d.Get("account_id").(int)), + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if vins_id, ok := d.GetOk("vins_id"); ok { + req.VINSID = uint64(vins_id.(int)) + } + + if vm_id, ok := d.GetOk("vm_id"); ok { + req.VMID = uint64(vm_id.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + + log.Debugf("utilityAccountRGListCheckPresence: load account list") + accountRGList, err := c.CloudBroker().Account().ListRG(ctx, req) + if err != nil { + return nil, err + } + + return accountRGList, nil +} diff --git a/internal/service/cloudbroker/account/utility_account_vins_list.go b/internal/service/cloudbroker/account/utility_account_vins_list.go index a995725..8781f12 100644 --- a/internal/service/cloudbroker/account/utility_account_vins_list.go +++ b/internal/service/cloudbroker/account/utility_account_vins_list.go @@ -1,81 +1,85 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 account - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListVINS, error) { - c := m.(*controller.ControllerCfg) - req := account.ListVINSRequest{ - AccountID: uint64(d.Get("account_id").(int)), - } - - if vins_id, ok := d.GetOk("vins_id"); ok { - req.VINSID = uint64(vins_id.(int)) - } - - if rg_id, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rg_id.(int)) - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - - if ext_ip, ok := d.GetOk("ext_ip"); ok { - req.ExtIP = ext_ip.(string) - } - - log.Debugf("utilityAccountVinsListCheckPresence: load account list") - accountVinsList, err := c.CloudBroker().Account().ListVINS(ctx, req) - if err != nil { - return nil, err - } - - return accountVinsList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 account + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityAccountVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*account.ListVINS, error) { + c := m.(*controller.ControllerCfg) + req := account.ListVINSRequest{ + AccountID: uint64(d.Get("account_id").(int)), + } + + if vins_id, ok := d.GetOk("vins_id"); ok { + req.VINSID = uint64(vins_id.(int)) + } + + if rg_id, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rg_id.(int)) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + + if ext_ip, ok := d.GetOk("ext_ip"); ok { + req.ExtIP = ext_ip.(string) + } + + log.Debugf("utilityAccountVinsListCheckPresence: load account list") + accountVinsList, err := c.CloudBroker().Account().ListVINS(ctx, req) + if err != nil { + return nil, err + } + + return accountVinsList, nil +} diff --git a/internal/service/cloudbroker/audit/flattens.go b/internal/service/cloudbroker/audit/flattens.go index e6c16e7..85164fd 100644 --- a/internal/service/cloudbroker/audit/flattens.go +++ b/internal/service/cloudbroker/audit/flattens.go @@ -78,6 +78,7 @@ func flattenLinkedJobs(ljl *audit.ListLinkedJobs) []map[string]interface{} { for _, item := range linkedJobs { temp := map[string]interface{}{ "cmd": item.CMD, + "guid": item.GUID, "nid": item.NID, "state": item.State, "time_create": item.TimeCreate, diff --git a/internal/service/cloudbroker/audit/schema.go b/internal/service/cloudbroker/audit/schema.go index a5db461..49a4c51 100644 --- a/internal/service/cloudbroker/audit/schema.go +++ b/internal/service/cloudbroker/audit/schema.go @@ -87,10 +87,20 @@ func dataSourceAuditListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "find by api endpoint (Mongo RegExp supported)", }, - "status_code": { + "min_status_code": { + Type: schema.TypeInt, + Optional: true, + Description: "find by HTTP min status code", + }, + "max_status_code": { Type: schema.TypeInt, Optional: true, - Description: "find by HTTP status code", + Description: "find by HTTP max status code", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", }, "page": { Type: schema.TypeInt, @@ -161,6 +171,11 @@ func dataSourceLinkedJobsSchemaMake() map[string]*schema.Schema { Computed: true, Description: "cmd", }, + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "guid", + }, "nid": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudbroker/audit/utility_audit_list.go b/internal/service/cloudbroker/audit/utility_audit_list.go index 6089351..6170b37 100644 --- a/internal/service/cloudbroker/audit/utility_audit_list.go +++ b/internal/service/cloudbroker/audit/utility_audit_list.go @@ -58,8 +58,14 @@ func utilityAuditListCheckPresence(ctx context.Context, d *schema.ResourceData, if call, ok := d.GetOk("call"); ok { req.Call = call.(string) } - if statusCode, ok := d.GetOk("status_code"); ok { - req.StatusCode = uint64(statusCode.(int)) + if minStatusCode, ok := d.GetOk("min_status_code"); ok { + req.MinStatusCode = uint64(minStatusCode.(int)) + } + if maxStatusCode, ok := d.GetOk("max_status_code"); ok { + req.MaxStatusCode = uint64(maxStatusCode.(int)) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) } if Page, ok := d.GetOk("page"); ok { req.Page = uint64(Page.(int)) diff --git a/internal/service/cloudbroker/disks/data_source_disk_replication.go b/internal/service/cloudbroker/disks/data_source_disk_replication.go new file mode 100644 index 0000000..4fdab02 --- /dev/null +++ b/internal/service/cloudbroker/disks/data_source_disk_replication.go @@ -0,0 +1,90 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 disks + +import ( + "context" + + "github.com/google/uuid" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceDiskReplicationRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("dataSourceDiskReplicationRead: called for disk with ID: %s", d.Id()) + c := m.(*controller.ControllerCfg) + + req := disks.ReplicationStatusRequest{ + DiskID: uint64(d.Get("disk_id").(int)), + } + + status, err := c.CloudAPI().Disks().ReplicationStatus(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + + disk, err := utilityDiskReplicaCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + flattenDiskReplica(d, disk, status) + + log.Debugf("dataSourceDiskReplicationRead: read complete for disk with ID: %s", d.Id()) + + return nil +} + +func DataSourceDiskReplication() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceDiskReplicationRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceDiskReplicationSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/disks/flattens.go b/internal/service/cloudbroker/disks/flattens.go index 6be53b3..8b62231 100644 --- a/internal/service/cloudbroker/disks/flattens.go +++ b/internal/service/cloudbroker/disks/flattens.go @@ -10,7 +10,6 @@ import ( func flattenDisk(d *schema.ResourceData, disk *disks.RecordDisk) { diskAcl, _ := json.Marshal(disk.ACL) - d.Set("account_id", disk.AccountID) d.Set("account_name", disk.AccountName) d.Set("acl", string(diskAcl)) @@ -41,6 +40,57 @@ func flattenDisk(d *schema.ResourceData, disk *disks.RecordDisk) { d.Set("purge_attempts", disk.PurgeAttempts) d.Set("present_to", disk.PresentTo) d.Set("purge_time", disk.PurgeTime) + d.Set("replication", flattenDiskReplication(disk.Replication)) + d.Set("reality_device_number", disk.RealityDeviceNumber) + d.Set("reference_id", disk.ReferenceID) + d.Set("res_id", disk.ResID) + d.Set("res_name", disk.ResName) + d.Set("role", disk.Role) + d.Set("sep_id", disk.SEPID) + d.Set("sep_type", disk.SEPType) + d.Set("shareable", disk.Shareable) + d.Set("size_max", disk.SizeMax) + d.Set("size_used", disk.SizeUsed) + d.Set("snapshots", flattendDiskSnapshotList(disk.Snapshots)) + d.Set("status", disk.Status) + d.Set("tech_status", disk.TechStatus) + d.Set("type", disk.Type) + d.Set("vmid", disk.VMID) +} + +func flattenDiskReplica(d *schema.ResourceData, disk *disks.RecordDisk, statusReplication string) { + diskAcl, _ := json.Marshal(disk.ACL) + d.Set("account_id", disk.AccountID) + d.Set("account_name", disk.AccountName) + d.Set("acl", string(diskAcl)) + d.Set("boot_partition", disk.BootPartition) + d.Set("computes", flattenDiskComputes(disk.Computes)) + d.Set("created_time", disk.CreatedTime) + d.Set("deleted_time", disk.DeletedTime) + d.Set("desc", disk.Description) + d.Set("destruction_time", disk.DestructionTime) + d.Set("devicename", disk.DeviceName) + d.Set("disk_path", disk.DiskPath) + d.Set("gid", disk.GID) + d.Set("guid", disk.GUID) + d.Set("replica_disk_id", disk.ID) + d.Set("image_id", disk.ImageID) + d.Set("images", disk.Images) + d.Set("iotune", flattenIOTune(disk.IOTune)) + d.Set("iqn", disk.IQN) + d.Set("login", disk.Login) + d.Set("milestones", disk.Milestones) + d.Set("disk_name", disk.Name) + d.Set("order", disk.Order) + d.Set("params", disk.Params) + d.Set("parent_id", disk.ParentID) + d.Set("passwd", disk.Password) + d.Set("pci_slot", disk.PCISlot) + d.Set("pool", disk.Pool) + d.Set("purge_attempts", disk.PurgeAttempts) + d.Set("present_to", disk.PresentTo) + d.Set("purge_time", disk.PurgeTime) + d.Set("replication", flattenDiskReplication(disk.Replication)) d.Set("reality_device_number", disk.RealityDeviceNumber) d.Set("reference_id", disk.ReferenceID) d.Set("res_id", disk.ResID) @@ -53,11 +103,26 @@ func flattenDisk(d *schema.ResourceData, disk *disks.RecordDisk) { d.Set("size_used", disk.SizeUsed) d.Set("snapshots", flattendDiskSnapshotList(disk.Snapshots)) d.Set("status", disk.Status) + d.Set("status_replication", statusReplication) d.Set("tech_status", disk.TechStatus) d.Set("type", disk.Type) d.Set("vmid", disk.VMID) } +func flattenDiskReplication(rep disks.ItemReplication) []map[string]interface{} { + res := []map[string]interface{}{ + { + "disk_id": rep.DiskID, + "pool_id": rep.PoolID, + "role": rep.Role, + "self_volume_id": rep.SelfVolumeID, + "storage_id": rep.StorageID, + "volume_id": rep.VolumeID, + }, + } + return res +} + func flattenDiskSnapshot(d *schema.ResourceData, snapshot disks.ItemSnapshot) { d.Set("timestamp", snapshot.Timestamp) d.Set("guid", snapshot.GUID) @@ -137,6 +202,7 @@ func flattenDiskList(dl *disks.ListDisks) []map[string]interface{} { "pool": disk.Pool, "purge_attempts": disk.PurgeAttempts, "purge_time": disk.PurgeTime, + "replication": flattenDiskReplication(disk.Replication), "reality_device_number": disk.RealityDeviceNumber, "reference_id": disk.ReferenceID, "res_id": disk.ResID, diff --git a/internal/service/cloudbroker/disks/resource_disk.go b/internal/service/cloudbroker/disks/resource_disk.go index d494ee5..12111fd 100644 --- a/internal/service/cloudbroker/disks/resource_disk.go +++ b/internal/service/cloudbroker/disks/resource_disk.go @@ -33,6 +33,7 @@ package disks import ( "context" + "errors" "fmt" "strconv" @@ -94,6 +95,14 @@ func resourceDiskCreate(ctx context.Context, d *schema.ResourceData, m interface w := dc.Warnings{} + if _, ok := d.GetOk("node_ids"); ok { + log.Debugf("resourceDiskCreate: present for disk %d", d.Get("disk_id")) + if err := resourceDiskChangeNodes(ctx, d, m, true); err != nil { + w.Add(err) + } + log.Debugf("resourceDiskCreate: finished present for disk %d", d.Get("disk_id")) + } + if _, ok := d.GetOk("iotune"); ok { if err := resourceDiskChangeIotune(ctx, d, m); err != nil { w.Add(err) @@ -208,26 +217,34 @@ func resourceDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface log.Debugf("resourceDiskUpdate: resizing disk ID %s - %d GB -> %d GB", d.Id(), oldSize.(int), newSize.(int)) if err := resourceDiskChangeSize(ctx, d, m); err != nil { - w.Add(err) + return diag.FromErr(err) } } if d.HasChange("disk_name") { if err := resourceDiskChangeDiskName(ctx, d, m); err != nil { - w.Add(err) + return diag.FromErr(err) } } if d.HasChange("iotune") { if err := resourceDiskChangeIotune(ctx, d, m); err != nil { - w.Add(err) + return diag.FromErr(err) } } if d.HasChange("shareable") { if err := resourceDiskChangeShareable(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("node_ids") { + log.Debugf("resourceDiskUpdate: present for disk %d", d.Get("disk_id")) + if err := resourceDiskChangeNodes(ctx, d, m, false); err != nil { w.Add(err) } + log.Debugf("resourceDiskUpdate: finished present for disk %d", d.Get("disk_id")) } return append(w.Get(), resourceDiskRead(ctx, d, m)...) @@ -347,6 +364,60 @@ func resourceDiskChangeSize(ctx context.Context, d *schema.ResourceData, m inter return err } +func resourceDiskChangeNodes(ctx context.Context, d *schema.ResourceData, m interface{}, afterCreate bool) error { + c := m.(*controller.ControllerCfg) + diskID := uint64(d.Get("disk_id").(int)) + presentIDs := make([]interface{}, 0) + var errs error + var oldNodes, newNodes interface{} + + if afterCreate { + nodeIDs := d.Get("node_ids").(*schema.Set).List() + presentIDs = nodeIDs + } else { + oldNodes, newNodes = d.GetChange("node_ids") + nodeIDs := (newNodes.(*schema.Set).Difference(oldNodes.(*schema.Set))).List() + presentIDs = nodeIDs + } + + for _, presentID := range presentIDs { + nodeID := uint64(presentID.(int)) + + req := disks.PresentRequest{ + DiskID: diskID, + NodeID: nodeID, + } + + _, err := c.CloudBroker().Disks().Present(ctx, req) + if err != nil { + errs = errors.Join(err) + } + } + + if afterCreate { + return errs + } + + depresentIDs := (oldNodes.(*schema.Set).Difference(newNodes.(*schema.Set))).List() + if len(depresentIDs) > 0 { + for _, depresentID := range depresentIDs { + nodeID := uint64(depresentID.(int)) + + req := disks.DepresentRequest{ + DiskID: diskID, + NodeID: nodeID, + } + + _, err := c.CloudBroker().Disks().Depresent(ctx, req) + if err != nil { + errs = errors.Join(err) + } + } + } + + return errs +} + func ResourceDisk() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, diff --git a/internal/service/cloudbroker/disks/resource_disk_replication.go b/internal/service/cloudbroker/disks/resource_disk_replication.go new file mode 100644 index 0000000..27298fa --- /dev/null +++ b/internal/service/cloudbroker/disks/resource_disk_replication.go @@ -0,0 +1,218 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 disks + +import ( + "context" + "strconv" + + "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/disks" + "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" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic" +) + +func resourceDiskReplicationCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskId := uint64(d.Get("disk_id").(int)) + + log.Debugf("resourceDiskReplicationCreate: called for disk with ID: %d", diskId) + + c := m.(*controller.ControllerCfg) + + err := ic.ExistDiskID(ctx, diskId, m) + if err != nil { + return diag.FromErr(err) + } + + reqCreate := disks.ReplicateRequest{ + DiskID: diskId, + Name: d.Get("disk_name").(string), + SepID: uint64(d.Get("sep_id").(int)), + PoolName: d.Get("pool_name").(string), + } + + diskReplicaId, err := c.CloudBroker().Disks().Replicate(ctx, reqCreate) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(diskReplicaId, 10)) + d.Set("replica_disk_id", diskReplicaId) + + log.Debugf("resourceDiskReplicationCreate: create replica complete for disk with ID: %d", diskId) + + warnings := dc.Warnings{} + + if start, ok := d.GetOk("start"); ok && !start.(bool) { + log.Debugf("resourceDiskReplicationCreate: replication between disk with ID: %d and replica with ID: %d, try to stop", diskId, diskReplicaId) + reqStop := disks.ReplicationStopRequest{ + DiskID: diskId, + } + _, err = c.CloudBroker().Disks().ReplicationStop(ctx, reqStop) + if err != nil { + warnings.Add(err) + } + log.Debugf("resourceDiskReplicationCreate: replication between disk with ID: %d and replica with ID: %d, stoped", diskId, diskReplicaId) + } + return append(resourceDiskReplicationRead(ctx, d, m), warnings.Get()...) +} + +func resourceDiskReplicationRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceDiskReplicationRead: called for disk with ID: %s", d.Id()) + c := m.(*controller.ControllerCfg) + + req := disks.ReplicationStatusRequest{ + DiskID: uint64(d.Get("disk_id").(int)), + } + + status, err := c.CloudBroker().Disks().ReplicationStatus(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + diskReplica, err := utilityDiskReplicaCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + flattenDiskReplica(d, diskReplica, status) + + log.Debugf("resourceDiskReplicationRead: read complete for disk with ID: %s", d.Id()) + return nil +} + +func resourceDiskReplicationUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskId := uint64(d.Get("disk_id").(int)) + log.Debugf("resourceDiskReplicationUpdate: called for disk with ID: %d", diskId) + + err := ic.ExistDiskID(ctx, diskId, m) + if err != nil { + return diag.FromErr(err) + } + + if d.HasChange("start") { + if err := utilityDiskReplicationUpdateStartStop(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("pause") { + if err := utilityDiskReplicationUpdatePause(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("reverse") { + if err := utilityDiskReplicationUpdateReverse(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + + log.Debugf("resourceDiskReplicationUpdate: read complete for disk with ID: %d", diskId) + return resourceDiskReplicationRead(ctx, d, m) +} + +func resourceDiskReplicationDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + diskId := uint64(d.Get("disk_id").(int)) + log.Debugf("resourceDiskReplicationDelete: called for disk with ID: %d", diskId) + + disk, err := utilityDiskReplicaCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + + if d.Get("start").(bool) { + reqStop := disks.ReplicationStopRequest{ + DiskID: uint64(d.Get("disk_id").(int)), + } + + log.Debugf("resourceDiskReplicationDelete: stop replication for disk with ID: %d", diskId) + _, err = c.CloudBroker().Disks().ReplicationStop(ctx, reqStop) + if err != nil { + return diag.FromErr(err) + } + log.Debugf("resourceDiskReplicationDelete: stop replication for disk with ID: %d, complete", diskId) + } + + reqDelete := disks.DeleteRequest{ + DiskID: disk.ID, + Detach: d.Get("detach").(bool), + Permanently: d.Get("permanently").(bool), + Reason: d.Get("reason").(string), + } + + log.Debugf("resourceDiskReplicationDelete: delete disk replica for disk with ID: %d", diskId) + _, err = c.CloudBroker().Disks().Delete(ctx, reqDelete) + if err != nil { + return diag.FromErr(err) + } + log.Debugf("resourceDiskReplicationDelete: delete disk replica for disk with ID: %d, complete", diskId) + + d.SetId("") + + return nil +} + +func ResourceDiskReplication() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceDiskReplicationCreate, + ReadContext: resourceDiskReplicationRead, + UpdateContext: resourceDiskReplicationUpdate, + DeleteContext: resourceDiskReplicationDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout300s, + Update: &constants.Timeout300s, + Delete: &constants.Timeout300s, + Default: &constants.Timeout300s, + }, + + Schema: resourceDiskReplicationSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/disks/schema.go b/internal/service/cloudbroker/disks/schema.go index ba8f62f..6d4b265 100644 --- a/internal/service/cloudbroker/disks/schema.go +++ b/internal/service/cloudbroker/disks/schema.go @@ -201,6 +201,39 @@ func dataSourceDiskSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, "reality_device_number": { Type: schema.TypeInt, Computed: true, @@ -350,6 +383,11 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by pool name", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -567,6 +605,39 @@ func dataSourceDiskListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, "reality_device_number": { Type: schema.TypeInt, Computed: true, @@ -707,6 +778,11 @@ func dataSourceDiskListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "type of the disks", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -924,6 +1000,39 @@ func dataSourceDiskListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, "reality_device_number": { Type: schema.TypeInt, Computed: true, @@ -1029,6 +1138,11 @@ func dataSourceDiskListDeletedSchemaMake() map[string]*schema.Schema { func dataSourceDiskListTypesSchemaMake() map[string]*schema.Schema { res := map[string]*schema.Schema{ + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1057,6 +1171,11 @@ func dataSourceDiskListTypesSchemaMake() map[string]*schema.Schema { func dataSourceDiskListTypesDetailedSchemaMake() map[string]*schema.Schema { return map[string]*schema.Schema{ + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1157,6 +1276,11 @@ func dataSourceDiskListUnattachedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Optional: true, }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1716,6 +1840,13 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { Optional: true, Computed: true, }, + "node_ids": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "detach": { Type: schema.TypeBool, Optional: true, @@ -1935,6 +2066,39 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, "reality_device_number": { Type: schema.TypeInt, Computed: true, @@ -2015,3 +2179,714 @@ func resourceDiskSchemaMake() map[string]*schema.Schema { return rets } + +func dataSourceDiskReplicationSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Id of primary disk", + }, + "replica_disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Id of secondary disk", + }, + "status_replication": { + Type: schema.TypeString, + Computed: true, + Description: "Status of replication", + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "boot_partition": { + Type: schema.TypeInt, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeString, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "disk_name": { + Type: schema.TypeString, + Computed: true, + }, + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "shareable": { + Type: schema.TypeBool, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_used": { + Type: schema.TypeFloat, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return rets +} + +func resourceDiskReplicationSchemaMake() map[string]*schema.Schema { + rets := map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Id of primary disk", + }, + "disk_name": { + Type: schema.TypeString, + Required: true, + Description: "Name of disk replica", + }, + "sep_id": { + Type: schema.TypeInt, + Required: true, + Description: "Storage endpoint provider ID to create disk replica", + }, + "pool_name": { + Type: schema.TypeString, + Required: true, + Description: "Pool for disk location", + }, + "pause": { + Type: schema.TypeBool, + Optional: true, + Description: "Resume replication", + }, + "reverse": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Reverse replication", + }, + "start": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "Start/Stop replication", + }, + "detach": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Detach disk from machine first", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Delete disk permanently", + }, + "reason": { + Type: schema.TypeString, + Optional: true, + Description: "Reason for disk deletion", + }, + "replica_disk_id": { + Type: schema.TypeInt, + Computed: true, + Description: "Id of replica disk", + }, + "status_replication": { + Type: schema.TypeString, + Computed: true, + Description: "Status of replication", + }, + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "account_name": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeString, + Computed: true, + }, + "boot_partition": { + Type: schema.TypeInt, + Computed: true, + }, + "computes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeString, + Computed: true, + }, + "compute_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "destruction_time": { + Type: schema.TypeInt, + Computed: true, + }, + "devicename": { + Type: schema.TypeString, + Computed: true, + }, + "disk_path": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "images": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "iotune": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "read_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "total_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_bytes_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec": { + Type: schema.TypeInt, + Computed: true, + }, + "write_iops_sec_max": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "iqn": { + Type: schema.TypeString, + Computed: true, + }, + "login": { + Type: schema.TypeString, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "order": { + Type: schema.TypeInt, + Computed: true, + }, + "params": { + Type: schema.TypeString, + Computed: true, + }, + "parent_id": { + Type: schema.TypeInt, + Computed: true, + }, + "passwd": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "purge_time": { + Type: schema.TypeInt, + Computed: true, + }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, + "reality_device_number": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "sep_type": { + Type: schema.TypeString, + Computed: true, + }, + "shareable": { + Type: schema.TypeBool, + Computed: true, + }, + "size_max": { + Type: schema.TypeInt, + Computed: true, + }, + "size_used": { + Type: schema.TypeFloat, + Computed: true, + }, + "snapshots": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "label": { + Type: schema.TypeString, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_guid": { + Type: schema.TypeString, + Computed: true, + }, + "snap_set_time": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vmid": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return rets +} \ No newline at end of file diff --git a/internal/service/cloudbroker/disks/utility_disk_list.go b/internal/service/cloudbroker/disks/utility_disk_list.go index 3320680..d453b13 100644 --- a/internal/service/cloudbroker/disks/utility_disk_list.go +++ b/internal/service/cloudbroker/disks/utility_disk_list.go @@ -1,93 +1,96 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 disks - -import ( - "context" - "strings" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*disks.ListDisks, error) { - c := m.(*controller.ControllerCfg) - req := disks.ListRequest{} - - if by_id, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(by_id.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if account_name, ok := d.GetOk("account_name"); ok { - req.AccountName = account_name.(string) - } - if disk_max_size, ok := d.GetOk("disk_max_size"); ok { - req.DiskMaxSize = int64(disk_max_size.(int)) - } - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - if shared, ok := d.GetOk("shared"); ok { - req.Shared = shared.(bool) - } - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if diskType, ok := d.GetOk("type"); ok { - req.Type = strings.ToUpper(diskType.(string)) - } - if pool, ok := d.GetOk("pool"); ok { - req.Pool = pool.(string) - } - if sepID, ok := d.GetOk("sep_id"); ok { - req.SEPID = uint64(sepID.(int)) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityDiskListCheckPresence: load disk list") - diskList, err := c.CloudBroker().Disks().List(ctx, req) - if err != nil { - return nil, err - } - - return diskList, nil -} +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 disks + +import ( + "context" + "strings" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityDiskListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*disks.ListDisks, error) { + c := m.(*controller.ControllerCfg) + req := disks.ListRequest{} + + if by_id, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(by_id.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if account_name, ok := d.GetOk("account_name"); ok { + req.AccountName = account_name.(string) + } + if disk_max_size, ok := d.GetOk("disk_max_size"); ok { + req.DiskMaxSize = int64(disk_max_size.(int)) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if shared, ok := d.GetOk("shared"); ok { + req.Shared = shared.(bool) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if diskType, ok := d.GetOk("type"); ok { + req.Type = strings.ToUpper(diskType.(string)) + } + if pool, ok := d.GetOk("pool"); ok { + req.Pool = pool.(string) + } + if sepID, ok := d.GetOk("sep_id"); ok { + req.SEPID = uint64(sepID.(int)) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityDiskListCheckPresence: load disk list") + diskList, err := c.CloudBroker().Disks().List(ctx, req) + if err != nil { + return nil, err + } + + return diskList, nil +} diff --git a/internal/service/cloudbroker/disks/utility_disk_list_deleted.go b/internal/service/cloudbroker/disks/utility_disk_list_deleted.go index 40921a6..5b21553 100644 --- a/internal/service/cloudbroker/disks/utility_disk_list_deleted.go +++ b/internal/service/cloudbroker/disks/utility_disk_list_deleted.go @@ -68,6 +68,9 @@ func utilityDiskListDeletedCheckPresence(ctx context.Context, d *schema.Resource if typev, ok := d.GetOk("type"); ok { req.Type = typev.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/disks/utility_disk_list_types.go b/internal/service/cloudbroker/disks/utility_disk_list_types.go index dafc4be..059ff05 100644 --- a/internal/service/cloudbroker/disks/utility_disk_list_types.go +++ b/internal/service/cloudbroker/disks/utility_disk_list_types.go @@ -15,6 +15,9 @@ func utilityDiskListTypesCheckPresence(ctx context.Context, d *schema.ResourceDa Detailed: false, } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/disks/utility_disk_list_types_detailed.go b/internal/service/cloudbroker/disks/utility_disk_list_types_detailed.go index 44ce0f3..d8616cd 100644 --- a/internal/service/cloudbroker/disks/utility_disk_list_types_detailed.go +++ b/internal/service/cloudbroker/disks/utility_disk_list_types_detailed.go @@ -15,6 +15,9 @@ func utilityDiskListTypesDetailedCheckPresence(ctx context.Context, d *schema.Re req := disks.ListTypesRequest{ Detailed: true, } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/disks/utility_disk_list_unattached.go b/internal/service/cloudbroker/disks/utility_disk_list_unattached.go index f3da6c9..414f6d5 100644 --- a/internal/service/cloudbroker/disks/utility_disk_list_unattached.go +++ b/internal/service/cloudbroker/disks/utility_disk_list_unattached.go @@ -37,6 +37,9 @@ func utilityDiskListUnattachedCheckPresence(ctx context.Context, d *schema.Resou if pool, ok := d.GetOk("pool"); ok { req.Pool = pool.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/disks/utility_disk_replica.go b/internal/service/cloudbroker/disks/utility_disk_replica.go new file mode 100644 index 0000000..9a56aa6 --- /dev/null +++ b/internal/service/cloudbroker/disks/utility_disk_replica.go @@ -0,0 +1,174 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 disks + +import ( + "context" + "strconv" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityDiskReplicationUpdateStartStop(ctx context.Context, d *schema.ResourceData, m interface{}) error { + diskId := uint64(d.Get("disk_id").(int)) + targetDiskId, _ := strconv.ParseUint(d.Id(), 10, 64) + + log.Debugf("utilityDiskReplicationUpdateStartStop: start update for disk replica with ID: %d", diskId) + c := m.(*controller.ControllerCfg) + + start, ok := d.GetOk("start") + + if ok && start.(bool) { + log.Debugf("utilityDiskReplicationUpdateStartStop: start disk replication from Disk with ID: %d to Disk with ID: %d", diskId, targetDiskId) + req := disks.ReplicationStartRequest{ + DiskID: diskId, + TargetDiskID: targetDiskId, + } + _, err := c.CloudBroker().Disks().ReplicationStart(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdateStartStop: start disk replication from Disk with ID: %d to Disk with ID: %d, complete", diskId, targetDiskId) + } + + if ok && !start.(bool) { + log.Debugf("utilityDiskReplicationUpdateStartStop: stop disk replication from Disk with ID: %d to Disk with ID: %d", targetDiskId, diskId) + req := disks.ReplicationStopRequest{ + DiskID: targetDiskId, + } + _, err := c.CloudBroker().Disks().ReplicationStop(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdateStartStop: stop disk replication from Disk with ID: %d to Disk with ID: %d, complete", targetDiskId, diskId) + } + + log.Debugf("utilityDiskReplicationUpdateStartStop: complete update for disk replica with ID: %d", diskId) + return nil +} + +func utilityDiskReplicationUpdatePause(ctx context.Context, d *schema.ResourceData, m interface{}) error { + diskId := uint64(d.Get("disk_id").(int)) + log.Debugf("utilityDiskReplicationUpdatePause: start update for disk replica with ID: %d", diskId) + c := m.(*controller.ControllerCfg) + + pause, ok := d.GetOk("pause") + + if ok && pause.(bool) { + log.Debugf("utilityDiskReplicationUpdatePause: pause disk replication with ID: %d", diskId) + req := disks.ReplicationSuspendRequest{ + DiskID: diskId, + } + _, err := c.CloudBroker().Disks().ReplicationSuspend(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdatePause: pause disk replication with ID: %d, complete", diskId) + } + + if ok && !pause.(bool) { + log.Debugf("utilityDiskReplicationUpdatePause: resume disk replication with ID: %d", diskId) + req := disks.ReplicationResumeRequest{ + DiskID: diskId, + } + _, err := c.CloudBroker().Disks().ReplicationResume(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicationUpdatePause: resume disk replication with ID: %d, complete", diskId) + } + + log.Debugf("utilityDiskReplicationUpdatePause: complete update for disk replica with ID: %d", diskId) + return nil +} + +func utilityDiskReplicationUpdateReverse(ctx context.Context, d *schema.ResourceData, m interface{}) error { + diskId := uint64(d.Get("disk_id").(int)) + targetDiskId, _ := strconv.ParseUint(d.Id(), 10, 64) + + log.Debugf("utilityDiskReplicaUpdateReverse: start update for disk replica with ID: %d", diskId) + c := m.(*controller.ControllerCfg) + + reverse, ok := d.GetOk("reverse") + + if ok && reverse.(bool) { + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d", diskId, targetDiskId) + req := disks.ReplicationReverseRequest{ + DiskID: diskId, + } + _, err := c.CloudBroker().Disks().ReplicationReverse(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d, complete", diskId, targetDiskId) + } + + if ok && !reverse.(bool) { + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d", targetDiskId, diskId) + req := disks.ReplicationReverseRequest{ + DiskID: targetDiskId, + } + _, err := c.CloudBroker().Disks().ReplicationReverse(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityDiskReplicaUpdateReverse: reverse disk replication from Disk with ID: %d to Disk with ID: %d, complete", targetDiskId, diskId) + } + + log.Debugf("utilityDiskReplicaUpdateReverse: complete update for disk replica with ID: %d", diskId) + return nil +} + +func utilityDiskReplicaCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*disks.RecordDisk, error) { + c := m.(*controller.ControllerCfg) + + req := disks.GetRequest{} + + if d.Id() != "" { + diskId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.DiskID = diskId + } else { + req.DiskID = uint64(d.Get("replica_disk_id").(int)) + } + + log.Debugf("utilityDiskReplicaCheckPresence: load disk") + disk, err := c.CloudBroker().Disks().Get(ctx, req) + if err != nil { + return nil, err + } + + return disk, nil +} diff --git a/internal/service/cloudbroker/extnet/schema.go b/internal/service/cloudbroker/extnet/schema.go index af67da8..3637947 100644 --- a/internal/service/cloudbroker/extnet/schema.go +++ b/internal/service/cloudbroker/extnet/schema.go @@ -47,6 +47,11 @@ func dataSourceExtnetListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -718,7 +723,7 @@ func resourceExtnetSchemaMake() map[string]*schema.Schema { "shared_with": { Type: schema.TypeSet, Computed: true, - Optional: true, + Optional: true, Elem: &schema.Schema{ Type: schema.TypeInt, }, @@ -899,4 +904,4 @@ func resourceExtnetSchemaMake() map[string]*schema.Schema { }, }, } -} \ No newline at end of file +} diff --git a/internal/service/cloudbroker/extnet/utility_extnet_list.go b/internal/service/cloudbroker/extnet/utility_extnet_list.go index f4305e3..1ce23d6 100644 --- a/internal/service/cloudbroker/extnet/utility_extnet_list.go +++ b/internal/service/cloudbroker/extnet/utility_extnet_list.go @@ -74,6 +74,10 @@ func utilityExtnetListCheckPresence(ctx context.Context, d *schema.ResourceData, req.Status = status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/flipgroup/schema.go b/internal/service/cloudbroker/flipgroup/schema.go index 8274d04..96e9b31 100644 --- a/internal/service/cloudbroker/flipgroup/schema.go +++ b/internal/service/cloudbroker/flipgroup/schema.go @@ -189,6 +189,11 @@ func dataSourceFlipgroupsListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "by_id", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -199,6 +204,29 @@ func dataSourceFlipgroupsListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Page size", }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Account id", + }, + "conn_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Conn id", + }, + "client_ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "client_ids", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Status", + }, "items": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudbroker/flipgroup/utility_flipgroup_list.go b/internal/service/cloudbroker/flipgroup/utility_flipgroup_list.go index 24c8dcc..6d9f0fe 100644 --- a/internal/service/cloudbroker/flipgroup/utility_flipgroup_list.go +++ b/internal/service/cloudbroker/flipgroup/utility_flipgroup_list.go @@ -69,12 +69,30 @@ func utilityFlipgroupListCheckPresence(ctx context.Context, d *schema.ResourceDa if byID, ok := d.GetOk("by_id"); ok { req.ByID = uint64(byID.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } if size, ok := d.GetOk("size"); ok { req.Size = uint64(size.(int)) } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountId = uint64(accountId.(int)) + } + if clientId, ok := d.GetOk("client_ids"); ok { + clientIds := clientId.([]interface{}) + for _, elem := range clientIds { + req.ClientIDs = append(req.ClientIDs, uint64(elem.(int))) + } + } + if connId, ok := d.GetOk("conn_id"); ok { + req.ConnId = uint64(connId.(int)) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } log.Debugf("utilityFlipgroupListCheckPresence: load flipgroup list") flipgroupList, err := c.CloudBroker().FLIPGroup().List(ctx, req) diff --git a/internal/service/cloudbroker/grid/schema.go b/internal/service/cloudbroker/grid/schema.go index 7295af4..f21b9a2 100644 --- a/internal/service/cloudbroker/grid/schema.go +++ b/internal/service/cloudbroker/grid/schema.go @@ -54,6 +54,11 @@ func dataSourceGridListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "name", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudbroker/grid/utility_grid_list.go b/internal/service/cloudbroker/grid/utility_grid_list.go index d6503b8..7f5f00e 100644 --- a/internal/service/cloudbroker/grid/utility_grid_list.go +++ b/internal/service/cloudbroker/grid/utility_grid_list.go @@ -1,68 +1,71 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 grid - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/grid" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityGridListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*grid.ListGrids, error) { - c := m.(*controller.ControllerCfg) - req := grid.ListRequest{} - - if byID, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(byID.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityGridListCheckPresence: load grid list") - gridList, err := c.CloudBroker().Grid().List(ctx, req) - if err != nil { - return nil, err - } - - return gridList, nil -} +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 grid + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/grid" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityGridListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*grid.ListGrids, error) { + c := m.(*controller.ControllerCfg) + req := grid.ListRequest{} + + if byID, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byID.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityGridListCheckPresence: load grid list") + gridList, err := c.CloudBroker().Grid().List(ctx, req) + if err != nil { + return nil, err + } + + return gridList, nil +} diff --git a/internal/service/cloudbroker/ic/input_checks.go b/internal/service/cloudbroker/ic/input_checks.go index dce6538..ada7925 100644 --- a/internal/service/cloudbroker/ic/input_checks.go +++ b/internal/service/cloudbroker/ic/input_checks.go @@ -7,6 +7,7 @@ import ( cb_account "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/account" cb_compute "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/compute" + cb_disks "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks" cb_extnet "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/extnet" cb_gid "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/grid" cb_image "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" @@ -15,7 +16,9 @@ import ( cb_lb "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/lb" cb_rg "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/rg" cb_stack "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/stack" + cb_vfpool "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vfpool" cb_vins "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vins" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" ) @@ -37,6 +40,78 @@ func ExistRG(ctx context.Context, rgId uint64, c *controller.ControllerCfg) erro return nil } +func ExistRGs(ctx context.Context, rgIDs []uint64, c *controller.ControllerCfg) error { + req := cb_rg.ListRequest{} + + rgList, err := c.CloudBroker().RG().List(ctx, req) + if err != nil { + return err + } + + if len(rgList.Data) == 0 { + return fmt.Errorf("you have not been granted access to any resource group") + } + + notFound := make([]uint64, 0, len(rgIDs)) + + for _, rgID := range rgIDs { + found := false + + for _, rg := range rgList.Data { + if rgID == rg.ID { + found = true + break + } + } + + if !found { + notFound = append(notFound, rgID) + } + } + + if len(notFound) > 0 { + return fmt.Errorf("RGs with ids %v not found", notFound) + } + + return nil +} + +func ExistAccouts(ctx context.Context, accountIDs []uint64, c *controller.ControllerCfg) error { + req := cb_account.ListRequest{} + + accList, err := c.CloudBroker().Account().List(ctx, req) + if err != nil { + return err + } + + if len(accList.Data) == 0 { + return fmt.Errorf("you have not been granted access to any account") + } + + notFound := make([]uint64, 0, len(accountIDs)) + + for _, accID := range accountIDs { + found := false + + for _, acc := range accList.Data { + if accID == acc.ID { + found = true + break + } + } + + if !found { + notFound = append(notFound, accID) + } + } + + if len(notFound) > 0 { + return fmt.Errorf("Accounts with ids %v not found", notFound) + } + + return nil +} + func ExistImage(ctx context.Context, imageId uint64, c *controller.ControllerCfg) error { req := cb_image.ListRequest{ ByID: imageId, @@ -54,6 +129,42 @@ func ExistImage(ctx context.Context, imageId uint64, c *controller.ControllerCfg return nil } +func ExistImages(ctx context.Context, imageIDs []uint64, c *controller.ControllerCfg) error { + req := cb_image.ListRequest{} + + listImages, err := c.CloudBroker().Image().List(ctx, req) + if err != nil { + return err + } + + if len(listImages.Data) == 0 { + return fmt.Errorf("you have not been granted access to any images") + } + + notFound := make([]uint64, 0, len(imageIDs)) + + for _, imageID := range imageIDs { + found := false + + for _, image := range listImages.Data { + if imageID == image.ID { + found = true + break + } + } + + if !found { + notFound = append(notFound, imageID) + } + } + + if len(notFound) > 0 { + return fmt.Errorf("images with ids %v not found", notFound) + } + + return nil +} + func ExistVins(ctx context.Context, vinsId uint64, c *controller.ControllerCfg) error { req := cb_vins.ListRequest{ ByID: vinsId, @@ -132,6 +243,35 @@ func ExistExtNets(ctx context.Context, extNetIds []uint64, c *controller.Control return errs } +func ExistVFPools(ctx context.Context, vfpoolIds []uint64, c *controller.ControllerCfg) []error { + var errs []error + + req := cb_vfpool.ListRequest{} + + vfpoolList, err := c.CloudBroker().VFPool().List(ctx, req) + if err != nil { + errs = append(errs, err) + return errs + } + + for _, vfpoolId := range vfpoolIds { + found := false + + for _, vfpool := range vfpoolList.Data { + if vfpoolId == vfpool.ID { + found = true + break + } + } + + if !found { + errs = append(errs, fmt.Errorf("VFPool with ID %v not found", vfpoolId)) + } + } + + return errs +} + func ExistExtNetInLb(ctx context.Context, extNetId uint64, c *controller.ControllerCfg) error { if extNetId == 0 { return nil @@ -404,3 +544,88 @@ func ExistK8s(ctx context.Context, k8sId uint64, c *controller.ControllerCfg) er return nil } + +func IsMoreThanOneDisksTypeB(ctx context.Context, disks interface{}) error { + count := 0 + + for _, elem := range disks.([]interface{}) { + diskVal := elem.(map[string]interface{}) + if diskVal["disk_type"].(string) == "B" { + count++ + } + if count > 1 { + return fmt.Errorf("block disks have more 1 disk type 'B'") + } + } + + return nil +} + +func ExistDiskID(ctx context.Context, diskId uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + + req := cb_disks.ListRequest{ + ByID: diskId, + } + + diskList, err := c.CloudBroker().Disks().List(ctx, req) + if err != nil { + return err + } + + if len(diskList.Data) == 0 { + return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not allowed or does not exist", diskId) + } + + if diskList.Data[0].SEPType != "TATLIN" { + return fmt.Errorf("resourceDiskReplication: can't create or update Disk replication because DiskID %d is not TATLIN SEP Type", diskId) + } + + return nil +} + +func ExistBlankCompute(ctx context.Context, computeId uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + req := cb_compute.GetRequest{ComputeID: computeId} + + // check for compute existence + computeRecord, err := c.CloudBroker().Compute().Get(ctx, req) + if err != nil { + return fmt.Errorf("ComputeID %d is not allowed or does not exist", computeId) + } + + // check if compute was created as blank + computeImageId := computeRecord.ImageID + bootImageId := -1 + for _, d := range computeRecord.Disks { + if d.Type == "B" { + bootImageId = int(d.ImageID) + break + } + } + + if computeImageId != 0 && bootImageId != 0 { + return fmt.Errorf("ComputeID %d is not allowed because it is not blank compute (either compute imageId or boot imageId are not zero)", computeId) + } + + return nil +} + +func ExistPlatformDisk(ctx context.Context, diskId uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + + req := cb_disks.ListRequest{ + ByID: diskId, + } + + diskList, err := c.CloudBroker().Disks().List(ctx, req) + if err != nil { + return err + } + + if len(diskList.Data) != 1 { + return fmt.Errorf("DiskID %d is not allowed or does not exist", diskId) + } + + return nil +} diff --git a/internal/service/cloudbroker/image/flattens.go b/internal/service/cloudbroker/image/flattens.go index 8d7b705..9a0d346 100644 --- a/internal/service/cloudbroker/image/flattens.go +++ b/internal/service/cloudbroker/image/flattens.go @@ -1,6 +1,7 @@ package image import ( + "encoding/json" "strconv" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -10,17 +11,18 @@ import ( ) func flattenImage(d *schema.ResourceData, img *image.RecordImage) { + cdPresentedTo, _ := json.Marshal(img.CdPresentedTo) + log.Debugf("flattenImageID %d", img.ID) d.Set("image_id", img.ID) d.Set("unc_path", img.UNCPath) - d.Set("ckey", img.CKey) - d.Set("meta", flattens.FlattenMeta(img.Meta)) d.Set("account_id", img.AccountID) d.Set("acl", flattenAcl(img.ACL)) d.Set("architecture", img.Architecture) d.Set("boot_type", img.BootType) d.Set("bootable", img.Bootable) d.Set("computeci_id", img.ComputeCIID) + d.Set("cd_presented_to", string(cdPresentedTo)) d.Set("deleted_time", img.DeletedTime) d.Set("desc", img.Description) d.Set("drivers", img.Drivers) @@ -33,6 +35,7 @@ func flattenImage(d *schema.ResourceData, img *image.RecordImage) { d.Set("link_to", img.LinkTo) d.Set("milestones", img.Milestones) d.Set("name", img.Name) + d.Set("network_interface_naming", img.NetworkInterfaceNaming) d.Set("password", img.Password) d.Set("pool_name", img.Pool) d.Set("present_to", img.PresentTo) @@ -86,48 +89,50 @@ func flattenImageList(il *image.ListImages) []map[string]interface{} { log.Debug("flattenImageList") res := make([]map[string]interface{}, 0, len(il.Data)) for _, item := range il.Data { + cdPresentedTo, _ := json.Marshal(item.CdPresentedTo) + temp := map[string]interface{}{ - "image_id": item.ID, - "unc_path": item.UNCPath, - "ckey": item.CKey, - "meta": flattens.FlattenMeta(item.Meta), - "account_id": item.AccountID, - "acl": flattenAcl(item.ACL), - "architecture": item.Architecture, - "boot_type": item.BootType, - "bootable": item.Bootable, - "computeci_id": item.ComputeCIID, - "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, - "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, + "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, + "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) } diff --git a/internal/service/cloudbroker/image/resource_check_input_values.go b/internal/service/cloudbroker/image/resource_check_input_values.go new file mode 100644 index 0000000..c4a6671 --- /dev/null +++ b/internal/service/cloudbroker/image/resource_check_input_values.go @@ -0,0 +1,50 @@ +package image + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func checkParamsExistenceBlankCompute(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg) diag.Diagnostics { + var errs []error + + accountID := uint64(d.Get("account_id").(int)) + computeId := uint64(d.Get("compute_id").(int)) + + if err := ic.ExistBlankCompute(ctx, computeId, c); err != nil { + errs = append(errs, err) + } + + if _, ok := d.GetOk("account_id"); ok { + if err := ic.ExistAccount(ctx, accountID, c); err != nil { + errs = append(errs, err) + } + } + + return dc.ErrorsToDiagnostics(errs) +} + +func checkParamsExistencePlatformDisk(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg) diag.Diagnostics { + var errs []error + + accountID := uint64(d.Get("account_id").(int)) + diskId := uint64(d.Get("disk_id").(int)) + + if err := ic.ExistPlatformDisk(ctx, diskId, c); err != nil { + errs = append(errs, err) + } + + if _, ok := d.GetOk("account_id"); ok { + if err := ic.ExistAccount(ctx, accountID, c); err != nil { + errs = append(errs, err) + } + } + + return dc.ErrorsToDiagnostics(errs) +} diff --git a/internal/service/cloudbroker/image/resource_image.go b/internal/service/cloudbroker/image/resource_image.go index ef2b447..364367a 100644 --- a/internal/service/cloudbroker/image/resource_image.go +++ b/internal/service/cloudbroker/image/resource_image.go @@ -41,19 +41,39 @@ import ( "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" "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" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" ) func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceImageCreate: called for image %s", d.Get("name").(string)) + url, urlOk := d.GetOk("url") + filePath, fileImageOk := d.GetOk("file_path") + + if !urlOk && !fileImageOk { + return diag.Errorf("resourceImageCreate: no valid url or file_path specified") + } + + if urlOk && fileImageOk { + return diag.Errorf("resourceImageCreate: either url or resource file_path should be specified") + } + c := m.(*controller.ControllerCfg) syncMode := d.Get("sync_mode").(bool) var imageId uint64 + if fileImageOk { + var err error + url, err = c.CloudBroker().Image().UploadImageFile(ctx, filePath.(string)) + if err != nil { + return diag.FromErr(err) + } + } + if syncMode { - req, err := SyncCreateRequest(ctx, d, m) + req, err := SyncCreateRequest(ctx, d, m, url.(string)) if err != nil { return diag.FromErr(err) } @@ -62,7 +82,7 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac return diag.FromErr(err) } } else { - req, err := CreateRequest(ctx, d, m) + req, err := CreateRequest(ctx, d, m, url.(string)) if err != nil { return diag.FromErr(err) } @@ -74,7 +94,15 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, m interfac d.SetId(strconv.FormatUint(imageId, 10)) - return resourceImageRead(ctx, d, m) + var w dc.Warnings + + if _, ok := d.GetOk("accounts"); ok { + if err := resourceImageSetAccess(ctx, d, m); err != nil { + w.Add(err) + } + } + + return append(resourceImageRead(ctx, d, m), w.Get()...) } func resourceImageRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -175,13 +203,20 @@ func resourceImageUpdate(ctx context.Context, d *schema.ResourceData, m interfac } } - if d.HasChanges("name", "username", "password", "account_id", "bootable", "hot_resize") { + if d.HasChanges("name", "username", "password", "account_id", "bootable", "hot_resize", "network_interface_naming") { err := resourceImageEdit(ctx, d, m) if err != nil { return diag.FromErr(err) } } + if d.HasChange("accounts") { + err := resourceImageChangeAccess(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + return nil } @@ -307,7 +342,9 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ if d.HasChange("hot_resize") { req.HotResize = d.Get("hot_resize").(bool) } - + if d.HasChange("network_interface_naming") { + req.NetworkInterfaceNaming = d.Get("network_interface_naming").(string) + } _, err := c.CloudBroker().Image().Edit(ctx, req) if err != nil { return err @@ -315,6 +352,78 @@ func resourceImageEdit(ctx context.Context, d *schema.ResourceData, m interface{ return nil } +func resourceImageChangeAccess(ctx context.Context, d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceImageChangeAccess: called for %s, id: %s", d.Get("name").(string), d.Id()) + c := m.(*controller.ControllerCfg) + + imageId, _ := strconv.ParseUint(d.Id(), 10, 64) + + oldSet, newSet := d.GetChange("accounts") + + revokeAccess := (oldSet.(*schema.Set).Difference(newSet.(*schema.Set))).List() + if len(revokeAccess) > 0 { + revokeAccounts := make([]uint64, 0, len(revokeAccess)) + for _, accountId := range revokeAccess { + revokeAccounts = append(revokeAccounts, uint64(accountId.(int))) + } + + req := image.RevokeAccessRequest{ + ImageID: imageId, + AccountIDs: revokeAccounts, + } + + _, err := c.CloudBroker().Image().RevokeAccess(ctx, req) + if err != nil { + return err + } + } + + addedAccess := (newSet.(*schema.Set).Difference(oldSet.(*schema.Set))).List() + if len(addedAccess) > 0 { + grantAccounts := make([]uint64, 0, len(addedAccess)) + for _, accountId := range addedAccess { + grantAccounts = append(grantAccounts, uint64(accountId.(int))) + } + + req := image.GrantAccessRequest{ + ImageID: imageId, + AccountIDs: grantAccounts, + } + + _, err := c.CloudBroker().Image().GrantAccess(ctx, req) + if err != nil { + return err + } + } + + return nil +} + +func resourceImageSetAccess(ctx context.Context, d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceImageSetAccess: called for %s, id: %s", d.Get("name").(string), d.Id()) + c := m.(*controller.ControllerCfg) + + imageId, _ := strconv.ParseUint(d.Id(), 10, 64) + + accounts := d.Get("accounts").([]interface{}) + accountIDs := make([]uint64, 0, len(accounts)) + for _, accountId := range accounts { + accountIDs = append(accountIDs, uint64(accountId.(int))) + } + + req := image.GrantAccessRequest{ + ImageID: imageId, + AccountIDs: accountIDs, + } + + _, err := c.CloudBroker().Image().GrantAccess(ctx, req) + if err != nil { + return err + } + + return nil +} + func ResourceImage() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, diff --git a/internal/service/cloudbroker/image/resource_image_from_blank_compute.go b/internal/service/cloudbroker/image/resource_image_from_blank_compute.go new file mode 100644 index 0000000..05c8598 --- /dev/null +++ b/internal/service/cloudbroker/image/resource_image_from_blank_compute.go @@ -0,0 +1,295 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 image + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "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/compute" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/tasks" + "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" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" +) + +func resourceImageFromBlankComputeCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromBlankComputeCreate: called for image %s", d.Get("name").(string)) + c := m.(*controller.ControllerCfg) + + if diags := checkParamsExistenceBlankCompute(ctx, d, c); diags != nil { + return diags + } + + req := compute.CreateTemplateFromBlankRequest{ + ComputeID: uint64(d.Get("compute_id").(int)), + Name: d.Get("name").(string), + BootType: d.Get("boot_type").(string), + ImageType: d.Get("image_type").(string), + } + + if username, ok := d.GetOk("username"); ok { + req.Username = username.(string) + } + if password, ok := d.GetOk("password"); ok { + req.Password = password.(string) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if sepId, ok := d.GetOk("sep_id"); ok { + req.SepID = uint64(sepId.(int)) + } + if poolName, ok := d.GetOk("pool_name"); ok { + req.PoolName = poolName.(string) + } + if hotresize, ok := d.GetOk("hot_resize"); ok { + req.HotResize = hotresize.(bool) + } + + var imageId uint64 + var err error + asyncMode := d.Get("async_mode").(bool) + if !asyncMode { + imageId, err = c.CloudBroker().Compute().CreateTemplateFromBlank(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } else { + taskId, err := c.CloudBroker().Compute().CreateTemplateFromBlankAsync(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + taskReq := tasks.GetRequest{ + AuditID: strings.Trim(taskId, `"`), + } + + for { + task, err := c.CloudBroker().Tasks().Get(ctx, taskReq) + if err != nil { + return diag.FromErr(err) + } + + log.Debugf("resourceImageFromBlankComputeCreate: instance creating - %s", task.Stage) + + if task.Completed { + if task.Error != "" { + return diag.FromErr(fmt.Errorf("cannot create image instance: %v", task.Error)) + } + + id, err := task.Result.ID() + imageId = uint64(id) + if err != nil { + return diag.FromErr(err) + } + break + } + + time.Sleep(time.Second * 20) + } + } + + d.SetId(strconv.FormatUint(imageId, 10)) + d.Set("image_id", imageId) + + var w dc.Warnings + + if _, ok := d.GetOk("accounts"); ok { + if err := resourceImageSetAccess(ctx, d, m); err != nil { + w.Add(err) + } + } + + return append(resourceImageFromBlankComputeRead(ctx, d, m), w.Get()...) +} + +func resourceImageFromBlankComputeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromBlankComputeRead: called for %s id: %s", d.Get("name").(string), d.Id()) + + img, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + switch img.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + } + + flattenImage(d, img) + + return nil +} + +func resourceImageFromBlankComputeDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromBlankComputeDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) + + _, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := image.DeleteRequest{ + ImageID: uint64(d.Get("image_id").(int)), + } + + if reason, ok := d.GetOk("reason"); ok { + req.Reason = reason.(string) + } + if permanently, ok := d.GetOk("permanently"); ok { + req.Permanently = permanently.(bool) + } + + _, err = c.CloudBroker().Image().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceImageFromBlankComputeUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromBlankComputeUpdate: called for %s, id: %s", d.Get("name").(string), d.Id()) + + c := m.(*controller.ControllerCfg) + if diags := checkParamsExistenceBlankCompute(ctx, d, c); diags != nil { + return diags + } + + // we do not allow change of compute_id, but allow resource update after import + old, _ := d.GetChange("compute_id") + if old.(int) != 0 && d.HasChange("compute_id") { + return diag.Errorf("resourceImageFromBlankComputeUpdate: can't update Image because compute_id is not allowed to be changed") + } + + img, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + switch img.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + } + + if d.HasChange("enabled") { + err := resourceImageChangeEnabled(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("shared_with") { + err := resourceImageShare(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("computeci_id") { + err := resourceImageChangeComputeci(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("enabled_stacks") { + err := resourceImageUpdateNodes(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChanges("name", "username", "password", "account_id", "bootable", "hot_resize", "network_interface_naming") { + err := resourceImageEdit(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("accounts") { + err := resourceImageChangeAccess(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + return resourceImageFromBlankComputeRead(ctx, d, m) +} + +func ResourceImageFromBlankCompute() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceImageFromBlankComputeCreate, + ReadContext: resourceImageFromBlankComputeRead, + UpdateContext: resourceImageFromBlankComputeUpdate, + DeleteContext: resourceImageFromBlankComputeDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout30m, + Read: &constants.Timeout900s, + Update: &constants.Timeout900s, + Delete: &constants.Timeout900s, + Default: &constants.Timeout900s, + }, + + Schema: resourceImageFromBlankComputeSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/image/resource_image_from_platform_disk.go b/internal/service/cloudbroker/image/resource_image_from_platform_disk.go new file mode 100644 index 0000000..1762834 --- /dev/null +++ b/internal/service/cloudbroker/image/resource_image_from_platform_disk.go @@ -0,0 +1,302 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 image + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "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/disks" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/tasks" + "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" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" +) + +func resourceImageFromPlatformDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromPlatformDiskCreate: called for image %s", d.Get("name").(string)) + c := m.(*controller.ControllerCfg) + + if diags := checkParamsExistencePlatformDisk(ctx, d, c); diags != nil { + return diags + } + + req := disks.FromPlatformDiskRequest{ + DiskID: uint64(d.Get("disk_id").(int)), + Name: d.Get("name").(string), + BootType: d.Get("boot_type").(string), + ImageType: d.Get("image_type").(string), + Architecture: d.Get("architecture").(string), + Bootable: d.Get("bootable").(bool), // default is true + } + + if username, ok := d.GetOk("username"); ok { + req.Username = username.(string) + } + if password, ok := d.GetOk("password"); ok { + req.Password = password.(string) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if sepId, ok := d.GetOk("sep_id"); ok { + req.SepID = uint64(sepId.(int)) + } + if poolName, ok := d.GetOk("pool_name"); ok { + req.PoolName = poolName.(string) + } + if driversInterface, ok := d.GetOk("drivers"); ok { + for _, d := range driversInterface.([]interface{}) { + req.Drivers = append(req.Drivers, d.(string)) + } + } + if hotresize, ok := d.GetOk("hot_resize"); ok { + req.HotResize = hotresize.(bool) + } + + var imageId uint64 + var err error + asyncMode := d.Get("async_mode").(bool) + if !asyncMode { + imageId, err = c.CloudBroker().Disks().FromPlatformDisk(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + } else { + taskId, err := c.CloudBroker().Disks().FromPlatformDiskAsync(ctx, req) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + taskReq := tasks.GetRequest{ + AuditID: strings.Trim(taskId, `"`), + } + + for { + task, err := c.CloudBroker().Tasks().Get(ctx, taskReq) + if err != nil { + return diag.FromErr(err) + } + + log.Debugf("resourceImageFromPlatformDiskCreate: instance creating - %s", task.Stage) + + if task.Completed { + if task.Error != "" { + return diag.FromErr(fmt.Errorf("cannot create image instance: %v", task.Error)) + } + + id, err := task.Result.ID() + imageId = uint64(id) + if err != nil { + return diag.FromErr(err) + } + break + } + + time.Sleep(time.Second * 20) + } + } + + d.SetId(strconv.FormatUint(imageId, 10)) + d.Set("image_id", imageId) + + var w dc.Warnings + + if _, ok := d.GetOk("accounts"); ok { + if err := resourceImageSetAccess(ctx, d, m); err != nil { + w.Add(err) + } + } + + return append(resourceImageFromPlatformDiskRead(ctx, d, m), w.Get()...) +} + +func resourceImageFromPlatformDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromPlatformDiskRead: called for %s id: %s", d.Get("name").(string), d.Id()) + + img, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + switch img.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + } + + flattenImage(d, img) + + return nil +} + +func resourceImageFromPlatformDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromPlatformDiskDelete: called for %s, id: %s", d.Get("name").(string), d.Id()) + + _, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + req := image.DeleteRequest{ + ImageID: uint64(d.Get("image_id").(int)), + } + + if reason, ok := d.GetOk("reason"); ok { + req.Reason = reason.(string) + } + if permanently, ok := d.GetOk("permanently"); ok { + req.Permanently = permanently.(bool) + } + + _, err = c.CloudBroker().Image().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func resourceImageFromPlatformDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceImageFromPlatformDiskUpdate: called for %s, id: %s", d.Get("name").(string), d.Id()) + + c := m.(*controller.ControllerCfg) + if diags := checkParamsExistencePlatformDisk(ctx, d, c); diags != nil { + return diags + } + + // we do not allow change of disk_id, but allow resource update after import + old, _ := d.GetChange("disk_id") + if old.(int) != 0 && d.HasChange("disk_id") { + return diag.Errorf("resourceImageFromPlatformDiskUpdate: can't update Image because disk_id is not allowed to be changed") + } + + img, err := utilityImageCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + switch img.Status { + case status.Modeled: + return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status) + case status.Destroyed, status.Purged: + d.SetId("") + return diag.Errorf("The resource cannot be updated because it has been destroyed") + } + + if d.HasChange("enabled") { + err := resourceImageChangeEnabled(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("shared_with") { + err := resourceImageShare(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("computeci_id") { + err := resourceImageChangeComputeci(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("enabled_stacks") { + err := resourceImageUpdateNodes(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChanges("name", "username", "password", "account_id", "bootable", "hot_resize", "network_interface_naming") { + err := resourceImageEdit(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("accounts") { + err := resourceImageChangeAccess(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + + return resourceImageFromPlatformDiskRead(ctx, d, m) +} + +func ResourceImageFromPlatformDisk() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceImageFromPlatformDiskCreate, + ReadContext: resourceImageFromPlatformDiskRead, + UpdateContext: resourceImageFromPlatformDiskUpdate, + DeleteContext: resourceImageFromPlatformDiskDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout30m, + Read: &constants.Timeout900s, + Update: &constants.Timeout900s, + Delete: &constants.Timeout900s, + Default: &constants.Timeout900s, + }, + + Schema: resourceImageFromPlatformDiskSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/image/schema.go b/internal/service/cloudbroker/image/schema.go index 33faa76..7077693 100644 --- a/internal/service/cloudbroker/image/schema.go +++ b/internal/service/cloudbroker/image/schema.go @@ -33,6 +33,8 @@ package image import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/statefuncs" ) func dataSourceImageListStacksSchemaMake() map[string]*schema.Schema { @@ -42,6 +44,11 @@ func dataSourceImageListStacksSchemaMake() map[string]*schema.Schema { Required: true, Description: "image id", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -385,6 +392,11 @@ func dataSourceImageListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "find by bootable True or False", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -406,18 +418,6 @@ func dataSourceImageListSchemaMake() map[string]*schema.Schema { Computed: true, Description: "unc path", }, - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "meta": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Description: "meta", - }, "account_id": { Type: schema.TypeInt, Computed: true, @@ -474,6 +474,10 @@ func dataSourceImageListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, "deleted_time": { Type: schema.TypeInt, Computed: true, @@ -550,6 +554,10 @@ func dataSourceImageListSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Name of the rescue disk", }, + "network_interface_naming": { + Type: schema.TypeString, + Computed: true, + }, "password": { Type: schema.TypeString, Computed: true, @@ -668,18 +676,6 @@ func dataSourceImageSchemaMake() map[string]*schema.Schema { Computed: true, Description: "unc path", }, - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "meta": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Description: "meta", - }, "account_id": { Type: schema.TypeInt, Computed: true, @@ -736,6 +732,10 @@ func dataSourceImageSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, "deleted_time": { Type: schema.TypeInt, Computed: true, @@ -807,6 +807,10 @@ func dataSourceImageSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Name of the rescue disk", }, + "network_interface_naming": { + Type: schema.TypeString, + Computed: true, + }, "password": { Type: schema.TypeString, Computed: true, @@ -1173,9 +1177,15 @@ func resourceImageSchemaMake() map[string]*schema.Schema { }, "url": { Type: schema.TypeString, - Required: true, + Optional: true, + Computed: true, Description: "URL where to download media from", }, + "file_path": { + Type: schema.TypeString, + Optional: true, + Description: "path to image file", + }, "gid": { Type: schema.TypeInt, Required: true, @@ -1193,7 +1203,8 @@ func resourceImageSchemaMake() map[string]*schema.Schema { }, "drivers": { Type: schema.TypeList, - Required: true, + Optional: true, + Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, @@ -1205,6 +1216,13 @@ func resourceImageSchemaMake() map[string]*schema.Schema { Computed: true, Description: "Does this machine supports hot resize", }, + "network_interface_naming": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"eth", "ens"}, true), + Description: "select a network interface naming pattern for your Linux machine. eth - onboard, ens - pci slot naming", + }, "username": { Type: schema.TypeString, Optional: true, @@ -1299,23 +1317,18 @@ func resourceImageSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Optional: true, }, + "accounts": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "unc_path": { Type: schema.TypeString, Computed: true, Description: "unc path", }, - "ckey": { - Type: schema.TypeString, - Computed: true, - }, - "meta": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - Description: "meta", - }, "acl": { Type: schema.TypeList, Computed: true, @@ -1350,6 +1363,10 @@ func resourceImageSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, "image_id": { Type: schema.TypeInt, Computed: true, @@ -1716,3 +1733,565 @@ func resourceVirtualImageSchemaMake() map[string]*schema.Schema { }, } } + +func resourceImageFromBlankComputeSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "compute_id": { + Type: schema.TypeInt, + Required: true, + Description: "Compute Id", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the rescue disk", + }, + "boot_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true), + Description: "Boot type of image BIOS or UEFI", + }, + "image_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "other"}, true), + Description: "Image type linux, windows or other", + }, + + "username": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional username for the image", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional password for the image", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "AccountId to make the image exclusive", + }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "storage endpoint provider ID", + }, + "pool_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "pool for image create", + }, + "hot_resize": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this machine supports hot resize", + }, + "async_mode": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "create an image in async/sync mode", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the image", + }, + "bootable": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this image boot OS", + }, + "enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "computeci_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "enabled_stacks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "shared_with": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "reason": { + Type: schema.TypeString, + Optional: true, + }, + "accounts": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "network_interface_naming": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"eth", "ens"}, true), + Description: "select a network interface naming pattern for your Linux machine. eth - onboard, ens - pci slot naming", + }, + + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true}, + "type": { + Type: schema.TypeString, + Computed: true}, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "architecture": { + Type: schema.TypeString, + Computed: true, + }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "drivers": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "history": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "last_modified": { + Type: schema.TypeInt, + Computed: true, + }, + "link_to": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "provider_name": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "rescuecd": { + Type: schema.TypeBool, + Computed: true, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "url": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + } +} + +func resourceImageFromPlatformDiskSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Required: true, + Description: "Disk Id", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of the rescue disk", + }, + "boot_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true), + Description: "Boot type of image BIOS or UEFI", + }, + "image_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "other"}, true), + Description: "Image type linux, windows or other", + }, + "architecture": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{"X86_64", "PPC64_LE"}, true), + Description: "Image type linux, windows or other", + }, + + "username": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional username for the image", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Optional password for the image", + }, + "account_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "AccountId to make the image exclusive", + }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "storage endpoint provider ID", + }, + "drivers": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + StateFunc: statefuncs.StateFuncToUpper, + ValidateFunc: validation.StringInSlice([]string{"SVA_KVM_X86", "KVM_X86", "KVM_PPC"}, false), // observe case while validating + Type: schema.TypeString, + }, + Description: "List of types of compute suitable for image. Example: [ \"KVM_X86\" ]", + }, + "pool_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "pool for image create", + }, + "hot_resize": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this machine supports hot resize", + }, + "async_mode": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "create an image in async/sync mode", + }, + "permanently": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "whether to completely delete the image", + }, + "bootable": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Does this image boot OS", + }, + "enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "computeci_id": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "enabled_stacks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "shared_with": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "reason": { + Type: schema.TypeString, + Optional: true, + }, + "accounts": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "network_interface_naming": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{"eth", "ens"}, true), + Description: "select a network interface naming pattern for your Linux machine. eth - onboard, ens - pci slot naming", + }, + + "image_id": { + Type: schema.TypeInt, + Computed: true, + }, + "unc_path": { + Type: schema.TypeString, + Computed: true, + }, + "acl": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "explicit": { + Type: schema.TypeBool, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "right": { + Type: schema.TypeString, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true}, + "type": { + Type: schema.TypeString, + Computed: true}, + "user_group_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "cd_presented_to": { + Type: schema.TypeString, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "desc": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "history": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "timestamp": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "last_modified": { + Type: schema.TypeInt, + Computed: true, + }, + "link_to": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "provider_name": { + Type: schema.TypeString, + Computed: true, + }, + "purge_attempts": { + Type: schema.TypeInt, + Computed: true, + }, + "present_to": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_id": { + Type: schema.TypeString, + Computed: true, + }, + "res_name": { + Type: schema.TypeString, + Computed: true, + }, + "rescuecd": { + Type: schema.TypeBool, + Computed: true, + }, + "size": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tech_status": { + Type: schema.TypeString, + Computed: true, + }, + "url": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + } +} diff --git a/internal/service/cloudbroker/image/utility_image_list.go b/internal/service/cloudbroker/image/utility_image_list.go index 8320e17..44d97ee 100644 --- a/internal/service/cloudbroker/image/utility_image_list.go +++ b/internal/service/cloudbroker/image/utility_image_list.go @@ -1,98 +1,101 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 image - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*image.ListImages, error) { - c := m.(*controller.ControllerCfg) - req := image.ListRequest{} - - if sepId, ok := d.GetOk("sep_id"); ok { - req.SepID = uint64(sepId.(int)) - } - if byId, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(byId.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - if architecture, ok := d.GetOk("architecture"); ok { - req.Architecture = architecture.(string) - } - if typeImage, ok := d.GetOk("type_image"); ok { - req.TypeImage = typeImage.(string) - } - if imageSize, ok := d.GetOk("image_size"); ok { - req.ImageSize = uint64(imageSize.(int)) - } - if sepName, ok := d.GetOk("sep_name"); ok { - req.SEPName = sepName.(string) - } - if pool, ok := d.GetOk("pool"); ok { - req.Pool = pool.(string) - } - if public, ok := d.GetOk("public"); ok { - req.Public = public.(bool) - } - if hotResize, ok := d.GetOk("hot_resize"); ok { - req.HotResize = hotResize.(bool) - } - if bootable, ok := d.GetOk("bootable"); ok { - req.Bootable = bootable.(bool) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - - log.Debugf("utilityImageListCheckPresence: load image list") - imageList, err := c.CloudBroker().Image().List(ctx, req) - if err != nil { - return nil, err - } - - return imageList, nil -} +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 image + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityImageListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*image.ListImages, error) { + c := m.(*controller.ControllerCfg) + req := image.ListRequest{} + + if sepId, ok := d.GetOk("sep_id"); ok { + req.SepID = uint64(sepId.(int)) + } + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byId.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if architecture, ok := d.GetOk("architecture"); ok { + req.Architecture = architecture.(string) + } + if typeImage, ok := d.GetOk("type_image"); ok { + req.TypeImage = typeImage.(string) + } + if imageSize, ok := d.GetOk("image_size"); ok { + req.ImageSize = uint64(imageSize.(int)) + } + if sepName, ok := d.GetOk("sep_name"); ok { + req.SEPName = sepName.(string) + } + if pool, ok := d.GetOk("pool"); ok { + req.Pool = pool.(string) + } + if public, ok := d.GetOk("public"); ok { + req.Public = public.(bool) + } + if hotResize, ok := d.GetOk("hot_resize"); ok { + req.HotResize = hotResize.(bool) + } + if bootable, ok := d.GetOk("bootable"); ok { + req.Bootable = bootable.(bool) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + + log.Debugf("utilityImageListCheckPresence: load image list") + imageList, err := c.CloudBroker().Image().List(ctx, req) + if err != nil { + return nil, err + } + + return imageList, nil +} diff --git a/internal/service/cloudbroker/image/utility_image_list_stacks.go b/internal/service/cloudbroker/image/utility_image_list_stacks.go index 651d996..a85451b 100644 --- a/internal/service/cloudbroker/image/utility_image_list_stacks.go +++ b/internal/service/cloudbroker/image/utility_image_list_stacks.go @@ -1,73 +1,76 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 image - -import ( - "context" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityImageListStacksCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*image.ListStacks, error) { - c := m.(*controller.ControllerCfg) - req := image.ListStacksRequest{ - ImageID: uint64(d.Get("image_id").(int)), - } - - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if status, ok := d.GetOk("status"); ok { - req.Status = status.(string) - } - if typeImage, ok := d.GetOk("type_image"); ok { - req.Type = typeImage.(string) - } - - log.Debugf("utilityImageListStacksCheckPresence: load image list") - imageListStacks, err := c.CloudBroker().Image().ListStacks(ctx, req) - if err != nil { - return nil, err - } - - return imageListStacks, nil -} +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 image + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/image" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityImageListStacksCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*image.ListStacks, error) { + c := m.(*controller.ControllerCfg) + req := image.ListStacksRequest{ + ImageID: uint64(d.Get("image_id").(int)), + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if typeImage, ok := d.GetOk("type_image"); ok { + req.Type = typeImage.(string) + } + + log.Debugf("utilityImageListStacksCheckPresence: load image list") + imageListStacks, err := c.CloudBroker().Image().ListStacks(ctx, req) + if err != nil { + return nil, err + } + + return imageListStacks, nil +} diff --git a/internal/service/cloudbroker/image/utility_resource_create.go b/internal/service/cloudbroker/image/utility_resource_create.go index 2220c40..adeb99e 100644 --- a/internal/service/cloudbroker/image/utility_resource_create.go +++ b/internal/service/cloudbroker/image/utility_resource_create.go @@ -40,10 +40,10 @@ import ( "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic" ) -func SyncCreateRequest(ctx context.Context, d *schema.ResourceData, m interface{}) (image.SyncCreateRequest, error) { +func SyncCreateRequest(ctx context.Context, d *schema.ResourceData, m interface{}, url string) (image.SyncCreateRequest, error) { req := image.SyncCreateRequest{ Name: d.Get("name").(string), - URL: d.Get("url").(string), + URL: url, BootType: d.Get("boot_type").(string), ImageType: d.Get("image_type").(string), } @@ -56,11 +56,13 @@ func SyncCreateRequest(ctx context.Context, d *schema.ResourceData, m interface{ req.GID = uint64(d.Get("gid").(int)) - drivers := []string{} - for _, driver := range d.Get("drivers").([]interface{}) { - drivers = append(drivers, driver.(string)) + if _, ok := d.GetOk("drivers"); ok { + drivers := []string{} + for _, driver := range d.Get("drivers").([]interface{}) { + drivers = append(drivers, driver.(string)) + } + req.Drivers = drivers } - req.Drivers = drivers if hotresize, ok := d.GetOk("hot_resize"); ok { req.HotResize = hotresize.(bool) @@ -92,13 +94,16 @@ func SyncCreateRequest(ctx context.Context, d *schema.ResourceData, m interface{ if bootable, ok := d.GetOk("bootable"); ok { req.Bootable = bootable.(bool) } + if networkInterfaceNaming, ok := d.GetOk("network_interface_naming"); ok { + req.NetworkInterfaceNaming = networkInterfaceNaming.(string) + } return req, nil } -func CreateRequest(ctx context.Context, d *schema.ResourceData, m interface{}) (image.CreateRequest, error) { +func CreateRequest(ctx context.Context, d *schema.ResourceData, m interface{}, url string) (image.CreateRequest, error) { req := image.CreateRequest{ Name: d.Get("name").(string), - URL: d.Get("url").(string), + URL: url, BootType: d.Get("boot_type").(string), ImageType: d.Get("image_type").(string), } @@ -111,11 +116,13 @@ func CreateRequest(ctx context.Context, d *schema.ResourceData, m interface{}) ( req.GID = uint64(d.Get("gid").(int)) - drivers := []string{} - for _, driver := range d.Get("drivers").([]interface{}) { - drivers = append(drivers, driver.(string)) + if _, ok := d.GetOk("drivers"); ok { + drivers := []string{} + for _, driver := range d.Get("drivers").([]interface{}) { + drivers = append(drivers, driver.(string)) + } + req.Drivers = drivers } - req.Drivers = drivers if hotresize, ok := d.GetOk("hot_resize"); ok { req.HotResize = hotresize.(bool) @@ -147,5 +154,8 @@ func CreateRequest(ctx context.Context, d *schema.ResourceData, m interface{}) ( if bootable, ok := d.GetOk("bootable"); ok { req.Bootable = bootable.(bool) } + if networkInterfaceNaming, ok := d.GetOk("network_interface_naming"); ok { + req.NetworkInterfaceNaming = networkInterfaceNaming.(string) + } return req, nil } diff --git a/internal/service/cloudbroker/k8ci/schema.go b/internal/service/cloudbroker/k8ci/schema.go index 1a2a251..57b5288 100644 --- a/internal/service/cloudbroker/k8ci/schema.go +++ b/internal/service/cloudbroker/k8ci/schema.go @@ -158,6 +158,11 @@ func dataSourceK8CIListSchemaMake() map[string]*schema.Schema { Default: false, Description: "Include deleted k8cis in result", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -283,6 +288,11 @@ func dataSourceK8CIListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by network plugin", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudbroker/k8ci/utility_k8ci_list.go b/internal/service/cloudbroker/k8ci/utility_k8ci_list.go index 85101af..9c976c6 100644 --- a/internal/service/cloudbroker/k8ci/utility_k8ci_list.go +++ b/internal/service/cloudbroker/k8ci/utility_k8ci_list.go @@ -68,6 +68,9 @@ func utilityK8CIListCheckPresence(ctx context.Context, d *schema.ResourceData, m if include_disabled, ok := d.GetOk("include_disabled"); ok { req.IncludeDisabled = include_disabled.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/k8ci/utility_k8ci_list_deleted.go b/internal/service/cloudbroker/k8ci/utility_k8ci_list_deleted.go index 86d123a..f530e3e 100644 --- a/internal/service/cloudbroker/k8ci/utility_k8ci_list_deleted.go +++ b/internal/service/cloudbroker/k8ci/utility_k8ci_list_deleted.go @@ -62,6 +62,9 @@ func utilityK8CIListDeletedCheckPresence(ctx context.Context, d *schema.Resource if network_plugin, ok := d.GetOk("network_plugin"); ok { req.NetworkPlugins = network_plugin.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/k8s/resource_k8s_cp.go b/internal/service/cloudbroker/k8s/resource_k8s_cp.go index 609ac3a..57551fe 100644 --- a/internal/service/cloudbroker/k8s/resource_k8s_cp.go +++ b/internal/service/cloudbroker/k8s/resource_k8s_cp.go @@ -166,6 +166,23 @@ func resourceK8sCPCreate(ctx context.Context, d *schema.ResourceData, m interfac createReq.Description = desc.(string) } + if lbSysctlParams, ok := d.GetOk("lb_sysctl_params"); ok { + syscrlSliceMaps := lbSysctlParams.([]map[string]string) + res := make([]map[string]interface{}, 0, len(syscrlSliceMaps)) + for _, syscrlMap := range syscrlSliceMaps { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + createReq.LbSysctlParams = res + } + resp, err := c.CloudBroker().K8S().Create(ctx, createReq) if err != nil { return diag.FromErr(err) @@ -188,7 +205,11 @@ func resourceK8sCPCreate(ctx context.Context, d *schema.ResourceData, m interfac return diag.FromErr(fmt.Errorf("cannot create k8s instance: %v", task.Error)) } - d.SetId(strconv.Itoa(int(task.Result))) + id, err := task.Result.ID() + if err != nil { + return diag.FromErr(err) + } + d.SetId(strconv.Itoa(id)) break } @@ -387,6 +408,13 @@ func resourceK8sCPUpdate(ctx context.Context, d *schema.ResourceData, m interfac } } + if d.HasChange("lb_sysctl_params") && d.Get("with_lb").(bool) { + err := handleUpdateLbSysctlParams(ctx, d, c, k8sData) + if err != nil { + return diag.FromErr(err) + } + } + return nil } @@ -399,7 +427,9 @@ func resourceK8sCPDelete(ctx context.Context, d *schema.ResourceData, m interfac } c := m.(*controller.ControllerCfg) - req := k8s.DeleteRequest{K8SID: k8sData.ID} + req := k8s.DeleteRequest{ + K8SID: k8sData.ID, + } if val, ok := d.GetOk("permanently"); ok { req.Permanently = val.(bool) @@ -553,3 +583,28 @@ func handleStart(ctx context.Context, c *controller.ControllerCfg, start bool, k } return nil } + +func handleUpdateLbSysctlParams(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg, k8sData *k8s.RecordK8S) error { + + lbSysctlParams := d.Get("lb_sysctl_params").([]map[string]string) + res := make([]map[string]interface{}, 0, len(lbSysctlParams)) + for _, syscrlMap := range lbSysctlParams { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + + req := lb.UpdateSysctParamsRequest{ + LBID: k8sData.LBID, + SysctlParams: res, + } + + _, err := c.CloudBroker().LB().UpdateSysctlParams(ctx, req) + return err +} diff --git a/internal/service/cloudbroker/k8s/resource_k8s_wg.go b/internal/service/cloudbroker/k8s/resource_k8s_wg.go index 75bc440..07963ef 100644 --- a/internal/service/cloudbroker/k8s/resource_k8s_wg.go +++ b/internal/service/cloudbroker/k8s/resource_k8s_wg.go @@ -115,7 +115,12 @@ func resourceK8sWgCreate(ctx context.Context, d *schema.ResourceData, m interfac if task.Error != "" { return diag.FromErr(fmt.Errorf("cannot create k8sWg instance: %v", task.Error)) } - d.SetId(fmt.Sprintf("%d#%d", d.Get("k8s_id").(int), int(task.Result))) + + wgId, err := task.Result.ID() + if err != nil { + return diag.FromErr(err) + } + d.SetId(fmt.Sprintf("%d#%d", d.Get("k8s_id").(int), wgId)) break } diff --git a/internal/service/cloudbroker/k8s/schema.go b/internal/service/cloudbroker/k8s/schema.go index 3dba393..6c31296 100644 --- a/internal/service/cloudbroker/k8s/schema.go +++ b/internal/service/cloudbroker/k8s/schema.go @@ -140,6 +140,11 @@ func dataSourceK8sListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by Tech Status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -228,7 +233,7 @@ func dataSourceK8sListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, - "name": { + "k8s_name": { Type: schema.TypeString, Computed: true, }, @@ -447,6 +452,11 @@ func dataSourceK8sListSchemaMake() map[string]*schema.Schema { Default: false, Description: "Include deleted k8s in result", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1337,8 +1347,8 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.IntInSlice([]int{1, 3}), - Description: "Number of VMs to create. Can be either 1 or 3", + ValidateFunc: validation.IntInSlice([]int{1, 3, 5}), + Description: "Number of VMs to create. Can be either 1 or 3 or 5", }, "cpu": { Type: schema.TypeInt, @@ -1351,8 +1361,8 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Optional: true, Computed: true, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), Description: "Node RAM in MB.", }, @@ -1429,6 +1439,17 @@ func resourceK8sCPSchemaMake() map[string]*schema.Schema { Optional: true, Description: "insert ssl certificate in x509 pem format", }, + "lb_sysctl_params": { + Type: schema.TypeList, + Optional: true, + Description: "Custom sysctl values for Load Balancer instance. Applied on boot.", + Elem: &schema.Schema{ + Type: schema.TypeMap, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, "extnet_id": { Type: schema.TypeInt, Optional: true, @@ -1743,12 +1764,12 @@ func resourceK8sWgSchemaMake() map[string]*schema.Schema { "ram": { Type: schema.TypeInt, Optional: true, - Default: 1024, + Computed: true, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), - Description: "Worker node RAM in MB.", + Description: "Node RAM in MB.", }, "disk": { Type: schema.TypeInt, diff --git a/internal/service/cloudbroker/k8s/utility_k8s_list.go b/internal/service/cloudbroker/k8s/utility_k8s_list.go index 3491a2a..509587e 100644 --- a/internal/service/cloudbroker/k8s/utility_k8s_list.go +++ b/internal/service/cloudbroker/k8s/utility_k8s_list.go @@ -70,6 +70,9 @@ func utilityK8sListCheckPresence(ctx context.Context, d *schema.ResourceData, m if includeDeleted, ok := d.GetOk("include_deleted"); ok { req.IncludeDeleted = includeDeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/k8s/utility_k8s_list_deleted.go b/internal/service/cloudbroker/k8s/utility_k8s_list_deleted.go index 4e5a25d..6a2c743 100644 --- a/internal/service/cloudbroker/k8s/utility_k8s_list_deleted.go +++ b/internal/service/cloudbroker/k8s/utility_k8s_list_deleted.go @@ -64,6 +64,9 @@ func utilityK8sListDeletedCheckPresence(ctx context.Context, d *schema.ResourceD if tech_status, ok := d.GetOk("tech_status"); ok { req.TechStatus = tech_status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/kvmvm/data_source_compute.go b/internal/service/cloudbroker/kvmvm/data_source_compute.go index e3d8d09..8f5eb41 100644 --- a/internal/service/cloudbroker/kvmvm/data_source_compute.go +++ b/internal/service/cloudbroker/kvmvm/data_source_compute.go @@ -33,7 +33,6 @@ package kvmvm import ( "context" - "strconv" // "net/url" "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" @@ -50,8 +49,10 @@ func dataSourceComputeRead(ctx context.Context, d *schema.ResourceData, m interf return diag.FromErr(err) } - d.SetId(strconv.Itoa(int(compFacts.ID))) - flattenDataCompute(d, compFacts) + if err = flattenDataCompute(d, compFacts); err != nil { + return diag.FromErr(err) + } + return nil } diff --git a/internal/service/cloudbroker/kvmvm/flattens.go b/internal/service/cloudbroker/kvmvm/flattens.go index 41534ed..abf5a3a 100644 --- a/internal/service/cloudbroker/kvmvm/flattens.go +++ b/internal/service/cloudbroker/kvmvm/flattens.go @@ -1,8 +1,8 @@ package kvmvm import ( - "context" "encoding/json" + "fmt" "sort" "strconv" @@ -12,7 +12,7 @@ import ( "repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens" ) -func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec *compute.RecordCompute) error { +func flattenCompute(d *schema.ResourceData, computeRec *compute.RecordCompute) error { log.Debugf("flattenCompute: ID %d, RG ID %d", computeRec.ID, computeRec.RGID) customFields, _ := json.Marshal(computeRec.CustomFields) @@ -49,7 +49,7 @@ func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec *com d.Set("deleted_time", computeRec.DeletedTime) d.Set("description", computeRec.Description) d.Set("devices", string(devices)) - err := d.Set("disks", flattenComputeDisks(ctx, d, computeRec.Disks, d.Get("extra_disks").(*schema.Set).List(), bootDisk.ID)) + err := d.Set("disks", flattenComputeDisks(computeRec.Disks, d.Get("disks").([]interface{}), d.Get("extra_disks").(*schema.Set).List(), bootDisk.ID)) if err != nil { return err } @@ -58,18 +58,26 @@ func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec *com d.Set("guid", computeRec.GUID) d.Set("compute_id", computeRec.ID) d.Set("image_id", computeRec.ImageID) + d.Set("image_name", computeRec.ImageName) d.Set("interfaces", flattenInterfaces(computeRec.Interfaces)) d.Set("lock_status", computeRec.LockStatus) d.Set("manager_id", computeRec.ManagerID) d.Set("manager_type", computeRec.ManagerType) d.Set("migrationjob", computeRec.MigrationJob) d.Set("milestones", computeRec.Milestones) + d.Set("natable_vins_id", computeRec.NatableVINSID) + d.Set("natable_vins_ip", computeRec.NatableVINSIP) + d.Set("natable_vins_name", computeRec.NatableVINSName) + d.Set("natable_vins_network", computeRec.NatableVINSNetwork) + d.Set("natable_vins_network_name", computeRec.NatableVINSNetworkName) d.Set("need_reboot", computeRec.NeedReboot) + d.Set("numa_node_id", computeRec.NumaNodeId) d.Set("os_users", flattenOSUsers(computeRec.OSUsers)) d.Set("pinned", computeRec.Pinned) d.Set("reference_id", computeRec.ReferenceID) d.Set("registered", computeRec.Registered) d.Set("res_name", computeRec.ResName) + d.Set("reserved_node_cpus", computeRec.ReservedNodeCpus) d.Set("rg_name", computeRec.RGName) d.Set("snap_sets", flattenSnapSets(computeRec.SnapSets)) d.Set("stack_id", computeRec.StackID) @@ -85,7 +93,7 @@ func flattenCompute(ctx context.Context, d *schema.ResourceData, computeRec *com d.Set("user_managed", computeRec.UserManaged) d.Set("vgpus", computeRec.VGPUs) d.Set("virtual_image_id", computeRec.VirtualImageID) - + d.Set("virtual_image_name", computeRec.VirtualImageName) return nil } @@ -140,6 +148,7 @@ func flattenInterfaces(ifaces compute.ListInterfaces) []map[string]interface{} { "conn_id": iface.ConnID, "conn_type": iface.ConnType, "def_gw": iface.DefGW, + "enabled": iface.Enabled, "flip_group_id": iface.FLIPGroupID, "guid": iface.GUID, "ip_address": iface.IPAddress, @@ -149,6 +158,7 @@ func flattenInterfaces(ifaces compute.ListInterfaces) []map[string]interface{} { "net_id": iface.NetID, "netmask": iface.NetMask, "net_type": iface.NetType, + "node_id": iface.NodeID, "pci_slot": iface.PCISlot, "qos": flattenQOS(iface.QOS), "target": iface.Target, @@ -171,20 +181,30 @@ func flattenQOS(qos compute.QOS) []map[string]interface{} { } } -func flattenComputeDisks(ctx context.Context, d *schema.ResourceData, disksList compute.ListDisks, extraDisks []interface{}, bootDiskId uint64) []map[string]interface{} { +func flattenComputeDisks(disksList compute.ListDisks, disksBlocks, extraDisks []interface{}, bootDiskId uint64) []map[string]interface{} { res := make([]map[string]interface{}, 0, len(disksList)) + + if len(disksBlocks) == 0 { + return res + } + + sort.Slice(disksList, func(i, j int) bool { + return disksList[i].ID < disksList[j].ID + }) + + indexDataDisks := 0 + for _, disk := range disksList { if disk.ID == bootDiskId || findInExtraDisks(uint(disk.ID), extraDisks) { //skip main bootdisk and extraDisks continue } - permanently, ok := ctx.Value(DiskKey(strconv.Itoa(int(disk.ID)))).(bool) // get permamently from Create or Update context - if !ok { - permanently = getPermanentlyByDiskID(d, disk.ID) // get permanently from state when Read is not after Create/Update - } + pernamentlyValue := disksBlocks[indexDataDisks].(map[string]interface{})["permanently"].(bool) + nodeIds := disksBlocks[indexDataDisks].(map[string]interface{})["node_ids"].(*schema.Set) temp := map[string]interface{}{ "disk_name": disk.Name, + "node_ids": nodeIds, "size": disk.SizeMax, "sep_id": disk.SEPID, "disk_type": disk.Type, @@ -195,29 +215,13 @@ func flattenComputeDisks(ctx context.Context, d *schema.ResourceData, disksList "shareable": disk.Shareable, "size_used": disk.SizeUsed, "size_max": disk.SizeMax, - "permanently": permanently, + "permanently": pernamentlyValue, } res = append(res, temp) + indexDataDisks++ } - sort.Slice(res, func(i, j int) bool { - return res[i]["disk_id"].(uint64) < res[j]["disk_id"].(uint64) - }) - return res -} -// getPermanentlyByDiskID gets permanently value of specific disk (by diskId) from disks current state -func getPermanentlyByDiskID(d *schema.ResourceData, diskId uint64) bool { - disks := d.Get("disks").([]interface{}) - - for _, diskItem := range disks { - disk := diskItem.(map[string]interface{}) - if uint64(disk["disk_id"].(int)) == diskId { - return disk["permanently"].(bool) - } - } - - log.Infof("getPermanentlyByDiskID: disk with id %d not found in state", diskId) - return false + return res } func findInExtraDisks(diskId uint, extraDisks []interface{}) bool { @@ -262,7 +266,7 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{} "arch": computeItem.Arch, "cd_image_id": computeItem.CdImageId, "boot_order": computeItem.BootOrder, - "boot_disk_size": computeItem.BootDiskSize, + "bootdisk_size": computeItem.BootDiskSize, "clone_reference": computeItem.CloneReference, "clones": computeItem.Clones, "computeci_id": computeItem.ComputeCIID, @@ -278,7 +282,9 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{} "driver": computeItem.Driver, "gid": computeItem.GID, "guid": computeItem.GUID, + "hp_backed": computeItem.HPBacked, "compute_id": computeItem.ID, + "cpu_pin": computeItem.CPUPin, "image_id": computeItem.ImageID, "interfaces": flattenInterfaces(computeItem.Interfaces), "lock_status": computeItem.LockStatus, @@ -288,12 +294,15 @@ func flattenComputeList(computes *compute.ListComputes) []map[string]interface{} "milestones": computeItem.Milestones, "name": computeItem.Name, "need_reboot": computeItem.NeedReboot, + "numa_affinity": computeItem.NumaAffinity, + "numa_node_id": computeItem.NumaNodeId, "os_users": flattenOSUsers(computeItem.OSUsers), "pinned": computeItem.Pinned, "ram": computeItem.RAM, "reference_id": computeItem.ReferenceID, "registered": computeItem.Registered, "res_name": computeItem.ResName, + "reserved_node_cpus": computeItem.ReservedNodeCpus, "rg_id": computeItem.RGID, "rg_name": computeItem.RGName, "snap_sets": flattenSnapSets(computeItem.SnapSets), @@ -503,23 +512,32 @@ func flattenPCIDevice(deviceList []compute.ItemPCIDevice) []map[string]interface return res } -func flattenVGPU(m []interface{}) []string { - var output []string - for _, item := range m { - switch d := item.(type) { - case string: - output = append(output, d) - case int: - output = append(output, strconv.Itoa(d)) - case int64: - output = append(output, strconv.FormatInt(d, 10)) - case float64: - output = append(output, strconv.FormatInt(int64(d), 10)) - default: - output = append(output, "") +func flattenVGPU(vgpuList []compute.ItemVGPU) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vgpuList)) + for _, dev := range vgpuList { + temp := map[string]interface{}{ + "account_id": dev.AccountID, + "created_time": dev.CreatedTime, + "deleted_time": dev.DeletedTime, + "gid": dev.GID, + "guid": dev.GUID, + "vgpu_id": dev.ID, + "last_claimed_by": dev.LastClaimedBy, + "last_update_time": dev.LastUpdateTime, + "mode": dev.Mode, + "pci_slot": dev.PCISlot, + "pgpuid": dev.PGPUID, + "profile_id": dev.ProfileID, + "ram": dev.RAM, + "reference_id": dev.ReferenceID, + "rg_id": dev.RGID, + "status": dev.Status, + "type": dev.Type, + "vm_id": dev.VMID, } + res = append(res, temp) } - return output + return res } func flattenNodes(m []interface{}) []string { @@ -553,6 +571,8 @@ func flattenDataCompute(d *schema.ResourceData, compFacts *compute.RecordCompute customFields, _ := json.Marshal(compFacts.CustomFields) devices, _ := json.Marshal(compFacts.Devices) userData, _ := json.Marshal(compFacts.Userdata) + // general fields setting + d.SetId(fmt.Sprintf("%d", compFacts.ID)) d.Set("account_id", compFacts.AccountID) d.Set("account_name", compFacts.AccountName) d.Set("acl", flattenListACLInterface(compFacts.ACL)) @@ -562,11 +582,11 @@ func flattenDataCompute(d *schema.ResourceData, compFacts *compute.RecordCompute d.Set("anti_affinity_rules", flattenAffinityRules(compFacts.AntiAffinityRules)) d.Set("arch", compFacts.Arch) d.Set("boot_order", compFacts.BootOrder) - d.Set("boot_disk_size", compFacts.BootDiskSize) d.Set("cd_image_id", compFacts.CdImageId) d.Set("clone_reference", compFacts.CloneReference) d.Set("clones", compFacts.Clones) d.Set("computeci_id", compFacts.ComputeCIID) + d.Set("cpu_pin", compFacts.CPUPin) d.Set("cpus", compFacts.CPUs) d.Set("created_by", compFacts.CreatedBy) d.Set("created_time", compFacts.CreatedTime) @@ -579,7 +599,9 @@ func flattenDataCompute(d *schema.ResourceData, compFacts *compute.RecordCompute d.Set("driver", compFacts.Driver) d.Set("gid", compFacts.GID) d.Set("guid", compFacts.GUID) + d.Set("hp_backed", compFacts.HPBacked) d.Set("image_id", compFacts.ImageID) + d.Set("image_name", compFacts.ImageName) d.Set("interfaces", flattenInterfaces(compFacts.Interfaces)) d.Set("lock_status", compFacts.LockStatus) d.Set("manager_id", compFacts.ManagerID) @@ -587,13 +609,21 @@ func flattenDataCompute(d *schema.ResourceData, compFacts *compute.RecordCompute d.Set("migrationjob", compFacts.MigrationJob) d.Set("milestones", compFacts.Milestones) d.Set("name", compFacts.Name) + d.Set("natable_vins_id", compFacts.NatableVINSID) + d.Set("natable_vins_ip", compFacts.NatableVINSIP) + d.Set("natable_vins_name", compFacts.NatableVINSName) + d.Set("natable_vins_network", compFacts.NatableVINSNetwork) + d.Set("natable_vins_network_name", compFacts.NatableVINSNetworkName) d.Set("need_reboot", compFacts.NeedReboot) + d.Set("numa_affinity", compFacts.NumaAffinity) + d.Set("numa_node_id", compFacts.NumaNodeId) d.Set("os_users", flattenOSUsers(compFacts.OSUsers)) d.Set("pinned", compFacts.Pinned) d.Set("ram", compFacts.RAM) d.Set("reference_id", compFacts.ReferenceID) d.Set("registered", compFacts.Registered) d.Set("res_name", compFacts.ResName) + d.Set("reserved_node_cpus", compFacts.ReservedNodeCpus) d.Set("rg_id", compFacts.RGID) d.Set("rg_name", compFacts.RGName) d.Set("snap_sets", flattenSnapSets(compFacts.SnapSets)) @@ -610,6 +640,15 @@ func flattenDataCompute(d *schema.ResourceData, compFacts *compute.RecordCompute d.Set("user_managed", compFacts.UserManaged) d.Set("vgpus", compFacts.VGPUs) d.Set("virtual_image_id", compFacts.VirtualImageID) + d.Set("virtual_image_name", compFacts.VirtualImageName) + //extra fields setting + bootDisk := findBootDisk(compFacts.Disks) + if bootDisk != nil { + d.Set("boot_disk_size", bootDisk.SizeMax) + d.Set("boot_disk_id", bootDisk.ID) // we may need boot disk ID in resize operations + d.Set("sep_id", bootDisk.SEPID) + d.Set("pool", bootDisk.Pool) + } return nil } @@ -669,6 +708,7 @@ func flattenDisk(diskList compute.ListDisks) []map[string]interface{} { "purge_attempts": disk.PurgeAttempts, "present_to": disk.PresentTo, "purge_time": disk.PurgeTime, + "replication": flattenDiskReplication(disk.Replication), "reality_device_number": disk.RealityDeviceNumber, "reference_id": disk.ReferenceID, "res_id": disk.ResID, @@ -689,6 +729,20 @@ func flattenDisk(diskList compute.ListDisks) []map[string]interface{} { return res } +func flattenDiskReplication(rep compute.ItemReplication) []map[string]interface{} { + res := []map[string]interface{}{ + { + "disk_id": rep.DiskID, + "pool_id": rep.PoolID, + "role": rep.Role, + "self_volume_id": rep.SelfVolumeID, + "storage_id": rep.StorageID, + "volume_id": rep.VolumeID, + }, + } + return res +} + func flattenIOTune(iot compute.IOTune) []map[string]interface{} { res := make([]map[string]interface{}, 0) temp := map[string]interface{}{ diff --git a/internal/service/cloudbroker/kvmvm/resource_check_input_values.go b/internal/service/cloudbroker/kvmvm/resource_check_input_values.go index 71f8e8e..d373b77 100644 --- a/internal/service/cloudbroker/kvmvm/resource_check_input_values.go +++ b/internal/service/cloudbroker/kvmvm/resource_check_input_values.go @@ -2,6 +2,7 @@ package kvmvm import ( "context" + "errors" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -25,12 +26,18 @@ func checkParamsExistence(ctx context.Context, d *schema.ResourceData, c *contro errs = append(errs, netErrs...) } + if disks, ok := d.GetOk("disks"); ok { + if err := ic.IsMoreThanOneDisksTypeB(ctx, disks); err != nil { + errs = append(errs, err) + } + } + return dc.ErrorsToDiagnostics(errs) } func existNetworks(ctx context.Context, d *schema.ResourceData, c *controller.ControllerCfg) []error { var errs []error - var vinsIds, extNetIds []uint64 + var vinsIds, extNetIds, vfpoolIds []uint64 networksIface, ok := d.GetOk("network") if !ok { @@ -46,6 +53,11 @@ func existNetworks(ctx context.Context, d *schema.ResourceData, c *controller.Co vinsIds = append(vinsIds, uint64(network["net_id"].(int))) case "EXTNET": extNetIds = append(extNetIds, uint64(network["net_id"].(int))) + case "VFNIC": + if d.Get("driver").(string) == "KVM_PPC" { + errs = append(errs, errors.New("'VFNIC' net_type is not allowed for driver 'KVM_PPC'")) + } + vfpoolIds = append(vfpoolIds, uint64(network["net_id"].(int))) default: continue } @@ -59,5 +71,9 @@ func existNetworks(ctx context.Context, d *schema.ResourceData, c *controller.Co errs = append(errs, extNetErrs...) } + if vfpoolErrs := ic.ExistVFPools(ctx, vfpoolIds, c); vfpoolErrs != nil { + errs = append(errs, vfpoolErrs...) + } + return errs } diff --git a/internal/service/cloudbroker/kvmvm/resource_compute.go b/internal/service/cloudbroker/kvmvm/resource_compute.go index 6f1829d..27cbc10 100644 --- a/internal/service/cloudbroker/kvmvm/resource_compute.go +++ b/internal/service/cloudbroker/kvmvm/resource_compute.go @@ -49,9 +49,6 @@ import ( "repository.basistech.ru/BASIS/terraform-provider-decort/internal/status" ) -// DiskKey is custom string type to set up context Key for Disk ID -type DiskKey string - func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { log.Debugf("resourceComputeCreate: called for Compute name %q, RG ID %d", d.Get("name").(string), d.Get("rg_id").(int)) c := m.(*controller.ControllerCfg) @@ -114,6 +111,7 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf interfacesPPC := make([]kvmppc.Interface, 0) for _, elem := range ns { netInterfaceVal := elem.(map[string]interface{}) + reqInterface := kvmx86.Interface{ NetType: netInterfaceVal["net_type"].(string), NetID: uint64(netInterfaceVal["net_id"].(int)), @@ -147,6 +145,57 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } + if disks, ok := d.GetOk("disks"); ok { + disksX86 := make([]kvmx86.DataDisk, 0) + disksPPC := make([]kvmppc.DataDisk, 0) + + for _, elem := range disks.([]interface{}) { + diskVal := elem.(map[string]interface{}) + reqDataDisk := kvmx86.DataDisk{ + DiskName: diskVal["disk_name"].(string), + Size: uint64(diskVal["size"].(int)), + } + if sepId, ok := diskVal["sep_id"]; ok { + reqDataDisk.SepID = uint64(sepId.(int)) + } + if pool, ok := diskVal["pool"]; ok { + reqDataDisk.Pool = pool.(string) + } + if desc, ok := diskVal["desc"]; ok { + reqDataDisk.Description = desc.(string) + } + if imageID, ok := diskVal["image_id"]; ok { + reqDataDisk.ImageID = uint64(imageID.(int)) + } + disksX86 = append(disksX86, reqDataDisk) + } + + createReqX86.DataDisks = disksX86 + + for _, elem := range disks.([]interface{}) { + diskVal := elem.(map[string]interface{}) + reqDataDisk := kvmppc.DataDisk{ + DiskName: diskVal["disk_name"].(string), + Size: uint64(diskVal["size"].(int)), + } + if sepId, ok := diskVal["sep_id"]; ok { + reqDataDisk.SepID = uint64(sepId.(int)) + } + if pool, ok := diskVal["pool"]; ok { + reqDataDisk.Pool = pool.(string) + } + if desc, ok := diskVal["desc"]; ok { + reqDataDisk.Description = desc.(string) + } + if imageID, ok := diskVal["image_id"]; ok { + reqDataDisk.ImageID = uint64(imageID.(int)) + } + disksPPC = append(disksPPC, reqDataDisk) + } + + createReqPPC.DataDisks = disksPPC + } + if cloudInit, ok := d.GetOk("cloud_init"); ok { userdata := cloudInit.(string) if userdata != "" && userdata != "applied" { @@ -177,7 +226,13 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf createReqX86.Name = d.Get("name").(string) createReqX86.CPU = uint64(d.Get("cpu").(int)) createReqX86.RAM = uint64(d.Get("ram").(int)) - createReqX86.ImageID = uint64(d.Get("image_id").(int)) + + if image, ok := d.GetOk("image_id"); ok { + createReqX86.ImageID = uint64(image.(int)) + } + if withoutBootDisk, ok := d.GetOk("without_boot_disk"); ok { + createReqX86.WithoutBootDisk = withoutBootDisk.(bool) + } createReqX86.Driver = driver @@ -191,6 +246,12 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf createReqX86.CustomField = val } + if numaAffinity, ok := d.GetOk("numa_affinity"); ok { + createReqX86.NumaAffinity = numaAffinity.(string) + } + createReqX86.CPUPin = d.Get("cpu_pin").(bool) + createReqX86.HPBacked = d.Get("hp_backed").(bool) + log.Debugf("resourceComputeCreate: creating Compute of type KVM VM x86") apiResp, err := c.CloudBroker().KVMX86().Create(ctx, createReqX86) if err != nil { @@ -260,6 +321,9 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } else if ok && !start.(bool) { req := compute.StopRequest{ComputeID: computeId} + if depresent, ok := d.Get("depresent").(bool); ok { + req.Depresent = depresent + } log.Debugf("resourceComputeCreate: stoping Compute ID %d after completing its resource configuration", computeId) if _, err := c.CloudBroker().Compute().Stop(ctx, req); err != nil { warnings.Add(err) @@ -280,45 +344,6 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf } } - if disks, ok := d.GetOk("disks"); ok { - log.Debugf("resourceComputeCreate: Create disks on ComputeID: %d", computeId) - addedDisks := disks.([]interface{}) - if len(addedDisks) > 0 { - for _, disk := range addedDisks { - diskConv := disk.(map[string]interface{}) - req := compute.DiskAddRequest{ - ComputeID: computeId, - DiskName: diskConv["disk_name"].(string), - Size: uint64(diskConv["size"].(int)), - } - - if uint64(diskConv["sep_id"].(int)) != 0 { - req.SepID = uint64(diskConv["sep_id"].(int)) - } - if diskConv["disk_type"].(string) != "" { - req.DiskType = diskConv["disk_type"].(string) - } - if diskConv["pool"].(string) != "" { - req.Pool = diskConv["pool"].(string) - } - if diskConv["desc"].(string) != "" { - req.Description = diskConv["desc"].(string) - } - if diskConv["image_id"].(int) != 0 { - req.ImageID = uint64(diskConv["image_id"].(int)) - } - - diskId, err := c.CloudBroker().Compute().DiskAdd(ctx, req) - if err != nil { - cleanup = true - return diag.FromErr(err) - } - - ctx = context.WithValue(ctx, DiskKey(strconv.Itoa(int(diskId))), diskConv["permanently"].(bool)) - } - } - } - if ars, ok := d.GetOk("affinity_rules"); ok { log.Debugf("resourceComputeCreate: Create affinity rules on ComputeID: %d", computeId) addedAR := ars.([]interface{}) @@ -393,9 +418,11 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf req := compute.PFWAddRequest{ ComputeID: computeId, PublicPortStart: uint64(pfwItem["public_port_start"].(int)), - LocalBasePort: uint64(pfwItem["local_port"].(int)), Proto: pfwItem["proto"].(string), } + if pfwItem["local_port"].(int) != 0 { + req.LocalBasePort = uint64(pfwItem["local_port"].(int)) + } if int64(pfwItem["public_port_end"].(int)) != 0 { req.PublicPortEnd = int64(pfwItem["public_port_end"].(int)) } @@ -494,6 +521,13 @@ func resourceComputeCreate(ctx context.Context, d *schema.ResourceData, m interf warnings.Add(err) } } + + if _, ok := d.GetOk("disks"); ok { + err := utilityComputeCreatePresentDisk(ctx, d, m) + if err != nil { + warnings.Add(err) + } + } } log.Debugf("resourceComputeCreate: new Compute ID %d, name %s creation sequence complete", computeId, d.Get("name").(string)) @@ -560,7 +594,7 @@ func resourceComputeRead(ctx context.Context, d *schema.ResourceData, m interfac d.SetId(strconv.FormatUint(computeRec.ID, 10)) - if err = flattenCompute(ctx, d, computeRec); err != nil { + if err = flattenCompute(d, computeRec); err != nil { return diag.FromErr(err) } @@ -645,7 +679,7 @@ func resourceComputeUpdate(ctx context.Context, d *schema.ResourceData, m interf } } - if d.HasChanges("description", "name") { + if d.HasChanges("description", "name", "numa_affinity", "cpu_pin", "hp_backed") { if err := utilityComputeUpdate(ctx, d, m); err != nil { return diag.FromErr(err) } diff --git a/internal/service/cloudbroker/kvmvm/schema.go b/internal/service/cloudbroker/kvmvm/schema.go index 4fbf50f..4bcc001 100644 --- a/internal/service/cloudbroker/kvmvm/schema.go +++ b/internal/service/cloudbroker/kvmvm/schema.go @@ -146,10 +146,6 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, }, }, - "boot_disk_size": { - Type: schema.TypeInt, - Computed: true, - }, "cd_image_id": { Type: schema.TypeInt, Computed: true, @@ -169,6 +165,10 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cpu_pin": { + Type: schema.TypeBool, + Computed: true, + }, "cpus": { Type: schema.TypeInt, Computed: true, @@ -193,6 +193,12 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "depresent": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "whether to depresent compute disks from node or not", + }, "desc": { Type: schema.TypeString, Computed: true, @@ -398,6 +404,39 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "replication": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool_id": { + Type: schema.TypeString, + Computed: true, + }, + "role": { + Type: schema.TypeString, + Computed: true, + }, + "self_volume_id": { + Type: schema.TypeString, + Computed: true, + }, + "storage_id": { + Type: schema.TypeString, + Computed: true, + }, + "volume_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + Description: "Replication status", + }, "reality_device_number": { Type: schema.TypeInt, Computed: true, @@ -497,10 +536,18 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "hp_backed": { + Type: schema.TypeBool, + Computed: true, + }, "image_id": { Type: schema.TypeInt, Computed: true, }, + "image_name": { + Type: schema.TypeString, + Computed: true, + }, "interfaces": { Type: schema.TypeList, Computed: true, @@ -518,6 +565,10 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, "flip_group_id": { Type: schema.TypeInt, Computed: true, @@ -554,6 +605,10 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, @@ -624,10 +679,38 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "natable_vins_id": { + Type: schema.TypeInt, + Computed: true, + }, + "natable_vins_ip": { + Type: schema.TypeString, + Computed: true, + }, + "natable_vins_name": { + Type: schema.TypeString, + Computed: true, + }, + "natable_vins_network": { + Type: schema.TypeString, + Computed: true, + }, + "natable_vins_network_name": { + Type: schema.TypeString, + Computed: true, + }, "need_reboot": { Type: schema.TypeBool, Computed: true, }, + "numa_affinity": { + Type: schema.TypeString, + Computed: true, + }, + "numa_node_id": { + Type: schema.TypeInt, + Computed: true, + }, "os_users": { Type: schema.TypeList, Computed: true, @@ -672,6 +755,13 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "reserved_node_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "rg_id": { Type: schema.TypeInt, Computed: true, @@ -774,6 +864,27 @@ func dataSourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "virtual_image_name": { + Type: schema.TypeString, + Computed: true, + }, + //extra parameters + "boot_disk_size": { + Type: schema.TypeInt, + Computed: true, + }, + "boot_disk_id": { + Type: schema.TypeInt, + Computed: true, + }, + "sep_id": { + Type: schema.TypeInt, + Computed: true, + }, + "pool": { + Type: schema.TypeString, + Computed: true, + }, } return res } @@ -834,6 +945,11 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Optional: true, }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -977,7 +1093,7 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, }, }, - "boot_disk_size": { + "bootdisk_size": { Type: schema.TypeInt, Computed: true, }, @@ -1000,6 +1116,10 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cpu_pin": { + Type: schema.TypeBool, + Computed: true, + }, "cpus": { Type: schema.TypeInt, Computed: true, @@ -1060,6 +1180,10 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "hp_backed": { + Type: schema.TypeBool, + Computed: true, + }, "compute_id": { Type: schema.TypeInt, Computed: true, @@ -1085,6 +1209,10 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, "flip_group_id": { Type: schema.TypeInt, Computed: true, @@ -1121,6 +1249,10 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, @@ -1195,6 +1327,14 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + "numa_affinity": { + Type: schema.TypeString, + Computed: true, + }, + "numa_node_id": { + Type: schema.TypeInt, + Computed: true, + }, "os_users": { Type: schema.TypeList, Computed: true, @@ -1239,6 +1379,13 @@ func dataSourceComputeListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "reserved_node_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "rg_id": { Type: schema.TypeInt, Computed: true, @@ -1403,6 +1550,11 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by Extnet ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1569,6 +1721,10 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "cpu_pin": { + Type: schema.TypeBool, + Computed: true, + }, "cpus": { Type: schema.TypeInt, Computed: true, @@ -1629,6 +1785,10 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "hp_backed": { + Type: schema.TypeBool, + Computed: true, + }, "compute_id": { Type: schema.TypeInt, Computed: true, @@ -1654,6 +1814,10 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, "flip_group_id": { Type: schema.TypeInt, Computed: true, @@ -1690,6 +1854,10 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, @@ -1764,6 +1932,14 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Computed: true, }, + "numa_affinity": { + Type: schema.TypeString, + Computed: true, + }, + "numa_node_id": { + Type: schema.TypeInt, + Computed: true, + }, "os_users": { Type: schema.TypeList, Computed: true, @@ -1808,6 +1984,13 @@ func dataSourceComputeListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "reserved_node_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "rg_id": { Type: schema.TypeInt, Computed: true, @@ -2351,12 +2534,21 @@ func dataSourceComputePCIDeviceListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by device id", }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, "status": { Type: schema.TypeString, Optional: true, - Computed: true, Description: "Find by status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -2462,6 +2654,11 @@ func dataSourceComputeVGPUListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Include deleted computes. If using field 'status', then includedeleted will be ignored", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -2476,8 +2673,81 @@ func dataSourceComputeVGPUListSchemaMake() map[string]*schema.Schema { "items": { Type: schema.TypeList, Computed: true, - Elem: &schema.Schema{ - Type: schema.TypeString, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeInt, + Computed: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "deleted_time": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "vgpu_id": { + Type: schema.TypeInt, + Computed: true, + }, + "last_claimed_by": { + Type: schema.TypeInt, + Computed: true, + }, + "last_update_time": { + Type: schema.TypeInt, + Computed: true, + }, + "mode": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeInt, + Computed: true, + }, + "pgpuid": { + Type: schema.TypeInt, + Computed: true, + }, + "profile_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "reference_id": { + Type: schema.TypeString, + Computed: true, + }, + "rg_id": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, }, }, "entry_count": { @@ -2527,23 +2797,29 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { "cpu": { Type: schema.TypeInt, Required: true, - ValidateFunc: validation.IntBetween(1, constants.MaxCpusPerCompute), + ValidateFunc: validation.IntBetween(1, constants.MAX_CPUS_PER_COMPUTE), Description: "Number of CPUs to allocate to this compute instance.", }, "ram": { Type: schema.TypeInt, Required: true, ValidateFunc: validation.All( - validation.IntAtLeast(constants.MinRamPerCompute), - validators.DivisibleBy(constants.RAMDivisibility), + validation.IntAtLeast(constants.MIN_RAM_PER_COMPUTE), + validators.DivisibleBy(constants.RAM_DIVISIBILITY), ), Description: "Amount of RAM in MB to allocate to this compute instance.", }, "image_id": { Type: schema.TypeInt, - Required: true, + Optional: true, Description: "ID of the OS image to base this compute instance on.", }, + "without_boot_disk": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "If True, the imageId, bootDisk, sepId, pool parameters are ignored and the compute is created without a boot disk in the stopped state.", + }, "boot_disk_size": { Type: schema.TypeInt, Optional: true, @@ -2610,14 +2886,14 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeSet, Optional: true, MinItems: 1, - MaxItems: constants.MaxNetworksPerCompute, + MaxItems: constants.MAX_NETWORKS_PER_COMPUTE, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "net_type": { Type: schema.TypeString, Required: true, StateFunc: statefuncs.StateFuncToUpper, - ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS"}, false), // observe case while validating + ValidateFunc: validation.StringInSlice([]string{"EXTNET", "VINS", "VFNIC"}, false), // observe case while validating Description: "Type of the network for this connection, either EXTNET or VINS.", }, @@ -2761,6 +3037,13 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Pool name; by default will be chosen automatically", }, + "node_ids": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "desc": { Type: schema.TypeString, Computed: true, @@ -2775,7 +3058,6 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { }, "permanently": { Type: schema.TypeBool, - Computed: true, Optional: true, Description: "Disk deletion status", }, @@ -2807,7 +3089,7 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { "extra_disks": { Type: schema.TypeSet, Optional: true, - MaxItems: constants.MaxExtraDisksPerCompute, + MaxItems: constants.MAX_EXTRA_DISKS_PER_COMPUTE, Elem: &schema.Schema{ Type: schema.TypeInt, }, @@ -2845,7 +3127,7 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { }, "local_port": { Type: schema.TypeInt, - Required: true, + Optional: true, }, "proto": { Type: schema.TypeString, @@ -2993,6 +3275,25 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Optional: true, Default: true, }, + "numa_affinity": { + Type: schema.TypeString, + Optional: true, + Default: "none", + ValidateFunc: validation.StringInSlice([]string{"none", "strict", "loose"}, false), // observe case while validating + Description: "Rule for VM placement with NUMA affinity.", + }, + "cpu_pin": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Run VM on dedicated CPUs. To use this feature, the system must be pre-configured by allocating CPUs on the physical node.", + }, + "hp_backed": { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Use Huge Pages to allocate RAM of the virtual machine. The system must be pre-configured by allocating Huge Pages on the physical node.", + }, // Computed properties "account_id": { Type: schema.TypeInt, @@ -3124,6 +3425,10 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, "flip_group_id": { Type: schema.TypeInt, Computed: true, @@ -3160,6 +3465,10 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, @@ -3206,6 +3515,10 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { }, }, }, + "image_name": { + Type: schema.TypeString, + Computed: true, + }, "lock_status": { Type: schema.TypeString, Computed: true, @@ -3226,10 +3539,34 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "natable_vins_id": { + Type: schema.TypeInt, + Computed: true, + }, + "natable_vins_ip": { + Type: schema.TypeString, + Computed: true, + }, + "natable_vins_name": { + Type: schema.TypeString, + Computed: true, + }, + "natable_vins_network": { + Type: schema.TypeString, + Computed: true, + }, + "natable_vins_network_name": { + Type: schema.TypeString, + Computed: true, + }, "need_reboot": { Type: schema.TypeBool, Computed: true, }, + "numa_node_id": { + Type: schema.TypeInt, + Computed: true, + }, "os_users": { Type: schema.TypeList, Computed: true, @@ -3279,6 +3616,13 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "reserved_node_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, "rg_name": { Type: schema.TypeString, Computed: true, @@ -3355,5 +3699,9 @@ func resourceComputeSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "virtual_image_name": { + Type: schema.TypeString, + Computed: true, + }, } } diff --git a/internal/service/cloudbroker/kvmvm/utility_compute.go b/internal/service/cloudbroker/kvmvm/utility_compute.go index 347b0c5..5c639cb 100644 --- a/internal/service/cloudbroker/kvmvm/utility_compute.go +++ b/internal/service/cloudbroker/kvmvm/utility_compute.go @@ -33,7 +33,9 @@ package kvmvm import ( "context" + "errors" "fmt" + "sort" "strconv" "strings" @@ -98,6 +100,9 @@ func utilityComputeStarted(ctx context.Context, d *schema.ResourceData, m interf if force, ok := d.Get("force_stop").(bool); ok { req.Force = force } + if depresent, ok := d.Get("depresent").(bool); ok { + req.Depresent = depresent + } if _, err := c.CloudBroker().Compute().Stop(ctx, req); err != nil { return err } @@ -193,20 +198,20 @@ func utilityComputeUpdateDisks(ctx context.Context, d *schema.ResourceData, m in addedDisks := make([]interface{}, 0) resizedDisks := make([]interface{}, 0) renamedDisks := make([]interface{}, 0) - - // save permanently in disks based on disk_id to context - for _, diskItemInterface := range d.Get("disks").([]interface{}) { - diskItem := diskItemInterface.(map[string]interface{}) - diskId := diskItem["disk_id"].(int) - permanently := diskItem["permanently"].(bool) - ctx = context.WithValue(ctx, DiskKey(strconv.Itoa(diskId)), permanently) - } + presentNewDisks := make([]interface{}, 0) + presentOldDisks := make([]interface{}, 0) oldDisks, newDisks := d.GetChange("disks") oldConv := oldDisks.([]interface{}) newConv := newDisks.([]interface{}) for _, el := range oldConv { + changeNodes, newEl := isChangeNodesDisk(newConv, el) + if changeNodes { + presentNewDisks = append(presentNewDisks, newEl) + presentOldDisks = append(presentOldDisks, el) + } + // !isRenameDisk(newConv, el) && !isResizeDisk(newConv, el) are required in case two or more disks are being created and their disk_id is the same (=0) if !isContainsDisk(newConv, el) && !isRenameDisk(newConv, el) && !isResizeDisk(newConv, el) { flag := false extraDisks := d.Get("extra_disks").(*schema.Set).List() @@ -246,6 +251,10 @@ func utilityComputeUpdateDisks(ctx context.Context, d *schema.ResourceData, m in 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 @@ -304,12 +313,30 @@ func utilityComputeUpdateDisks(ctx context.Context, d *schema.ResourceData, m in if diskConv["image_id"].(int) != 0 { req.ImageID = uint64(diskConv["image_id"].(int)) } - diskId, err := c.CloudBroker().Compute().DiskAdd(ctx, req) + diskID, err := c.CloudBroker().Compute().DiskAdd(ctx, req) + if err != nil { + return err + } + if nodeIDs, ok := diskConv["node_ids"]; ok { + presentIDs := nodeIDs.(*schema.Set).List() + if len(presentIDs) > 0 { + log.Debugf("resourceComputeUpdate: start presents new disk ID:%d to nodes", diskID) + } + for _, presentID := range presentIDs { + nodeID := uint64(presentID.(int)) + req := disks.PresentRequest{ + DiskID: diskID, + NodeID: nodeID, + } + _, err := c.CloudBroker().Disks().Present(ctx, req) + if err != nil { + return err + } + } + } if err != nil { return err } - - ctx = context.WithValue(ctx, DiskKey(strconv.Itoa(int(diskId))), diskConv["permanently"].(bool)) } } @@ -348,6 +375,43 @@ func utilityComputeUpdateDisks(ctx context.Context, d *schema.ResourceData, m in } } + for i := range presentNewDisks { + newDisk := presentNewDisks[i].(map[string]interface{}) + oldDisk := presentOldDisks[i].(map[string]interface{}) + newArr := newDisk["node_ids"] + oldArr := oldDisk["node_ids"] + diskID := uint64(newDisk["disk_id"].(int)) + presentIDs := (newArr.(*schema.Set).Difference(oldArr.(*schema.Set))).List() + depresentIDs := (oldArr.(*schema.Set).Difference(newArr.(*schema.Set))).List() + for _, presentID := range presentIDs { + nodeID := uint64(presentID.(int)) + + req := disks.PresentRequest{ + DiskID: diskID, + NodeID: nodeID, + } + log.Debugf("resourceComputeUpdate: start presents disk ID:%d from nodes %d", req.DiskID, req.NodeID) + _, err := c.CloudBroker().Disks().Present(ctx, req) + if err != nil { + return err + } + } + + for _, depresentID := range depresentIDs { + nodeID := uint64(depresentID.(int)) + + req := disks.DepresentRequest{ + DiskID: diskID, + NodeID: nodeID, + } + log.Debugf("resourceComputeUpdate: start depresents disk ID:%d from nodes %d", req.DiskID, req.NodeID) + _, err := c.CloudBroker().Disks().Depresent(ctx, req) + if err != nil { + return err + } + } + } + return nil } @@ -398,6 +462,11 @@ func utilityComputeExtraDisksConfigure(ctx context.Context, d *schema.ResourceDa 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 @@ -481,7 +550,7 @@ func findBootDisk(disks compute.ListDisks) *compute.ItemDisk { return &disk } } - return nil + return &compute.ItemDisk{} } func networkSubresIPAddreDiffSupperss(key, oldVal, newVal string, d *schema.ResourceData) bool { @@ -560,8 +629,7 @@ func utilityComputeNetworksConfigure(ctx context.Context, d *schema.ResourceData needStart := false if d.Get("network").(*schema.Set).Len() == 1 || old_set.(*schema.Set).Len() < 1 { - computeId, _ := strconv.ParseUint(d.Id(), 10, 64) - if err := utilityComputeStop(ctx, computeId, m); err != nil { + if err := utilityComputeStop(ctx, d, m); err != nil { apiErrCount++ lastSavedError = err } @@ -624,11 +692,47 @@ func utilityComputeUpdate(ctx context.Context, d *schema.ResourceData, m interfa if d.HasChange("description") { req.Description = d.Get("description").(string) } + 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) + } + // 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") && 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 + } + } + + // perform update if _, err := c.CloudBroker().Compute().Update(ctx, req); err != nil { return err } + // If used to be STARTED, we need to start it after update + if isStopRequired { + if _, err := c.CloudBroker().Compute().Start(ctx, compute.StartRequest{ComputeID: computeId}); err != nil { + return err + } + } + return nil } @@ -865,11 +969,12 @@ func utilityComputeUpdatePFW(ctx context.Context, d *schema.ResourceData, m inte req := compute.PFWDelRequest{ ComputeID: computeId, PublicPortStart: uint64(pfwItem["public_port_start"].(int)), - LocalBasePort: uint64(pfwItem["local_port"].(int)), Proto: pfwItem["proto"].(string), RuleID: uint64(pfwItem["rule_id"].(int)), } - + if pfwItem["local_port"].(int) != 0 { + req.LocalBasePort = uint64(pfwItem["local_port"].(int)) + } if pfwItem["public_port_end"].(int) == -1 { req.PublicPortEnd = req.PublicPortStart } else { @@ -894,10 +999,11 @@ func utilityComputeUpdatePFW(ctx context.Context, d *schema.ResourceData, m inte ComputeID: computeId, PublicPortStart: uint64(pfwItem["public_port_start"].(int)), PublicPortEnd: int64(pfwItem["public_port_end"].(int)), - LocalBasePort: uint64(pfwItem["local_port"].(int)), Proto: pfwItem["proto"].(string), } - + if pfwItem["local_port"].(int) != 0 { + req.LocalBasePort = uint64(pfwItem["local_port"].(int)) + } if pfwItem["reason"].(string) != "" { req.Reason = pfwItem["reason"].(string) } @@ -1033,6 +1139,9 @@ func utilityComputeRollback(ctx context.Context, d *schema.ResourceData, m inter ComputeID: computeId, Force: false, } + if depresent, ok := d.Get("depresent").(bool); ok { + req.Depresent = depresent + } _, err := c.CloudBroker().Compute().Stop(ctx, req) if err != nil { @@ -1194,6 +1303,9 @@ func utilityComputeUpdateImage(ctx context.Context, d *schema.ResourceData, m in 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 { @@ -1261,14 +1373,17 @@ func utilityComputeUpdateCustomFields(ctx context.Context, d *schema.ResourceDat return nil } -func utilityComputeStop(ctx context.Context, computeID uint64, m interface{}) error { +func utilityComputeStop(ctx context.Context, d *schema.ResourceData, m interface{}) error { c := m.(*controller.ControllerCfg) req := compute.StopRequest{ - ComputeID: computeID, - Force: true, + Force: true, + } + req.ComputeID = uint64(d.Get("compute_id").(int)) + if depresent, ok := d.Get("depresent").(bool); ok { + req.Depresent = depresent } - log.Debugf("utilityComputeNetworksConfigure: stopping compute %d", computeID) + log.Debugf("utilityComputeNetworksConfigure: stopping compute %d", req.ComputeID) _, err := c.CloudBroker().Compute().Stop(ctx, req) if err != nil { return err @@ -1288,6 +1403,51 @@ func utilityComputeStart(ctx context.Context, computeID uint64, m interface{}) ( return 0, nil } +func utilityComputeCreatePresentDisk(ctx context.Context, d *schema.ResourceData, m interface{}) error { + c := m.(*controller.ControllerCfg) + var errs error + diskList := d.Get("disks") + presentArr := make([]interface{}, 0) + for _, elem := range diskList.([]interface{}) { + diskVal := elem.(map[string]interface{}) + presentArr = append(presentArr, diskVal["node_ids"]) + } + + computeRec, err := utilityComputeCheckPresence(ctx, d, m) + bootDisk := findBootDisk(computeRec.Disks) + if err != nil { + errs = errors.Join(err) + } + computeDisksIDs := getComputeDiskIDs(computeRec.Disks, d.Get("disks").([]interface{}), d.Get("extra_disks").(*schema.Set).List(), bootDisk.ID) + + for i, diskID := range computeDisksIDs { + if len(presentArr) <= i || presentArr[i] == nil { + continue + } + presentIDs := presentArr[i].(*schema.Set).List() + + if len(presentIDs) > 0 { + log.Debugf("resourceComputeCreate: start presents disk ID:%d to nodes", diskID) + } + + for _, presentID := range presentIDs { + nodeID := uint64(presentID.(int)) + + req := disks.PresentRequest{ + DiskID: diskID.(uint64), + NodeID: nodeID, + } + + _, err := c.CloudBroker().Disks().Present(ctx, req) + if err != nil { + errs = errors.Join(err) + } + } + } + + return errs +} + func isResizeDisk(els []interface{}, el interface{}) bool { for _, elOld := range els { elOldConv := elOld.(map[string]interface{}) @@ -1323,6 +1483,26 @@ func isContainsDisk(els []interface{}, el interface{}) bool { return false } +// isChangeNodesDisk get slice of new disks values and current value disk, +// if need change nodes on disk returns true and new disk value, else return false and nil +func isChangeNodesDisk(els []interface{}, elOld interface{}) (bool, interface{}) { + for _, elNew := range els { + elNewConv := elNew.(map[string]interface{}) + elOldConv := elOld.(map[string]interface{}) + if elOldConv["disk_id"].(int) == elNewConv["disk_id"].(int) { + newArr := elNewConv["node_ids"] + oldArr := elOldConv["node_ids"] + presentID := (newArr.(*schema.Set).Difference(oldArr.(*schema.Set))).List() + depresentID := (oldArr.(*schema.Set).Difference(newArr.(*schema.Set))).List() + if len(presentID) > 0 || len(depresentID) > 0 { + return true, elNew + } + return false, nil + } + } + return false, nil +} + func isContainsAR(els []interface{}, el interface{}) bool { for _, elOld := range els { elOldConv := elOld.(map[string]interface{}) @@ -1337,3 +1517,25 @@ func isContainsAR(els []interface{}, el interface{}) bool { } return false } + +func getComputeDiskIDs(disksList compute.ListDisks, disksBlocks, extraDisks []interface{}, bootDiskId uint64) []interface{} { + res := make([]interface{}, 0) + + if len(disksBlocks) == 0 { + return res + } + + sort.Slice(disksList, func(i, j int) bool { + return disksList[i].ID < disksList[j].ID + }) + + for _, disk := range disksList { + if disk.ID == bootDiskId || findInExtraDisks(uint(disk.ID), extraDisks) { //skip main bootdisk and extraDisks + continue + } + + res = append(res, disk.ID) + } + + return res +} diff --git a/internal/service/cloudbroker/kvmvm/utility_compute_list.go b/internal/service/cloudbroker/kvmvm/utility_compute_list.go index 83d3816..c33acc0 100644 --- a/internal/service/cloudbroker/kvmvm/utility_compute_list.go +++ b/internal/service/cloudbroker/kvmvm/utility_compute_list.go @@ -78,6 +78,9 @@ func utilityDataComputeListCheckPresence(ctx context.Context, d *schema.Resource if includeDeleted, ok := d.GetOk("includedeleted"); ok { req.IncludeDeleted = includeDeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/kvmvm/utility_compute_list_deleted.go b/internal/service/cloudbroker/kvmvm/utility_compute_list_deleted.go index e947709..acb6638 100644 --- a/internal/service/cloudbroker/kvmvm/utility_compute_list_deleted.go +++ b/internal/service/cloudbroker/kvmvm/utility_compute_list_deleted.go @@ -71,6 +71,9 @@ func utilityDataComputeListDeletedCheckPresence(ctx context.Context, d *schema.R if extnetId, ok := d.GetOk("extnet_id"); ok { req.ExtNetID = uint64(extnetId.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/kvmvm/utility_compute_pci_device_list.go b/internal/service/cloudbroker/kvmvm/utility_compute_pci_device_list.go index 36a1311..521809a 100644 --- a/internal/service/cloudbroker/kvmvm/utility_compute_pci_device_list.go +++ b/internal/service/cloudbroker/kvmvm/utility_compute_pci_device_list.go @@ -51,9 +51,15 @@ func utilityComputePCIDeviceListCheckPresence(ctx context.Context, d *schema.Res if devId, ok := d.GetOk("device_id"); ok { req.DevID = uint64(devId.(int)) } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } if status, ok := d.GetOk("status"); ok { req.Status = status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/kvmvm/utility_compute_vgpu_list.go b/internal/service/cloudbroker/kvmvm/utility_compute_vgpu_list.go index 0f5d568..6474eeb 100644 --- a/internal/service/cloudbroker/kvmvm/utility_compute_vgpu_list.go +++ b/internal/service/cloudbroker/kvmvm/utility_compute_vgpu_list.go @@ -57,6 +57,9 @@ func utilityComputeVGPUListCheckPresence(ctx context.Context, d *schema.Resource if includeDeleted, ok := d.GetOk("includedeleted"); ok { req.IncludeDeleted = includeDeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/lb/flattens.go b/internal/service/cloudbroker/lb/flattens.go index fae1386..b3c17da 100644 --- a/internal/service/cloudbroker/lb/flattens.go +++ b/internal/service/cloudbroker/lb/flattens.go @@ -108,6 +108,8 @@ func flattenLB(d *schema.ResourceData, lb *lb.RecordLB) { d.Set("gid", lb.GID) d.Set("guid", lb.GUID) d.Set("lb_id", lb.ID) + d.Set("manager_id", lb.ManagerId) + d.Set("manager_type", lb.ManagerType) d.Set("image_id", lb.ImageID) d.Set("milestones", lb.Milestones) d.Set("name", lb.Name) @@ -117,6 +119,7 @@ func flattenLB(d *schema.ResourceData, lb *lb.RecordLB) { d.Set("secondary_node", flattenNode(lb.SecondaryNode)) d.Set("status", lb.Status) d.Set("tech_status", lb.TechStatus) + d.Set("user_managed", lb.UserManaged) d.Set("vins_id", lb.VINSID) } @@ -235,8 +238,11 @@ func flattenLBList(lbl *lb.ListLB) []map[string]interface{} { "gid": lb.GID, "guid": lb.GUID, "lb_id": lb.ID, + "manager_id": lb.ManagerId, + "manager_type": lb.ManagerType, "milestones": lb.Milestones, "name": lb.Name, + "part_k8s": lb.PartK8s, "primary_node": flattenNode(lb.PrimaryNode), "rg_id": lb.RGID, "rg_name": lb.RGName, @@ -245,6 +251,7 @@ func flattenLBList(lbl *lb.ListLB) []map[string]interface{} { "tech_status": lb.TechStatus, "updated_by": lb.UpdatedBy, "updated_time": lb.UpdatedTime, + "user_managed": lb.UserManaged, "vins_id": lb.VINSID, } res = append(res, temp) diff --git a/internal/service/cloudbroker/lb/resource_lb.go b/internal/service/cloudbroker/lb/resource_lb.go index 4f979ed..7558739 100644 --- a/internal/service/cloudbroker/lb/resource_lb.go +++ b/internal/service/cloudbroker/lb/resource_lb.go @@ -34,9 +34,10 @@ package lb import ( "context" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc" "strconv" + "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" log "github.com/sirupsen/logrus" @@ -69,6 +70,22 @@ func resourceLBCreate(ctx context.Context, d *schema.ResourceData, m interface{} if haMode, ok := d.GetOk("ha_mode"); ok { req.HighlyAvailable = haMode.(bool) } + if sysctlParams, ok := d.GetOk("sysctl_params"); ok { + syscrlSliceMaps := sysctlParams.([]map[string]string) + res := make([]map[string]interface{}, 0, len(syscrlSliceMaps)) + for _, syscrlMap := range syscrlSliceMaps { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + req.SysctlParams = res + } lbId, err := c.CloudBroker().LB().Create(ctx, req) if err != nil { @@ -286,6 +303,12 @@ func resourceLBUpdate(ctx context.Context, d *schema.ResourceData, m interface{} } } + if d.HasChange("sysctl_params") { + if err := resourceLbChangeSysctlParams(ctx, d, lbRec.ID, m); err != nil { + return diag.FromErr(err) + } + } + if d.HasChange("start") { if err := resourceLbChangeStart(ctx, d, lbRec.ID, m); err != nil { return diag.FromErr(err) @@ -323,6 +346,31 @@ func resourceLbEnable(ctx context.Context, lbId uint64, m interface{}) error { return err } +func resourceLbChangeSysctlParams(ctx context.Context, d *schema.ResourceData, lbId uint64, m interface{}) error { + c := m.(*controller.ControllerCfg) + + syscrlSliceMaps := d.Get("sysctl_params").([]map[string]string) + res := make([]map[string]interface{}, 0, len(syscrlSliceMaps)) + for _, syscrlMap := range syscrlSliceMaps { + tempMap := make(map[string]interface{}) + for k, v := range syscrlMap { + if intVal, err := strconv.Atoi(v); err == nil { + tempMap[k] = intVal + continue + } + tempMap[k] = v + } + res = append(res, tempMap) + } + + req := lb.UpdateSysctParamsRequest{ + LBID: lbId, + SysctlParams: res, + } + _, err := c.CloudBroker().LB().UpdateSysctlParams(ctx, req) + return err +} + func resourceLbDisable(ctx context.Context, lbId uint64, m interface{}) error { c := m.(*controller.ControllerCfg) @@ -429,6 +477,9 @@ func resourceLbChangeRestart(ctx context.Context, d *schema.ResourceData, lbId u req := lb.RestartRequest{ LBID: lbId, } + if safe, ok := d.GetOk("safe"); ok { + req.Safe = safe.(bool) + } if _, err := c.CloudBroker().LB().Restart(ctx, req); err != nil { return err diff --git a/internal/service/cloudbroker/lb/schema.go b/internal/service/cloudbroker/lb/schema.go index afe0f41..735dfef 100644 --- a/internal/service/cloudbroker/lb/schema.go +++ b/internal/service/cloudbroker/lb/schema.go @@ -274,6 +274,14 @@ func dsLBSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "manager_id": { + Type: schema.TypeInt, + Computed: true, + }, + "manager_type": { + Type: schema.TypeString, + Computed: true, + }, "image_id": { Type: schema.TypeInt, Computed: true, @@ -366,6 +374,10 @@ func dsLBSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, "vins_id": { Type: schema.TypeInt, Computed: true, @@ -412,6 +424,11 @@ func dsLBListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by BackIP", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -663,6 +680,14 @@ func dsLBListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "manager_id": { + Type: schema.TypeInt, + Computed: true, + }, + "manager_type": { + Type: schema.TypeString, + Computed: true, + }, "lb_id": { Type: schema.TypeInt, Computed: true, @@ -675,6 +700,10 @@ func dsLBListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "part_k8s": { + Type: schema.TypeBool, + Computed: true, + }, "primary_node": { Type: schema.TypeList, Computed: true, @@ -763,6 +792,10 @@ func dsLBListDeletedSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, "vins_id": { Type: schema.TypeInt, Computed: true, @@ -824,6 +857,11 @@ func dsLBListSchemaMake() map[string]*schema.Schema { Optional: true, Default: false, }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1075,6 +1113,14 @@ func dsLBListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "manager_id": { + Type: schema.TypeInt, + Computed: true, + }, + "manager_type": { + Type: schema.TypeString, + Computed: true, + }, "lb_id": { Type: schema.TypeInt, Computed: true, @@ -1087,6 +1133,10 @@ func dsLBListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "part_k8s": { + Type: schema.TypeBool, + Computed: true, + }, "primary_node": { Type: schema.TypeList, Computed: true, @@ -1175,6 +1225,10 @@ func dsLBListSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, "vins_id": { Type: schema.TypeInt, Computed: true, @@ -1222,7 +1276,6 @@ func lbResourceSchemaMake() map[string]*schema.Schema { Optional: true, Computed: true, }, - "enable": { Type: schema.TypeBool, Optional: true, @@ -1231,6 +1284,11 @@ func lbResourceSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Optional: true, }, + "safe": { + Type: schema.TypeBool, + Default: true, + Optional: true, + }, "restore": { Type: schema.TypeBool, Optional: true, @@ -1243,7 +1301,17 @@ func lbResourceSchemaMake() map[string]*schema.Schema { Type: schema.TypeBool, Optional: true, }, - + "sysctl_params": { + Type: schema.TypeList, + Optional: true, + Description: "Custom sysctl values for Load Balancer instance. Applied on boot", + Elem: &schema.Schema{ + Type: schema.TypeMap, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, "ckey": { Type: schema.TypeString, Computed: true, @@ -1467,6 +1535,14 @@ func lbResourceSchemaMake() map[string]*schema.Schema { Type: schema.TypeInt, Computed: true, }, + "manager_id": { + Type: schema.TypeInt, + Computed: true, + }, + "manager_type": { + Type: schema.TypeString, + Computed: true, + }, "image_id": { Type: schema.TypeInt, Computed: true, @@ -1551,6 +1627,10 @@ func lbResourceSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "user_managed": { + Type: schema.TypeBool, + Computed: true, + }, } } diff --git a/internal/service/cloudbroker/lb/utility_lb_list.go b/internal/service/cloudbroker/lb/utility_lb_list.go index ca2d904..cada30e 100644 --- a/internal/service/cloudbroker/lb/utility_lb_list.go +++ b/internal/service/cloudbroker/lb/utility_lb_list.go @@ -82,6 +82,10 @@ func utilityLBListCheckPresence(ctx context.Context, d *schema.ResourceData, m i req.IncludeDeleted = includedeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/lb/utility_lb_list_deleted.go b/internal/service/cloudbroker/lb/utility_lb_list_deleted.go index 75a15f4..283ad14 100644 --- a/internal/service/cloudbroker/lb/utility_lb_list_deleted.go +++ b/internal/service/cloudbroker/lb/utility_lb_list_deleted.go @@ -74,6 +74,10 @@ func utilityLBListDeletedCheckPresence(ctx context.Context, d *schema.ResourceDa req.BackIP = back_ip.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/node/data_source_node.go b/internal/service/cloudbroker/node/data_source_node.go new file mode 100644 index 0000000..87a8104 --- /dev/null +++ b/internal/service/cloudbroker/node/data_source_node.go @@ -0,0 +1,70 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 node + +import ( + "context" + "strconv" + + "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 dataSourceNodeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + nodeRec, err := utilityNodeCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + + flattenNode(d, nodeRec) + d.SetId(strconv.Itoa(d.Get("node_id").(int))) + + return nil +} + +func DataSourceNode() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceNodeRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceNodeSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/node/data_source_node_list.go b/internal/service/cloudbroker/node/data_source_node_list.go new file mode 100644 index 0000000..940a48d --- /dev/null +++ b/internal/service/cloudbroker/node/data_source_node_list.go @@ -0,0 +1,72 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 node + +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 dataSourceNodeListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + nodeList, err := utilityNodeListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenNodeList(nodeList)) + d.Set("entry_count", nodeList.EntryCount) + + return nil +} + +func DataSourceNodeList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceNodeListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceNodeListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/node/flattens.go b/internal/service/cloudbroker/node/flattens.go new file mode 100644 index 0000000..85c3fc7 --- /dev/null +++ b/internal/service/cloudbroker/node/flattens.go @@ -0,0 +1,239 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 node + +import ( + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/node" +) + +func flattenNode(d *schema.ResourceData, item *node.RecordNode) { + log.Debugf("flattenNode: decoded node id %d", d.Get("node_id").(int)) + + d.Set("consumption", flattenConsumption(item.Consumption)) + d.Set("cpu_info", flattenCpuInfo(item.CpuInfo)) + d.Set("cpu_allocation_ratio", item.CPUAllocationRatio) + d.Set("gid", item.GID) + d.Set("ipaddr", item.IPAddr) + d.Set("isolated_cpus", flattenNodeItem(item.IsolatedCpus)) + d.Set("name", item.Name) + d.Set("need_reboot", item.NeedReboot) + d.Set("nic_info", flattenNicInfo(item.NicInfo)) + d.Set("numa_topology", flattenNumaTopology(item.NumaTopology)) + d.Set("reserved_cpus", flattenNodeItem(item.ReservedCPUs)) + d.Set("roles", item.Roles) + d.Set("sriov_enabled", item.SriovEnabled) + d.Set("stack_id", item.StackID) + d.Set("status", item.Status) + d.Set("version", item.Version) +} + +func flattenConsumption(info node.ConsumptionInfo) []map[string]interface{} { + res := make([]map[string]interface{}, 1) + tempRes := map[string]interface{}{ + "hostname": info.Hostname, + } + + tempConsumed := map[string]interface{}{ + "ram": info.Consumed.RAM, + "computes": info.Consumed.Computes, + "routers": info.Consumed.Routers, + "vcpu": info.Consumed.VCPU, + } + tempRes["consumed"] = []map[string]interface{}{ + tempConsumed, + } + + tempFree := map[string]interface{}{ + "ram": info.Free.RAM, + } + tempRes["free"] = []map[string]interface{}{ + tempFree, + } + + tempReserved := map[string]interface{}{ + "ram": info.Reserved.RAM, + } + tempRes["reserved"] = []map[string]interface{}{ + tempReserved, + } + + tempTotal := map[string]interface{}{ + "ram": info.Total.RAM, + } + tempRes["total"] = []map[string]interface{}{ + tempTotal, + } + + res[0] = tempRes + return res +} + +func flattenNodeList(nodes *node.ListNodes) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(nodes.Data)) + for _, item := range nodes.Data { + temp := map[string]interface{}{ + "additional_pkgs": flattenNodeItem(item.AdditionalPkgs), + "cpu_info": flattenCpuInfo(item.CpuInfo), + "description": item.Description, + "gid": item.GID, + "guid": item.GUID, + "hostkey": item.HostKey, + "node_id": item.ID, + "ipaddr": item.IPAddr, + "isolated_cpus": flattenNodeItem(item.IsolatedCpus), + "lastcheck": item.LastCheck, + "machine_guid": item.MachineGUID, + "mainboard_sn": item.MainboardSN, + "memory": item.Memory, + "milestones": item.Milestones, + "model": item.Model, + "name": item.Name, + "need_reboot": item.NeedReboot, + "net_addr": flattenNetAddr(item.NetAddr), + "network_mode": item.NetworkMode, + "nic_info": flattenNicInfo(item.NicInfo), + "node_uuid": item.NodeUUID, + "numa_topology": flattenNumaTopology(item.NumaTopology), + "peer_backup": item.PeerBackup, + "peer_log": item.PeerLog, + "peer_stats": item.PeerStats, + "pgpus": item.Pgpus, + "public_keys": item.PublicKeys, + "release": item.Release, + "reserved_cpus": flattenNodeItem(item.ReservedCPUs), + "roles": item.Roles, + "seps": item.Seps, + "serial_num": item.SerialNum, + "sriov_enabled": item.SriovEnabled, + "stack_id": item.StackID, + "status": item.Status, + "tags": item.Tags, + "type": item.Type, + "version": item.Version, + } + res = append(res, temp) + } + return res +} + +func flattenNumaTopology(info node.NumaTopologyInfo) []map[string]interface{} { + res := make([]map[string]interface{}, 1) + tempRes := map[string]interface{}{ + "node_num": info.NodeNum, + } + resNodes := make([]map[string]interface{}, 0, len(info.Nodes)) + for _, item := range info.Nodes { + memoryTemp := []map[string]interface{}{ + { + "one_g": item.Memory.OneG, + "two_m": item.Memory.TwoM, + "total": item.Memory.Total, + }, + } + temp := map[string]interface{}{ + "cpu_list": item.CPUList, + "memory": memoryTemp, + } + resNodes = append(resNodes, temp) + } + tempRes["nodes"] = resNodes + res[0] = tempRes + return res +} + +func flattenNicInfo(infos node.ListNicInfo) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(infos)) + for _, item := range infos { + temp := map[string]interface{}{ + "driver": item.Driver, + "max_vfs": item.MaxVFS, + "numa_node": item.NumaNode, + "num_vfs": item.NumVFS, + "os_name": item.OSName, + "pci_slot": item.PCISlot, + "vf_list": flattenNodeItem(item.VFList), + } + res = append(res, temp) + } + return res +} + +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, + "ip": item.IP, + "mac": item.Mac, + "mtu": item.MTU, + "name": item.Name, + } + res = append(res, temp) + } + return res +} + +func flattenCpuInfo(info node.CpuInfo) []map[string]interface{} { + res := make([]map[string]interface{}, 1) + temp := map[string]interface{}{ + "clock_speed": info.ClockSpeed, + "core_count": info.CoreCount, + "phys_count": info.PhysCount, + } + res[0] = temp + return res +} + +func flattenNodeItem(m []interface{}) []string { + output := []string{} + for _, item := range m { + switch d := item.(type) { + case string: + output = append(output, d) + case int: + output = append(output, strconv.Itoa(d)) + case int64: + output = append(output, strconv.FormatInt(d, 10)) + case float64: + output = append(output, strconv.FormatInt(int64(d), 10)) + default: + output = append(output, "") + } + } + return output +} diff --git a/internal/service/cloudbroker/node/schema.go b/internal/service/cloudbroker/node/schema.go new file mode 100644 index 0000000..236d85b --- /dev/null +++ b/internal/service/cloudbroker/node/schema.go @@ -0,0 +1,629 @@ +package node + +import "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + +func dataSourceNodeSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "node_id": { + Type: schema.TypeInt, + Required: true, + Description: "node id", + }, + "consumption": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "consumed": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + "computes": { + Type: schema.TypeInt, + Computed: true, + }, + "routers": { + Type: schema.TypeInt, + Computed: true, + }, + "vcpu": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "free": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "reserved": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "total": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ram": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "hostname": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "cpu_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "clock_speed": { + Type: schema.TypeInt, + Computed: true, + }, + "core_count": { + Type: schema.TypeInt, + Computed: true, + }, + "phys_count": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "cpu_allocation_ratio": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "ipaddr": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "isolated_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "need_reboot": { + Type: schema.TypeBool, + Computed: true, + }, + "nic_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "driver": { + Type: schema.TypeString, + Computed: true, + }, + "max_vfs": { + Type: schema.TypeInt, + Computed: true, + }, + "numa_node": { + Type: schema.TypeInt, + Computed: true, + }, + "num_vfs": { + Type: schema.TypeInt, + Computed: true, + }, + "os_name": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeString, + Computed: true, + }, + + "vf_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "numa_topology": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_num": { + Type: schema.TypeInt, + Computed: true, + }, + "nodes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "memory": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "one_g": { + Type: schema.TypeInt, + Computed: true, + }, + "two_m": { + Type: schema.TypeInt, + Computed: true, + }, + "total": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "reserved_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "roles": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "sriov_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "stack_id": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + } +} + +func dataSourceNodeListSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "find node by id", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "find node by name", + }, + "version": { + Type: schema.TypeString, + Optional: true, + Description: "find node by version", + }, + "release": { + Type: schema.TypeString, + Optional: true, + Description: "find node by release", + }, + "sep_id": { + Type: schema.TypeInt, + Optional: true, + Description: "find node by sepId", + }, + "role": { + Type: schema.TypeString, + Optional: true, + Description: "find node by role", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "find node by status", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "page size", + }, + + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "additional_pkgs": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "cpu_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "clock_speed": { + Type: schema.TypeFloat, + Computed: true, + }, + "core_count": { + Type: schema.TypeInt, + Computed: true, + }, + "phys_count": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeString, + Computed: true, + }, + "hostkey": { + Type: schema.TypeString, + Computed: true, + }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, + "ipaddr": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "isolated_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "lastcheck": { + Type: schema.TypeInt, + Computed: true, + }, + "machine_guid": { + Type: schema.TypeString, + Computed: true, + }, + "mainboard_sn": { + Type: schema.TypeString, + Computed: true, + }, + "memory": { + Type: schema.TypeInt, + Computed: true, + }, + "milestones": { + Type: schema.TypeInt, + Computed: true, + }, + "model": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "need_reboot": { + Type: schema.TypeBool, + Computed: true, + }, + "net_addr": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cidr": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "index": { + Type: schema.TypeInt, + Computed: true, + }, + "ip": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "mac": { + Type: schema.TypeString, + Computed: true, + }, + "mtu": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "network_mode": { + Type: schema.TypeString, + Computed: true, + }, + "nic_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "driver": { + Type: schema.TypeString, + Computed: true, + }, + "max_vfs": { + Type: schema.TypeInt, + Computed: true, + }, + "numa_node": { + Type: schema.TypeInt, + Computed: true, + }, + "num_vfs": { + Type: schema.TypeInt, + Computed: true, + }, + "os_name": { + Type: schema.TypeString, + Computed: true, + }, + "pci_slot": { + Type: schema.TypeString, + Computed: true, + }, + + "vf_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "node_uuid": { + Type: schema.TypeString, + Computed: true, + }, + "numa_topology": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_num": { + Type: schema.TypeInt, + Computed: true, + }, + "nodes": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "memory": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "one_g": { + Type: schema.TypeInt, + Computed: true, + }, + "two_m": { + Type: schema.TypeInt, + Computed: true, + }, + "total": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "peer_backup": { + Type: schema.TypeInt, + Computed: true, + }, + "peer_log": { + Type: schema.TypeInt, + Computed: true, + }, + "peer_stats": { + Type: schema.TypeInt, + Computed: true, + }, + "pgpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "public_keys": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "release": { + Type: schema.TypeString, + Computed: true, + }, + "reserved_cpus": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "roles": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "seps": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "serial_num": { + Type: schema.TypeString, + Computed: true, + }, + "sriov_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "stack_id": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "tags": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + "version": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + Description: "entry count", + }, + } +} diff --git a/internal/service/cloudbroker/node/utility_node.go b/internal/service/cloudbroker/node/utility_node.go new file mode 100644 index 0000000..3598b6f --- /dev/null +++ b/internal/service/cloudbroker/node/utility_node.go @@ -0,0 +1,56 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 node + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/node" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityNodeCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*node.RecordNode, error) { + c := m.(*controller.ControllerCfg) + req := node.GetRequest{NID: uint64(d.Get("node_id").(int))} + + log.Debugf("utilityNodeCheckPresence: load node") + nodeInfo, err := c.CloudBroker().Node().Get(ctx, req) + if err != nil { + return nil, err + } + + return nodeInfo, nil +} diff --git a/internal/service/cloudbroker/node/utility_node_list.go b/internal/service/cloudbroker/node/utility_node_list.go new file mode 100644 index 0000000..a3f5855 --- /dev/null +++ b/internal/service/cloudbroker/node/utility_node_list.go @@ -0,0 +1,87 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 node + +import ( + "context" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/node" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityNodeListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*node.ListNodes, error) { + c := m.(*controller.ControllerCfg) + req := node.ListRequest{} + + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byId.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if version, ok := d.GetOk("version"); ok { + req.Version = version.(string) + } + if release, ok := d.GetOk("release"); ok { + req.Release = release.(string) + } + if sepId, ok := d.GetOk("sep_id"); ok { + req.SepID = uint64(sepId.(int)) + } + if role, ok := d.GetOk("role"); ok { + req.Role = role.(string) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if Page, ok := d.GetOk("page"); ok { + req.Page = uint64(Page.(int)) + } + if Size, ok := d.GetOk("size"); ok { + req.Size = uint64(Size.(int)) + } + + log.Debugf("utilityNodeListCheckPresence: load node list") + nodeList, err := c.CloudBroker().Node().List(ctx, req) + if err != nil { + return nil, err + } + + return nodeList, nil +} diff --git a/internal/service/cloudbroker/rg/flattens.go b/internal/service/cloudbroker/rg/flattens.go index 4f379a0..c3150de 100644 --- a/internal/service/cloudbroker/rg/flattens.go +++ b/internal/service/cloudbroker/rg/flattens.go @@ -14,6 +14,7 @@ func flattenResgroup(d *schema.ResourceData, rgData *rg.RecordRG) { d.Set("account_id", rgData.AccountID) d.Set("account_name", rgData.AccountName) d.Set("acl", flattenRgAcl(rgData.ACL)) + d.Set("compute_features", rgData.ComputeFeatures) d.Set("cpu_allocation_parameter", rgData.CPUAllocationParameter) d.Set("cpu_allocation_ratio", rgData.CPUAllocationRatio) d.Set("created_by", rgData.CreatedBy) @@ -387,6 +388,7 @@ func flattenRgList(rgl *rg.ListRG) []map[string]interface{} { "account_id": rg.AccountID, "account_name": rg.AccountName, "acl": flattenRgAcl(rg.ACL), + "compute_features": rg.ComputeFeatures, "cpu_allocation_parameter": rg.CPUAllocationParameter, "cpu_allocation_ratio": rg.CPUAllocationRatio, "created_by": rg.CreatedBy, @@ -430,6 +432,8 @@ func flattenRgListVins(lv *rg.ListVINS) []map[string]interface{} { "deleted_by": vins.DeletedBy, "deleted_time": vins.DeletedTime, "external_ip": vins.ExternalIP, + "extnet_id": vins.ExtnetId, + "free_ips": vins.FreeIPs, "id": vins.ID, "name": vins.Name, "network": vins.Network, diff --git a/internal/service/cloudbroker/rg/resource_rg.go b/internal/service/cloudbroker/rg/resource_rg.go index d528fbd..68991ed 100644 --- a/internal/service/cloudbroker/rg/resource_rg.go +++ b/internal/service/cloudbroker/rg/resource_rg.go @@ -160,6 +160,15 @@ func resourceResgroupCreate(ctx context.Context, d *schema.ResourceData, m inter w := dc.Warnings{} + // compute_features is not set up during create request and is updated after create on purpose: + // 1. to support configuration as final state in resource group, + // 2. not to support compute_features inheritance from account. + // other implementation may result in inconsistency between user configuration and state after rg creation. + // note that call for compute features updated required even if compute_features is null in configuration, in order not ot inherit from account. + if err := resourceRGChangeComputeFeatures(ctx, d, m); err != nil { + w.Add(err) + } + if _, ok := d.GetOk("access"); ok { if errs := resourceRGAccessGrant(ctx, d, m); len(errs) != 0 { for _, err := range errs { @@ -482,6 +491,12 @@ func resourceResgroupUpdate(ctx context.Context, d *schema.ResourceData, m inter } } + if d.HasChange("compute_features") { + if err := resourceRGChangeComputeFeatures(ctx, d, m); err != nil { + return diag.FromErr(err) + } + } + return resourceResgroupRead(ctx, d, m) } @@ -606,7 +621,7 @@ func resourceRGSetCPUAllocationParameter(ctx context.Context, d *schema.Resource func resourceRGSetCPUAllocationRatio(ctx context.Context, d *schema.ResourceData, m interface{}) error { cpuAllocationRatio := d.Get("cpu_allocation_ratio").(float64) - log.Debugf("resourceRGSetCPUAllocationRatio: cpuAllocationRatio %f for rg id %d", cpuAllocationRatio, uint64(d.Get("rg_id").(int))) + log.Debugf("resourceRGSetCPUAllocationRatio: cpuAllocationRatio %s for rg id %d", cpuAllocationRatio, uint64(d.Get("rg_id").(int))) c := m.(*controller.ControllerCfg) @@ -695,6 +710,32 @@ func resourceRGChangeEnable(ctx context.Context, d *schema.ResourceData, m inter return nil } +func resourceRGChangeComputeFeatures(ctx context.Context, d *schema.ResourceData, m interface{}) error { + rgId := uint64(d.Get("rg_id").(int)) + compFeaturesInterface := d.Get("compute_features").(*schema.Set).List() + + compFeatures := make([]string, 0, len(compFeaturesInterface)) + for _, item := range compFeaturesInterface { + compFeatures = append(compFeatures, item.(string)) + } + + log.Debugf("resourceRGChangeComputeFeatures: compute_features %v for rg id %d", compFeatures, rgId) + + c := m.(*controller.ControllerCfg) + + req := rg.UpdateComputeFeaturesRequest{ + RGID: rgId, + ComputeFeatures: compFeatures, + } + + _, err := c.CloudBroker().RG().UpdateComputeFeatures(ctx, req) + if err != nil { + return err + } + + return nil +} + func ResourceResgroup() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, diff --git a/internal/service/cloudbroker/rg/schema.go b/internal/service/cloudbroker/rg/schema.go index 4280e1b..d58c41b 100644 --- a/internal/service/cloudbroker/rg/schema.go +++ b/internal/service/cloudbroker/rg/schema.go @@ -55,6 +55,13 @@ func dataSourceRgSchemaMake() map[string]*schema.Schema { }, }, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "cpu_allocation_parameter": { Type: schema.TypeString, Computed: true, @@ -841,6 +848,11 @@ func dataSourceRgListComputesSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by extnet ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1038,11 +1050,6 @@ func dataSourceRgListLbSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by name", }, - "account_id": { - Type: schema.TypeInt, - Optional: true, - Description: "Filter by account ID", - }, "tech_status": { Type: schema.TypeString, Optional: true, @@ -1063,6 +1070,11 @@ func dataSourceRgListLbSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by backend IP", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1484,6 +1496,11 @@ func dataSourceRgListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by lock status", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1540,6 +1557,13 @@ func dataSourceRgListDeletedSchemaMake() map[string]*schema.Schema { }, }, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "cpu_allocation_parameter": { Type: schema.TypeString, Computed: true, @@ -1746,6 +1770,11 @@ func dataSourceRgListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Include deleted", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1802,6 +1831,13 @@ func dataSourceRgListSchemaMake() map[string]*schema.Schema { }, }, }, + "compute_features": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "cpu_allocation_parameter": { Type: schema.TypeString, Computed: true, @@ -1988,6 +2024,11 @@ func dataSourceRgListVinsSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by ViNS ID", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -2036,6 +2077,14 @@ func dataSourceRgListVinsSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "extnet_id": { + Type: schema.TypeInt, + Computed: true, + }, + "free_ips": { + Type: schema.TypeInt, + Computed: true, + }, "id": { Type: schema.TypeInt, Computed: true, @@ -2364,6 +2413,15 @@ func resourceRgSchemaMake() map[string]*schema.Schema { Description: "flag to permanently delete resource group", }, + "compute_features": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{"hugepages", "numa", "cpupin", "vfnic"}, true), + }, + }, + "acl": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/cloudbroker/rg/utility_rg_list.go b/internal/service/cloudbroker/rg/utility_rg_list.go index 9437111..b2c981b 100644 --- a/internal/service/cloudbroker/rg/utility_rg_list.go +++ b/internal/service/cloudbroker/rg/utility_rg_list.go @@ -73,6 +73,10 @@ func utilityRgListCheckPresence(ctx context.Context, d *schema.ResourceData, m i req.IncludeDeleted = includedeleted.(bool) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if size, ok := d.GetOk("size"); ok { req.Size = uint64(size.(int)) } diff --git a/internal/service/cloudbroker/rg/utility_rg_list_computes.go b/internal/service/cloudbroker/rg/utility_rg_list_computes.go index 1d9ab4e..d74a17e 100644 --- a/internal/service/cloudbroker/rg/utility_rg_list_computes.go +++ b/internal/service/cloudbroker/rg/utility_rg_list_computes.go @@ -78,6 +78,10 @@ func utilityRgListComputesCheckPresence(ctx context.Context, d *schema.ResourceD req.ExtNetID = uint64(extnet_id.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/rg/utility_rg_list_deleted.go b/internal/service/cloudbroker/rg/utility_rg_list_deleted.go index 0b35472..49f61b0 100644 --- a/internal/service/cloudbroker/rg/utility_rg_list_deleted.go +++ b/internal/service/cloudbroker/rg/utility_rg_list_deleted.go @@ -72,6 +72,10 @@ func utilityRgListDeletedCheckPresence(ctx context.Context, d *schema.ResourceDa req.LockStatus = lock_status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if size, ok := d.GetOk("size"); ok { req.Size = uint64(size.(int)) } diff --git a/internal/service/cloudbroker/rg/utility_rg_list_lb.go b/internal/service/cloudbroker/rg/utility_rg_list_lb.go index 79b0997..cd96172 100644 --- a/internal/service/cloudbroker/rg/utility_rg_list_lb.go +++ b/internal/service/cloudbroker/rg/utility_rg_list_lb.go @@ -54,10 +54,6 @@ func utilityRgListLbCheckPresence(ctx context.Context, d *schema.ResourceData, m req.Name = name.(string) } - if account_id, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(account_id.(int)) - } - if tech_status, ok := d.GetOk("tech_status"); ok { req.TechStatus = tech_status.(string) } @@ -74,6 +70,10 @@ func utilityRgListLbCheckPresence(ctx context.Context, d *schema.ResourceData, m req.BackIP = back_ip.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/rg/utility_rg_list_vins.go b/internal/service/cloudbroker/rg/utility_rg_list_vins.go index a138b26..8445f3f 100644 --- a/internal/service/cloudbroker/rg/utility_rg_list_vins.go +++ b/internal/service/cloudbroker/rg/utility_rg_list_vins.go @@ -62,6 +62,10 @@ func utilityRgListVinsCheckPresence(ctx context.Context, d *schema.ResourceData, req.VINSID = uint64(vins_id.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/sep/resource_sep.go b/internal/service/cloudbroker/sep/resource_sep.go index 347529f..1994ce8 100644 --- a/internal/service/cloudbroker/sep/resource_sep.go +++ b/internal/service/cloudbroker/sep/resource_sep.go @@ -34,7 +34,6 @@ package sep import ( "context" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc" "strconv" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -43,6 +42,7 @@ import ( "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/sep" "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" ) func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { @@ -58,14 +58,12 @@ func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{ GID: uint64(d.Get("gid").(int)), Name: d.Get("name").(string), SEPType: d.Get("type").(string), + Config: d.Get("config").(string), } if desc, ok := d.GetOk("desc"); ok { req.Description = desc.(string) } - if configString, ok := d.GetOk("config"); ok { - req.Config = configString.(string) - } if enable, ok := d.GetOk("enable"); ok { req.Enable = enable.(bool) } @@ -119,6 +117,14 @@ func resourceSepCreate(ctx context.Context, d *schema.ResourceData, m interface{ } } + if pools, ok := d.GetOk("pools"); ok { + log.Debugf("resourceSepCreate, pools: pools=%v sep_id %d after completing its resource configuration", pools, sepId) + err := resourceSepChangePools(ctx, d, m) + if err != nil { + warnings.Add(err) + } + } + return append(resourceSepRead(ctx, d, m), warnings.Get()...) } @@ -236,6 +242,13 @@ func resourceSepUpdate(ctx context.Context, d *schema.ResourceData, m interface{ } } + if d.HasChange("pools") { + err := resourceSepChangePools(ctx, d, m) + if err != nil { + return diag.FromErr(err) + } + } + return resourceSepRead(ctx, d, m) } @@ -337,6 +350,42 @@ func resourceSepChangeAccessToPool(ctx context.Context, d *schema.ResourceData, return nil } +func resourceSepChangePools(ctx context.Context, d *schema.ResourceData, m interface{}) error { + log.Debugf("resourceSepChangePools: called for %s, id: %d", d.Get("name").(string), d.Get("sep_id").(int)) + c := m.(*controller.ControllerCfg) + + oldPoolsInterface, newPoolsInterface := d.GetChange("pools") + + oldPoolsList := oldPoolsInterface.(*schema.Set).Difference(newPoolsInterface.(*schema.Set)).List() + for _, pool := range oldPoolsList { + delPoolReq := sep.DelPoolRequest{ + SEPID: uint64(d.Get("sep_id").(int)), + PoolName: pool.(string), + } + + _, err := c.CloudBroker().SEP().DelPool(ctx, delPoolReq) + if err != nil { + return err + } + } + + newPoolsList := newPoolsInterface.(*schema.Set).Difference(oldPoolsInterface.(*schema.Set)).List() + for _, pool := range newPoolsList { + addPoolReq := sep.AddPoolRequest{ + SEPID: uint64(d.Get("sep_id").(int)), + Sync: true, + Pool: pool.(string), + } + + _, err := c.CloudBroker().SEP().AddPool(ctx, addPoolReq) + if err != nil { + return err + } + } + + return nil +} + func resourceSepDecommission(ctx context.Context, d *schema.ResourceData, m interface{}) error { c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudbroker/sep/schema.go b/internal/service/cloudbroker/sep/schema.go index 94d0234..3439215 100644 --- a/internal/service/cloudbroker/sep/schema.go +++ b/internal/service/cloudbroker/sep/schema.go @@ -274,6 +274,11 @@ func dataSourceSepListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "find by consumed physical node id", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -583,6 +588,14 @@ func resourceSepSchemaMake() map[string]*schema.Schema { Default: false, Description: "Update SEP capacity limit", }, + "pools": { + Type: schema.TypeSet, + Optional: true, + Description: "add/delete pools to/from sep", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "ckey": { Type: schema.TypeString, Computed: true, @@ -598,8 +611,7 @@ func resourceSepSchemaMake() map[string]*schema.Schema { }, "config": { Type: schema.TypeString, - Optional: true, - Computed: true, + Required: true, Description: "sep config string", }, "consumed_by": { diff --git a/internal/service/cloudbroker/sep/utility_sep_list.go b/internal/service/cloudbroker/sep/utility_sep_list.go index 7798f32..fd3e3cb 100644 --- a/internal/service/cloudbroker/sep/utility_sep_list.go +++ b/internal/service/cloudbroker/sep/utility_sep_list.go @@ -67,6 +67,9 @@ func utilitySepListCheckPresence(ctx context.Context, d *schema.ResourceData, m if consumed_by, ok := d.GetOk("consumed_by"); ok { req.ConsumedBy = uint64(consumed_by.(int)) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/service/cloudbroker/stack/schema.go b/internal/service/cloudbroker/stack/schema.go index 0c40a5a..c2a9d89 100644 --- a/internal/service/cloudbroker/stack/schema.go +++ b/internal/service/cloudbroker/stack/schema.go @@ -289,6 +289,11 @@ func dataSourceStacksListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "type", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, diff --git a/internal/service/cloudbroker/stack/utility_stack_list.go b/internal/service/cloudbroker/stack/utility_stack_list.go index 29c2f43..6893798 100644 --- a/internal/service/cloudbroker/stack/utility_stack_list.go +++ b/internal/service/cloudbroker/stack/utility_stack_list.go @@ -58,6 +58,9 @@ func utilityStackListCheckPresence(ctx context.Context, d *schema.ResourceData, if Status, ok := d.GetOk("status"); ok { req.Status = Status.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if Page, ok := d.GetOk("page"); ok { req.Page = uint64(Page.(int)) } diff --git a/internal/service/cloudbroker/user/data_source_user.go b/internal/service/cloudbroker/user/data_source_user.go new file mode 100644 index 0000000..14be07b --- /dev/null +++ b/internal/service/cloudbroker/user/data_source_user.go @@ -0,0 +1,68 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 user + +import ( + "context" + + "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 dataSourceUserRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + user, err := utilityUserCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + + flattenUserDataSource(d, user) + d.SetId(d.Get("user_id").(string)) + + return nil +} + +func DataSourceUser() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceUserRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceUserSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/user/data_source_user_get_audit.go b/internal/service/cloudbroker/user/data_source_user_get_audit.go new file mode 100644 index 0000000..96b2ebb --- /dev/null +++ b/internal/service/cloudbroker/user/data_source_user_get_audit.go @@ -0,0 +1,71 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 user + +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 dataSourceUserGetAuditRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + audits, err := utilityUserGetAuditCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenUserGetAudits(audits)) + d.Set("entry_count", audits.EntryCount) + + return nil +} + +func DataSourceUserGetAudit() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceUserGetAuditRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceUserGetAuditSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/user/data_source_user_list.go b/internal/service/cloudbroker/user/data_source_user_list.go new file mode 100644 index 0000000..9141923 --- /dev/null +++ b/internal/service/cloudbroker/user/data_source_user_list.go @@ -0,0 +1,73 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 user + +import ( + "context" + "github.com/google/uuid" + log "github.com/sirupsen/logrus" + + "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 dataSourceUserListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + users, err := utilityUserListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + + id := uuid.New() + d.SetId(id.String()) + err = d.Set("items", flattenUserList(users)) + log.Debug("err:", err) + d.Set("entry_count", users.EntryCount) + + return nil +} + +func DataSourceUserList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceUserListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceUserListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/user/flattens.go b/internal/service/cloudbroker/user/flattens.go new file mode 100644 index 0000000..7ced2c3 --- /dev/null +++ b/internal/service/cloudbroker/user/flattens.go @@ -0,0 +1,184 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 user + +import ( + "strconv" + + log "github.com/sirupsen/logrus" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/user" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens" +) + +func flattenUserDataSource(d *schema.ResourceData, details *user.ItemUser) { + log.Debugf("flattenUser: decoded User ID %s", + details.ID) + + d.Set("user_id", details.ID) + d.Set("ckey", details.CKey) + d.Set("meta", flattens.FlattenMeta(details.Meta)) + d.Set("api_access", details.APIAccess) + d.Set("active", details.Active) + d.Set("authkey", details.AuthKey) + d.Set("auth_keys", flattenItemUser(details.AuthKeys)) + d.Set("data", details.Data) + d.Set("description", details.Description) + d.Set("domain", details.Domain) + d.Set("emails", details.Emails) + d.Set("gid", details.GID) + d.Set("groups", details.Groups) + d.Set("guid", details.GUID) + d.Set("last_check", details.LastCheck) + d.Set("mobile", flattenItemUser(details.Mobile)) + d.Set("password", details.Password) + d.Set("protected", details.Protected) + d.Set("roles", flattenItemUser(details.Roles)) + d.Set("service_account", details.ServiceAccount) + d.Set("xmpp", flattenItemUser(details.XMPP)) +} + +func flattenUserResource(d *schema.ResourceData, details *user.ItemUser) { + log.Debugf("flattenUser: decoded User ID %s", + details.ID) + + d.Set("username", details.ID) + d.Set("ckey", details.CKey) + d.Set("meta", flattens.FlattenMeta(details.Meta)) + d.Set("apiaccess", flattenAPIAcess(details.APIAccess)) + d.Set("active", details.Active) + d.Set("authkey", details.AuthKey) + d.Set("auth_keys", flattenItemUser(details.AuthKeys)) + d.Set("data", details.Data) + d.Set("description", details.Description) + d.Set("domain", details.Domain) + d.Set("emailaddress", details.Emails) + d.Set("gid", details.GID) + d.Set("groups", details.Groups) + d.Set("guid", details.GUID) + d.Set("last_check", details.LastCheck) + d.Set("mobile", flattenItemUser(details.Mobile)) + d.Set("protected", details.Protected) + d.Set("roles", flattenItemUser(details.Roles)) + d.Set("service_account", details.ServiceAccount) + d.Set("xmpp", flattenItemUser(details.XMPP)) +} + +func flattenItemUser(m []interface{}) []string { + output := []string{} + for _, item := range m { + switch d := item.(type) { + case string: + output = append(output, d) + case int: + output = append(output, strconv.Itoa(d)) + case int64: + output = append(output, strconv.FormatInt(d, 10)) + case float64: + output = append(output, strconv.FormatInt(int64(d), 10)) + default: + output = append(output, "") + } + } + return output +} + +func flattenUserGetAudits(audits *user.ListAudits) []map[string]interface{} { + log.Debug("flattenUserGetAudits") + + res := make([]map[string]interface{}, 0, len(audits.Data)) + for _, item := range audits.Data { + temp := map[string]interface{}{ + "call": item.Call, + "response_time": item.ResponseTime, + "status_code": item.StatusCode, + "time": item.Time, + } + res = append(res, temp) + } + + return res +} + +func flattenUserList(users *user.ListUsers) []map[string]interface{} { + log.Debug("flattenUserList") + + res := make([]map[string]interface{}, 0, len(users.Data)) + for _, item := range users.Data { + temp := map[string]interface{}{ + "ckey": item.CKey, + "meta": flattens.FlattenMeta(item.Meta), + "api_access": item.APIAccess, + "active": item.Active, + "authkey": item.AuthKey, + "authkeys": flattenItemUser(item.AuthKeys), + "data": item.Data, + "description": item.Description, + "domain": item.Domain, + "emails": item.Emails, + "gid": item.GID, + "groups": item.Groups, + "guid": item.GUID, + "user_id": item.ID, + "last_check": item.LastCheck, + "mobile": flattenItemUser(item.Mobile), + "password": item.Password, + "protected": item.Protected, + "roles": flattenItemUser(item.Roles), + "service_account": item.ServiceAccount, + "xmpp": flattenItemUser(item.XMPP), + } + res = append(res, temp) + } + + return res +} + +func flattenAPIAcess(in map[string]string) []int { + + res := make([]int, 0, len(in)) + + for i := range in { + num, err := strconv.Atoi(i) + if err != nil { + + log.Errorf("flattenAPIAcess: unable to convert %s to digit %v", i, err) + + return nil + } + res = append(res, num) + } + return res + +} diff --git a/internal/service/cloudbroker/user/resource_user.go b/internal/service/cloudbroker/user/resource_user.go new file mode 100644 index 0000000..8be3360 --- /dev/null +++ b/internal/service/cloudbroker/user/resource_user.go @@ -0,0 +1,149 @@ +package user + +import ( + "context" + + "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/user" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func resourceUserCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + + log.Debugf("resourceUserCreate: called with username %s, emailaddress %v", d.Get("username").(string), d.Get("emailaddress").([]interface{})) + + c := m.(*controller.ControllerCfg) + + username := d.Get("username").(string) + + emails := d.Get("emailaddress").([]interface{}) + + emailAddress := make([]string, 0, len(emails)) + + for _, v := range emails { + + emailAddress = append(emailAddress, v.(string)) + } + + createReq := user.CreateRequest{ + Username: username, + EmailAddress: emailAddress, + } + + if passwd, ok := d.GetOk("password"); ok { + + createReq.Password = passwd.(string) + } + + if aa, ok := d.GetOk("apiaccess"); ok { + + apiaccess := aa.(*schema.Set) + + for _, v := range apiaccess.List() { + + createReq.APIAccess = append(createReq.APIAccess, uint64(v.(int))) + } + } + + if groups, ok := d.GetOk("groups"); ok { + + for _, v := range groups.([]interface{}) { + + createReq.Groups = append(createReq.Groups, v.(string)) + } + } + + _, err := c.CloudBroker().User().Create(ctx, createReq) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(username) + + return resourceUserRead(ctx, d, m) +} + +func resourceUserRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + + log.Debugf("resourceUserRead: called with username %s", d.Get("username").(string)) + + user, err := utilityUserCheckPresence(ctx, d, m) + if err != nil { + + d.SetId("") + + return diag.FromErr(err) + } + flattenUserResource(d, user) + + return nil +} + +func resourceUserUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + + log.Debugf("resourceUserUpdate: called with username %s", d.Get("username").(string)) + + if d.HasChange("apiaccess") { + + err := utilityUserAPIAccessGroupsConfigure(ctx, d, m) + if err != nil { + + return diag.FromErr(err) + } + } + return resourceUserRead(ctx, d, m) +} + +func resourceUserDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + + log.Debugf("resourceUserDelete: called with username %s", d.Get("username").(string)) + + usr, err := utilityUserCheckPresence(ctx, d, m) + if err != nil { + + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + + req := user.DeleteRequest{ + Username: usr.ID, + } + + _, err = c.CloudBroker().User().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + return nil +} + +func ResourceUser() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceUserCreate, + ReadContext: resourceUserRead, + UpdateContext: resourceUserUpdate, + DeleteContext: resourceUserDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout600s, + Read: &constants.Timeout600s, + Update: &constants.Timeout600s, + Delete: &constants.Timeout600s, + Default: &constants.Timeout600s, + }, + + Schema: resourceUserSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/user/schema.go b/internal/service/cloudbroker/user/schema.go new file mode 100644 index 0000000..ba12a80 --- /dev/null +++ b/internal/service/cloudbroker/user/schema.go @@ -0,0 +1,525 @@ +package user + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" +) + +func dataSourceUserSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "user_id": { + Type: schema.TypeString, + Required: true, + Description: "user_id", + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + Description: "ckey", + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "meta", + }, + "active": { + Type: schema.TypeBool, + Computed: true, + Description: "active", + }, + "api_access": { + Type: schema.TypeMap, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "api_access", + }, + "authkey": { + Type: schema.TypeString, + Computed: true, + Description: "authkey", + }, + "authkeys": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "authkeys", + }, + "data": { + Type: schema.TypeString, + Computed: true, + Description: "data", + }, + "description": { + Type: schema.TypeString, + Computed: true, + Description: "description", + }, + "domain": { + Type: schema.TypeString, + Computed: true, + Description: "domain", + }, + "emails": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "emails", + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "gid", + }, + "groups": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "groups", + }, + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "guid", + }, + "last_check": { + Type: schema.TypeInt, + Computed: true, + Description: "last_check", + }, + "mobile": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "mobile", + }, + "password": { + Type: schema.TypeString, + Computed: true, + Description: "password", + }, + "protected": { + Type: schema.TypeBool, + Computed: true, + Description: "protected", + }, + "roles": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "roles", + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + Description: "service_account", + }, + "xmpp": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "xmpp", + }, + } +} + +func dataSourceUserGetAuditSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "username": { + Type: schema.TypeString, + Optional: true, + Description: "name of user (get audits for current user if set to empty)", + }, + "call": { + Type: schema.TypeString, + Optional: true, + Description: "find by api call", + }, + "status_code": { + Type: schema.TypeInt, + Optional: true, + Description: "find by status code", + }, + "timestamp_at": { + Type: schema.TypeInt, + Optional: true, + Description: "find all audits after point in time (unixtime)", + }, + "timestamp_to": { + Type: schema.TypeInt, + Optional: true, + Description: "find all audits before point in time (unixtime)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "call": { + Type: schema.TypeString, + Computed: true, + }, + "response_time": { + Type: schema.TypeFloat, + Computed: true, + }, + "status_code": { + Type: schema.TypeInt, + Computed: true, + }, + "time": { + Type: schema.TypeFloat, + Computed: true, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + Description: "entry_count", + }, + } +} + +func dataSourceUserListSchemaMake() map[string]*schema.Schema { + return map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeString, + Optional: true, + Description: "find by id", + }, + "active": { + Type: schema.TypeBool, + Optional: true, + Description: "find by active. True or False", + }, + "service_account": { + Type: schema.TypeBool, + Optional: true, + Description: "find by service account. True or False", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ckey": { + Type: schema.TypeString, + Computed: true, + Description: "ckey", + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "meta", + }, + "active": { + Type: schema.TypeBool, + Computed: true, + Description: "active", + }, + "apiaccess": { + Type: schema.TypeMap, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "apiaccess", + }, + "authkey": { + Type: schema.TypeString, + Computed: true, + Description: "authkey", + }, + "authkeys": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "authkeys", + }, + "data": { + Type: schema.TypeString, + Computed: true, + Description: "data", + }, + "description": { + Type: schema.TypeString, + Computed: true, + Description: "description", + }, + "domain": { + Type: schema.TypeString, + Computed: true, + Description: "domain", + }, + "emails": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "emails", + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "gid", + }, + "groups": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "groups", + }, + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "guid", + }, + "user_id": { + Type: schema.TypeString, + Computed: true, + Description: "user id", + }, + "last_check": { + Type: schema.TypeInt, + Computed: true, + Description: "last_check", + }, + "mobile": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "mobile", + }, + "password": { + Type: schema.TypeString, + Computed: true, + Description: "password", + }, + "protected": { + Type: schema.TypeBool, + Computed: true, + Description: "protected", + }, + "roles": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "roles", + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + Description: "service_account", + }, + "xmpp": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "xmpp", + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + Description: "entry_count", + }, + } +} + +func resourceUserSchemaMake() map[string]*schema.Schema { + log.Debugf("resourceUserSchemaMake: invoked") + return map[string]*schema.Schema{ + "username": { + Type: schema.TypeString, + Required: true, + Description: "ID of user", + }, + "emailaddress": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "email addresses of the user", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Description: "password of user", + }, + "groups": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "list of groups this user belongs to", + }, + "ckey": { + Type: schema.TypeString, + Computed: true, + Description: "ckey", + }, + "meta": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "meta", + }, + "active": { + Type: schema.TypeBool, + Computed: true, + Description: "active", + }, + "apiaccess": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "list of apiaccess groups this user belongs to", + }, + "authkey": { + Type: schema.TypeString, + Computed: true, + Description: "authkey", + }, + "auth_keys": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "authkeys", + }, + "data": { + Type: schema.TypeString, + Computed: true, + Description: "data", + }, + "description": { + Type: schema.TypeString, + Computed: true, + Description: "description", + }, + "domain": { + Type: schema.TypeString, + Computed: true, + Description: "domain", + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + Description: "gid", + }, + "guid": { + Type: schema.TypeString, + Computed: true, + Description: "guid", + }, + "last_check": { + Type: schema.TypeInt, + Computed: true, + Description: "last_check", + }, + "mobile": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "mobile", + }, + "protected": { + Type: schema.TypeBool, + Computed: true, + Description: "protected", + }, + "roles": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "roles", + }, + "service_account": { + Type: schema.TypeBool, + Computed: true, + Description: "service_account", + }, + "xmpp": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "xmpp", + }, + } +} diff --git a/internal/service/cloudbroker/user/utility_user.go b/internal/service/cloudbroker/user/utility_user.go new file mode 100644 index 0000000..0e754ae --- /dev/null +++ b/internal/service/cloudbroker/user/utility_user.go @@ -0,0 +1,108 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 user + +import ( + "context" + + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/user" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" +) + +func utilityUserCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*user.ItemUser, error) { + c := m.(*controller.ControllerCfg) + req := user.GetRequest{} + + if d.Id() != "" { + req.UserID = d.Id() + } else { + req.UserID = d.Get("user_id").(string) + } + + userInfo, err := c.CloudBroker().User().Get(ctx, req) + if err != nil { + return nil, err + } + + return userInfo, nil +} + +func utilityUserAPIAccessGroupsConfigure(ctx context.Context, d *schema.ResourceData, m interface{}) error { + + c := m.(*controller.ControllerCfg) + + old_set, new_set := d.GetChange("apiaccess") + + leave_set := old_set.(*schema.Set).Difference(new_set.(*schema.Set)) + + log.Debugf("utilityUserAPIAccessGroupsConfigure: leave set has %d items for Username %s", leave_set.Len(), d.Id()) + + if leave_set.Len() > 0 { + + for _, v := range leave_set.List() { + + leaveReq := user.APIAccessLeaveRequest{ + UserID: d.Id(), + APIAccessID: uint64(v.(int)), + } + _, err := c.CloudBroker().User().APIAccessLeave(ctx, leaveReq) + if err != nil { + return err + } + } + } + + join_set := new_set.(*schema.Set).Difference(old_set.(*schema.Set)) + + log.Debugf("utilityUserAPIAccessGroupsConfigure: join set has %d items for Username %s", join_set.Len(), d.Id()) + + if join_set.Len() > 0 { + + for _, v := range join_set.List() { + + joinReq := user.APIAccessJoinRequest{ + UserID: d.Id(), + APIAccessID: uint64(v.(int)), + } + _, err := c.CloudBroker().User().APIAccessJoin(ctx, joinReq) + if err != nil { + return err + } + } + } + + return nil +} diff --git a/internal/service/cloudbroker/user/utility_user_get_audit.go b/internal/service/cloudbroker/user/utility_user_get_audit.go new file mode 100644 index 0000000..74481b3 --- /dev/null +++ b/internal/service/cloudbroker/user/utility_user_get_audit.go @@ -0,0 +1,77 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 user + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/user" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func utilityUserGetAuditCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*user.ListAudits, error) { + c := m.(*controller.ControllerCfg) + req := user.GetAuditRequest{} + + if username, ok := d.GetOk("username"); ok { + req.Username = username.(string) + } + if call, ok := d.GetOk("call"); ok { + req.Call = call.(string) + } + if statusCode, ok := d.GetOk("status_code"); ok { + req.StatusCode = uint64(statusCode.(int)) + } + + if timestampAt, ok := d.GetOk("timestamp_at"); ok { + req.TimestampAt = uint64(timestampAt.(int)) + } + if timestampTo, ok := d.GetOk("timestamp_to"); ok { + req.TimestampTo = uint64(timestampTo.(int)) + } + + if Page, ok := d.GetOk("page"); ok { + req.Page = uint64(Page.(int)) + } + if Size, ok := d.GetOk("size"); ok { + req.Size = uint64(Size.(int)) + } + + audits, err := c.CloudBroker().User().GetAudit(ctx, req) + if err != nil { + return nil, err + } + + return &audits, nil +} diff --git a/internal/service/cloudbroker/user/utility_user_list.go b/internal/service/cloudbroker/user/utility_user_list.go new file mode 100644 index 0000000..dcb745b --- /dev/null +++ b/internal/service/cloudbroker/user/utility_user_list.go @@ -0,0 +1,77 @@ +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Sergey Kisil, + +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 user + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/user" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" +) + +func utilityUserListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*user.ListUsers, error) { + c := m.(*controller.ControllerCfg) + req := user.ListRequest{} + + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = byId.(string) + } + + if active, ok := d.GetOk("active"); ok { + req.Active = active.(bool) + } + + if serviceAccount, ok := d.GetOk("service_account"); ok { + req.ServiceAccount = serviceAccount.(bool) + } + + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + + if Page, ok := d.GetOk("page"); ok { + req.Page = uint64(Page.(int)) + } + + if Size, ok := d.GetOk("size"); ok { + req.Size = uint64(Size.(int)) + } + + usersList, err := c.CloudBroker().User().List(ctx, req) + if err != nil { + return nil, err + } + + return usersList, nil +} diff --git a/internal/service/cloudbroker/vfpool/data_source_vfpool.go b/internal/service/cloudbroker/vfpool/data_source_vfpool.go new file mode 100644 index 0000000..27062c9 --- /dev/null +++ b/internal/service/cloudbroker/vfpool/data_source_vfpool.go @@ -0,0 +1,68 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 vfpool + +import ( + "context" + "strconv" + + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceVFPoolRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vfpool, err := utilityVFpoolCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + d.SetId(strconv.Itoa(d.Get("vfpool_id").(int))) + flattenVFPoolDataSource(d, vfpool) + return nil +} + +func DataSourceVFPool() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceVFPoolRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceVFPoolSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/vfpool/data_source_vfpool_list.go b/internal/service/cloudbroker/vfpool/data_source_vfpool_list.go new file mode 100644 index 0000000..4818f2b --- /dev/null +++ b/internal/service/cloudbroker/vfpool/data_source_vfpool_list.go @@ -0,0 +1,70 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 vfpool + +import ( + "context" + + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceVFPoolListRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vfpoolList, err := utilityVFpoolListCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") // ensure ID is empty in this case + return diag.FromErr(err) + } + id := uuid.New() + d.SetId(id.String()) + d.Set("items", flattenVFPoolList(vfpoolList)) + d.Set("entry_count", vfpoolList.EntryCount) + return nil +} + +func DataSourceVFPoolList() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + ReadContext: dataSourceVFPoolListRead, + + Timeouts: &schema.ResourceTimeout{ + Read: &constants.Timeout30s, + Default: &constants.Timeout60s, + }, + + Schema: dataSourceVFPoolListSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/vfpool/flattens.go b/internal/service/cloudbroker/vfpool/flattens.go new file mode 100644 index 0000000..2d2d7a1 --- /dev/null +++ b/internal/service/cloudbroker/vfpool/flattens.go @@ -0,0 +1,142 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vfpool + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vfpool" +) + +func flattenVFPoolList(vfpooll *vfpool.ListVFPool) []map[string]interface{} { + log.Debugf("flattenVFPoolList start") + res := make([]map[string]interface{}, 0, len(vfpooll.Data)) + for _, vfpool := range vfpooll.Data { + temp := map[string]interface{}{ + "account_access": vfpool.AccountAccess, + "created_time": vfpool.CreatedTime, + "description": vfpool.Description, + "gid": vfpool.GID, + "guid": vfpool.GUID, + "vfpool_id": vfpool.ID, + "name": vfpool.Name, + "rg_access": vfpool.RGAccess, + "status": vfpool.Status, + "updated_time": vfpool.UpdatedTime, + "vfs": flattenVFSList(vfpool.VFS), + } + res = append(res, temp) + } + log.Debugf("flattenVFPoolList end") + return res + +} + +func flattenVFPoolDataSource(d *schema.ResourceData, item *vfpool.RecordVFPool) error { + log.Debugf("flattenVFPoolDataSource: start decoded VFPool name %q / ID %d", + item.Name, item.ID) + + d.Set("account_access", item.AccountAccess) + d.Set("created_time", item.CreatedTime) + d.Set("description", item.Description) + d.Set("gid", item.GID) + d.Set("guid", item.GUID) + d.Set("name", item.Name) + d.Set("rg_access", item.RGAccess) + d.Set("status", item.Status) + d.Set("updated_time", item.UpdatedTime) + d.Set("vfs", flattenVFSList(item.VFS)) + + log.Debugf("flattenVFPoolDataSource: decoded VFPool name %q / ID %d, complete", + item.Name, item.ID) + return nil +} + +func flattenVFPoolResource(d *schema.ResourceData, item *vfpool.RecordVFPool) error { + log.Debugf("flattenVFPoolResource: start decoded VFPool name %q / ID %d", + item.Name, item.ID) + + d.Set("account_access", item.AccountAccess) + d.Set("created_time", item.CreatedTime) + d.Set("description", item.Description) + d.Set("gid", item.GID) + d.Set("guid", item.GUID) + d.Set("vfpool_id", item.ID) + d.Set("name", item.Name) + d.Set("rg_access", item.RGAccess) + d.Set("status", item.Status) + d.Set("updated_time", item.UpdatedTime) + d.Set("vfs", flattenVFSList(item.VFS)) + + log.Debugf("flattenVFPoolResource: decoded VFPool name %q / ID %d, complete", + item.Name, item.ID) + return nil +} + + +func flattenVFSList(vfsItem []vfpool.VFS) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vfsItem)) + for _, item := range vfsItem { + temp := map[string]interface{}{ + "node_id": item.NodeID, + "vf_list": flattenVFList(item.VFList), + } + res = append(res, temp) + } + return res +} + +func flattenVFList(vfItem vfpool.VFList) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vfItem)) + for _, item := range vfItem { + temp := map[string]interface{}{ + "nic_name": item.NicName, + "vfs_info": flattenVFInfoList(item.VFSInfo), + } + res = append(res, temp) + } + return res +} + +func flattenVFInfoList(vfInfo vfpool.VFSInfoList) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vfInfo)) + for _, item := range vfInfo { + temp := map[string]interface{}{ + "id": item.ID, + "claimed": item.Claimed, + "vm_id": item.VMID, + } + res = append(res, temp) + } + return res +} diff --git a/internal/service/cloudbroker/vfpool/resource_check_input_values.go b/internal/service/cloudbroker/vfpool/resource_check_input_values.go new file mode 100644 index 0000000..3c8ced4 --- /dev/null +++ b/internal/service/cloudbroker/vfpool/resource_check_input_values.go @@ -0,0 +1,24 @@ +package vfpool + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic" +) + +func checkParamsExistence(ctx context.Context, c *controller.ControllerCfg, accountIDs, rgIDs []uint64) diag.Diagnostics { + var errs []error + + if err := ic.ExistAccouts(ctx, accountIDs, c); err != nil { + errs = append(errs, err) + } + + if err := ic.ExistRGs(ctx, rgIDs, c); err != nil { + errs = append(errs, err) + } + + return dc.ErrorsToDiagnostics(errs) +} diff --git a/internal/service/cloudbroker/vfpool/resource_vfpool.go b/internal/service/cloudbroker/vfpool/resource_vfpool.go new file mode 100644 index 0000000..5ea466b --- /dev/null +++ b/internal/service/cloudbroker/vfpool/resource_vfpool.go @@ -0,0 +1,230 @@ +/* +Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 vfpool + +import ( + "context" + "strconv" + + "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/vfpool" + "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" +) + +func resourceVFPoolCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vfpoolName := d.Get("name").(string) + + log.Debugf("resourceVFPoolCreate: called VFPool with name %s", vfpoolName) + + c := m.(*controller.ControllerCfg) + + req := vfpool.CreateRequest{ + Name: vfpoolName, + } + + if desc, ok := d.GetOk("description"); ok { + req.Description = desc.(string) + } + + if accountAccess, ok := d.GetOk("account_access"); ok { + accountAccessArray := accountAccess.(*schema.Set).List() + + req.AccountAccess = make([]uint64, 0, len(accountAccessArray)) + + for _, access := range accountAccessArray { + req.AccountAccess = append(req.AccountAccess, uint64(access.(int))) + } + } + + if rgAccess, ok := d.GetOk("rg_access"); ok { + rgAccessArray := rgAccess.(*schema.Set).List() + + req.RGAccess = make([]uint64, 0, len(rgAccessArray)) + + for _, access := range rgAccessArray { + req.RGAccess = append(req.RGAccess, uint64(access.(int))) + } + } + + if err := checkParamsExistence(ctx, c, req.AccountAccess, req.RGAccess); err != nil { + return err + } + + config, configOk := d.GetOk("config") + if configOk { + configArray := config.(*schema.Set).List() + req.Config = make([]vfpool.Config, 0, len(configArray)) + + for _, access := range configArray { + temp := access.(map[string]interface{}) + + vfArray := temp["vf_ids"].([]interface{}) + resVfIds := make([]uint64, 0, len(vfArray)) + + for _, vfID := range vfArray { + resVfIds = append(resVfIds, uint64(vfID.(int))) + } + + reqTemp := vfpool.Config{ + NodeID: uint64(temp["node_id"].(int)), + NicName: temp["nic_name"].(string), + VFIDs: resVfIds, + } + req.Config = append(req.Config, reqTemp) + } + } + + vfPoolID, err := c.CloudBroker().VFPool().Create(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(strconv.FormatUint(vfPoolID, 10)) + + warnings := dc.Warnings{} + + if enable, ok := d.GetOk("enable"); ok { + if err := utilityVFPoolEnabled(ctx, m, enable.(bool), vfPoolID, configOk); err != nil { + warnings.Add(err) + } + } + + log.Debugf("resourceVFPoolCreate: create VFPool with ID: %d, complete", vfPoolID) + return append(resourceVFPoolRead(ctx, d, m), warnings.Get()...) +} + +func resourceVFPoolRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceVFPoolRead: called VFPool with id %s", d.Id()) + + vfPool, err := utilityVFpoolCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + flattenVFPoolResource(d, vfPool) + + log.Debugf("resourceVFPoolRead: read VFPool with id %s, complete", d.Id()) + return nil +} + +func resourceVFPoolUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + vfPoolID, _ := strconv.ParseUint(d.Id(), 10, 64) + + log.Debugf("resourceVFPoolUpdate: called VFPool with id %d", vfPoolID) + + _, ok := d.GetOk("config") + + if d.HasChanges("name,", "description", "account_access", "rg_access,", "config") { + if err := utilityVFPoolUpdate(ctx, d, m, vfPoolID); err != nil { + return diag.FromErr(err) + } + } + + if d.HasChange("enable") { + if err := utilityVFPoolEnabled(ctx, m, d.Get("enable").(bool), vfPoolID, ok); err != nil { + return diag.FromErr(err) + } + } + + log.Debugf("resourceVFPoolUpdate: update VFPool with id %d, complete", vfPoolID) + + return resourceVFPoolRead(ctx, d, m) +} + +func resourceVFPoolDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Debugf("resourceVFPoolDelete: called VFPool with id %s", d.Id()) + + vfPool, err := utilityVFpoolCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return diag.FromErr(err) + } + + c := m.(*controller.ControllerCfg) + + req := vfpool.DeleteRequest{ + VFPoolID: vfPool.ID, + } + + if vfPool.Status == "ENABLED" || vfPool.Status == "CREATED" { + reqDisable := vfpool.DisableRequest{ + VFPoolID: vfPool.ID, + } + + log.Debugf("resourceVFPoolDelete: need to disable vfPool with ID: %d, after delete", vfPool.ID) + _, err = c.CloudBroker().VFPool().Disable(ctx, reqDisable) + if err != nil { + return diag.FromErr(err) + } + log.Debugf("resourceVFPoolDelete: disable vfPool with ID: %d, complete", vfPool.ID) + } + + _, err = c.CloudBroker().VFPool().Delete(ctx, req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId("") + + return nil +} + +func ResourceVFPool() *schema.Resource { + return &schema.Resource{ + SchemaVersion: 1, + + CreateContext: resourceVFPoolCreate, + ReadContext: resourceVFPoolRead, + UpdateContext: resourceVFPoolUpdate, + DeleteContext: resourceVFPoolDelete, + + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: &constants.Timeout20m, + Read: &constants.Timeout20m, + Update: &constants.Timeout20m, + Delete: &constants.Timeout20m, + Default: &constants.Timeout20m, + }, + + Schema: resourceVFPoolSchemaMake(), + } +} diff --git a/internal/service/cloudbroker/vfpool/schema.go b/internal/service/cloudbroker/vfpool/schema.go new file mode 100644 index 0000000..97e5731 --- /dev/null +++ b/internal/service/cloudbroker/vfpool/schema.go @@ -0,0 +1,394 @@ +package vfpool + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceVFPoolSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "vfpool_id": { + Type: schema.TypeInt, + Required: true, + }, + "account_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "rg_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vfs": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vf_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "nic_name": { + Type: schema.TypeString, + Computed: true, + }, + "vfs_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "claimed": { + Type: schema.TypeBool, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + return res +} + +func dataSourceVFPoolListSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "by_id": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by ID", + }, + "gid": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by Grid ID", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Find by name", + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: "Find by description", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "Find by status", + }, + "account_access": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by accountAccess", + }, + "rg_access": { + Type: schema.TypeInt, + Optional: true, + Description: "Find by rgAccess", + }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, + "page": { + Type: schema.TypeInt, + Optional: true, + Description: "Page number", + }, + "size": { + Type: schema.TypeInt, + Optional: true, + Description: "Page size", + }, + "items": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "vfpool_id": { + Type: schema.TypeInt, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "rg_access": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vfs": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vf_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "nic_name": { + Type: schema.TypeString, + Computed: true, + }, + "vfs_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "claimed": { + Type: schema.TypeBool, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "entry_count": { + Type: schema.TypeInt, + Computed: true, + }, + } + + return res +} + +func resourceVFPoolSchemaMake() map[string]*schema.Schema { + res := map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Name of device", + }, + "description": { + Type: schema.TypeString, + Computed: true, + Optional: true, + Description: "Description", + }, + "account_access": { + Type: schema.TypeSet, + Computed: true, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of account IDs", + }, + "rg_access": { + Type: schema.TypeSet, + Computed: true, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + Description: "List of RG IDs", + }, + "config": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_id": { + Type: schema.TypeInt, + Required: true, + }, + "nic_name": { + Type: schema.TypeString, + Required: true, + }, + "vf_ids": { + Required: true, + Type: schema.TypeList, + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + MinItems: 1, + }, + }, + }, + Description: "List of dict describing configuration data", + }, + "enable": { + Type: schema.TypeBool, + Optional: true, + }, + "created_time": { + Type: schema.TypeInt, + Computed: true, + }, + "gid": { + Type: schema.TypeInt, + Computed: true, + }, + "guid": { + Type: schema.TypeInt, + Computed: true, + }, + "vfpool_id": { + Type: schema.TypeInt, + Computed: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "updated_time": { + Type: schema.TypeInt, + Computed: true, + }, + "vfs": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, + "vf_list": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "nic_name": { + Type: schema.TypeString, + Computed: true, + }, + "vfs_info": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeInt, + Computed: true, + }, + "claimed": { + Type: schema.TypeBool, + Computed: true, + }, + "vm_id": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + return res +} diff --git a/internal/service/cloudbroker/vfpool/utility_vfpool.go b/internal/service/cloudbroker/vfpool/utility_vfpool.go new file mode 100644 index 0000000..7fd0c98 --- /dev/null +++ b/internal/service/cloudbroker/vfpool/utility_vfpool.go @@ -0,0 +1,209 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vfpool + +import ( + "context" + "fmt" + "strconv" + + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vfpool" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + log "github.com/sirupsen/logrus" +) + +func utilityVFpoolCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vfpool.RecordVFPool, error) { + c := m.(*controller.ControllerCfg) + req := vfpool.GetRequest{} + + if d.Id() != "" { + vfpoolId, _ := strconv.ParseUint(d.Id(), 10, 64) + req.VFPoolID = vfpoolId + } else { + req.VFPoolID = uint64(d.Get("vfpool_id").(int)) + } + + vfpoolData, err := c.CloudBroker().VFPool().Get(ctx, req) + if err != nil { + return nil, err + } + + return vfpoolData, nil +} + +func utilityVFPoolEnabled(ctx context.Context, m interface{}, enable bool, vfPoolID uint64, configOk bool) error { + c := m.(*controller.ControllerCfg) + + if enable && configOk { + req := vfpool.EnableRequest{ + VFPoolID: vfPoolID, + } + _, err := c.CloudBroker().VFPool().Enable(ctx, req) + if err != nil { + return err + } + } + if enable && !configOk { + return fmt.Errorf("you must provide configuration for this resource, after enabling it") + } + if !enable { + req := vfpool.DisableRequest{ + VFPoolID: vfPoolID, + } + _, err := c.CloudBroker().VFPool().Disable(ctx, req) + if err != nil { + return err + } + } + + log.Debugf("utilityVFPoolEnabled: enable=%v vfPool ID %d after completing its resource configuration", enable, vfPoolID) + + return nil +} + +func utilityVFPoolUpdate(ctx context.Context, d *schema.ResourceData, m interface{}, vfPoolID uint64) error { + c := m.(*controller.ControllerCfg) + + vfPool, err := utilityVFpoolCheckPresence(ctx, d, m) + if err != nil { + d.SetId("") + return err + } + + req := vfpool.UpdateRequest{ + VFPoolID: vfPoolID, + } + + if d.HasChange("name") { + req.Name = d.Get("name").(string) + } + if d.HasChange("description") { + req.Description = d.Get("description").(string) + } + + if config, ok := d.GetOk("config"); ok { + configArray := config.(*schema.Set).List() + req.Config = make([]vfpool.Config, 0, len(configArray)) + + for _, access := range configArray { + temp := access.(map[string]interface{}) + + vfArray := temp["vf_ids"].([]interface{}) + resVfIds := make([]uint64, 0, len(vfArray)) + + for _, vfID := range vfArray { + resVfIds = append(resVfIds, uint64(vfID.(int))) + } + + reqTemp := vfpool.Config{ + NodeID: uint64(temp["node_id"].(int)), + NicName: temp["nic_name"].(string), + VFIDs: resVfIds, + } + req.Config = append(req.Config, reqTemp) + } + } else { + req.Config = []vfpool.Config{} + } + + if accountAccess, ok := d.GetOk("account_access"); ok { + accountAccessArray := accountAccess.(*schema.Set).List() + + req.AccountAccess = make([]uint64, 0, len(accountAccessArray)) + + for _, access := range accountAccessArray { + req.AccountAccess = append(req.AccountAccess, uint64(access.(int))) + } + + if err := ic.ExistAccouts(ctx, req.AccountAccess, c); err != nil { + return err + } + } else { + req.AccountAccess = []uint64{} + } + + if rgAccess, ok := d.GetOk("rg_access"); ok { + rgAccessArray := rgAccess.(*schema.Set).List() + + req.RGAccess = make([]uint64, 0, len(rgAccessArray)) + + for _, access := range rgAccessArray { + req.RGAccess = append(req.RGAccess, uint64(access.(int))) + } + + if err := ic.ExistRGs(ctx, req.RGAccess, c); err != nil { + return err + } + } else { + req.RGAccess = []uint64{} + } + + if vfPool.Status == "ENABLED" || vfPool.Status == "CREATED" { + reqDisable := vfpool.DisableRequest{ + VFPoolID: vfPoolID, + } + + log.Debugf("utilityVFPoolUpdate: need to disable vfPool with ID: %d, after update", vfPoolID) + _, err = c.CloudBroker().VFPool().Disable(ctx, reqDisable) + if err != nil { + return err + } + log.Debugf("utilityVFPoolUpdate: disable vfPool with ID: %d, complete", vfPoolID) + } + + _, err = c.CloudBroker().VFPool().Update(ctx, req) + if err != nil { + return err + } + log.Debugf("utilityVFPoolUpdate: update vfPool with ID: %d, complete with params=%v", vfPoolID, req) + + if len(d.Get("config").(*schema.Set).List()) > 0 && d.Get("enable").(bool) { + reqEnable := vfpool.EnableRequest{ + VFPoolID: vfPoolID, + } + + log.Debugf("utilityVFPoolUpdate: start to enable vfPool with ID: %d, after update", vfPoolID) + _, err = c.CloudBroker().VFPool().Enable(ctx, reqEnable) + if err != nil { + return err + } + log.Debugf("utilityVFPoolUpdate: enable vfPool with ID: %d, complete", vfPoolID) + } else { + return (fmt.Errorf("the vfPool is not enabled after update, you must provide configuration for this resource, after enabling it")) + } + + return nil +} diff --git a/internal/service/cloudbroker/vfpool/utility_vfpool_list.go b/internal/service/cloudbroker/vfpool/utility_vfpool_list.go new file mode 100644 index 0000000..cb23a69 --- /dev/null +++ b/internal/service/cloudbroker/vfpool/utility_vfpool_list.go @@ -0,0 +1,85 @@ +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, +Kasim Baybikov, + +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 vfpool + +import ( + "context" + + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vfpool" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityVFpoolListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vfpool.ListVFPool, error) { + c := m.(*controller.ControllerCfg) + req := vfpool.ListRequest{} + + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byId.(int)) + } + if gid, ok := d.GetOk("gid"); ok { + req.GID = uint64(gid.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if description, ok := d.GetOk("description"); ok { + req.Description = description.(string) + } + if status, ok := d.GetOk("status"); ok { + req.Status = status.(string) + } + if accountAccess, ok := d.GetOk("account_access"); ok { + req.AccountAccess = uint64(accountAccess.(int)) + } + if rgAccess, ok := d.GetOk("rg_access"); ok { + req.RGAccess = uint64(rgAccess.(int)) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + + vfpoolList, err := c.CloudBroker().VFPool().List(ctx, req) + if err != nil { + return nil, err + } + + return vfpoolList, nil +} diff --git a/internal/service/cloudbroker/vgpu/api.go b/internal/service/cloudbroker/vgpu/api.go index df28688..a0b096f 100644 --- a/internal/service/cloudbroker/vgpu/api.go +++ b/internal/service/cloudbroker/vgpu/api.go @@ -1,34 +1,34 @@ -/* -Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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 vgpu - -const vgpuListAPI = "/restmachine/cloudbroker/vgpu/list" +/* +Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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 vgpu + +const VGPU_LIST_API = "/restmachine/cloudbroker/vgpu/list" diff --git a/internal/service/cloudbroker/vins/data_source_vins_list_deleted.go b/internal/service/cloudbroker/vins/data_source_vins_list_deleted.go index 780a208..82d6b6c 100644 --- a/internal/service/cloudbroker/vins/data_source_vins_list_deleted.go +++ b/internal/service/cloudbroker/vins/data_source_vins_list_deleted.go @@ -50,7 +50,7 @@ func dataSourceVinsListDeletedRead(ctx context.Context, d *schema.ResourceData, id := uuid.New() d.SetId(id.String()) - d.Set("items", flattenVinsList(vinsList)) + d.Set("items", flattenVinsListDeleted(vinsList)) d.Set("entry_count", vinsList.EntryCount) return nil diff --git a/internal/service/cloudbroker/vins/flattens.go b/internal/service/cloudbroker/vins/flattens.go index e4bd2d5..637d5be 100644 --- a/internal/service/cloudbroker/vins/flattens.go +++ b/internal/service/cloudbroker/vins/flattens.go @@ -406,6 +406,7 @@ func flattenVinsListInterfaces(i vins.ListInterfaces) []map[string]interface{} { "net_id": v.NetID, "net_mask": v.NetMask, "net_type": v.NetType, + "node_id": v.NodeID, "pci_slot": v.PCISlot, "qos": flattenVinsQOS(v.QOS), "target": v.Target, @@ -418,6 +419,50 @@ func flattenVinsListInterfaces(i vins.ListInterfaces) []map[string]interface{} { } func flattenVinsList(vl *vins.ListVINS) []map[string]interface{} { + res := make([]map[string]interface{}, 0, len(vl.Data)) + for _, v := range vl.Data { + temp := map[string]interface{}{ + "account_id": v.AccountID, + "account_name": v.AccountName, + "created_by": v.CreatedBy, + "created_time": v.CreatedTime, + "default_gw": v.DefaultGW, + "default_qos": flattenVinsQOS(v.DefaultQOS), + "deleted_by": v.DeletedBy, + "deleted_time": v.DeletedTime, + "description": v.Description, + "external_ip": v.ExternalIP, + "extnet_id": v.ExtnetId, + "free_ips": v.FreeIPs, + "gid": v.GID, + "guid": v.GUID, + "vins_id": v.ID, + "name": v.Name, + "lock_status": v.LockStatus, + "manager_id": v.ManagerID, + "manager_type": v.ManagerType, + "milestones": v.Milestones, + "netmask": v.NetMask, + "network": v.Network, + "pre_reservations_num": v.PreReservationsNum, + "pri_vnf_dev_id": v.PriVNFDevID, + "redundant": v.Redundant, + "rg_id": v.RGID, + "rg_name": v.RGName, + "sec_vnf_dev_id": v.SecVNFDevID, + "status": v.Status, + "updated_by": v.UpdatedBy, + "updated_time": v.UpdatedTime, + "user_managed": v.UserManaged, + "vnfs": flattenVinsVNFs(v.VNFs), + "vxlan_id": v.VXLANID, + } + res = append(res, temp) + } + return res +} + +func flattenVinsListDeleted(vl *vins.ListVINS) []map[string]interface{} { res := make([]map[string]interface{}, 0, len(vl.Data)) for _, v := range vl.Data { temp := map[string]interface{}{ diff --git a/internal/service/cloudbroker/vins/resource_utility.go b/internal/service/cloudbroker/vins/resource_utility.go index 20cb7ca..fd77299 100644 --- a/internal/service/cloudbroker/vins/resource_utility.go +++ b/internal/service/cloudbroker/vins/resource_utility.go @@ -34,6 +34,7 @@ package vins import ( "context" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vins" @@ -77,6 +78,13 @@ func createVinsInAcc(ctx context.Context, d *schema.ResourceData, m interface{}, } req.Routes = routes } + if dns, ok := d.GetOk("dns"); ok { + dnsInterface := dns.(*schema.Set).List() + req.DNSList = make([]string, 0, len(dnsInterface)) + for _, item := range dnsInterface { + req.DNSList = append(req.DNSList, item.(string)) + } + } return req, nil } @@ -123,6 +131,13 @@ func createVinsInRG(ctx context.Context, d *schema.ResourceData, m interface{}, } req.Routes = routes } + if dns, ok := d.GetOk("dns"); ok { + dnsInterface := dns.(*schema.Set).List() + req.DNSList = make([]string, 0, len(dnsInterface)) + for _, item := range dnsInterface { + req.DNSList = append(req.DNSList, item.(string)) + } + } return req, nil } diff --git a/internal/service/cloudbroker/vins/resource_vins.go b/internal/service/cloudbroker/vins/resource_vins.go index 3313d7a..9a967a9 100644 --- a/internal/service/cloudbroker/vins/resource_vins.go +++ b/internal/service/cloudbroker/vins/resource_vins.go @@ -284,6 +284,12 @@ func resourceVinsUpdate(ctx context.Context, d *schema.ResourceData, m interface } } + if d.HasChange("dns") { + if err := resourceVinsChangeDNS(ctx, d, m); err != nil { + warnings.Add(err) + } + } + if d.HasChange("default_qos") { if err := resourceVinsChangeDefaultQos(ctx, d, m); err != nil { warnings.Add(err) @@ -441,9 +447,12 @@ func resourceVinsNatRuleAdd(ctx context.Context, d *schema.ResourceData, m inter req := vins.NATRuleAddRequest{ VINSID: vinsId, IntIP: natRule["int_ip"].(string), - IntPort: uint64(natRule["int_port"].(int)), ExtPortStart: uint64(natRule["ext_port_start"].(int)), } + + if intPort, ok := natRule["int_port"]; ok { + req.IntPort = uint64(intPort.(int)) + } if extPortEnd, ok := natRule["ext_port_end"]; ok { req.ExtPortEnd = uint64(extPortEnd.(int)) } @@ -646,10 +655,12 @@ func resourceVinsChangeNatRule(ctx context.Context, d *schema.ResourceData, m in req := vins.NATRuleAddRequest{ VINSID: vinsId, IntIP: natRule["int_ip"].(string), - IntPort: uint64(natRule["int_port"].(int)), ExtPortStart: uint64(natRule["ext_port_start"].(int)), } + if natRule["int_port"].(int) != 0 { + req.IntPort = uint64(natRule["int_port"].(int)) + } if natRule["ext_port_end"].(int) != 0 { req.ExtPortEnd = uint64(natRule["ext_port_end"].(int)) } @@ -667,6 +678,31 @@ func resourceVinsChangeNatRule(ctx context.Context, d *schema.ResourceData, m in return errs } +func resourceVinsChangeDNS(ctx context.Context, d *schema.ResourceData, m interface{}) error { + c := m.(*controller.ControllerCfg) + + vinsId := uint64(d.Get("vins_id").(int)) + + // empty "dns" is allowed, it will update vnfs.dhcp.config.dns from current values to empty list + dnsInterface := d.Get("dns").(*schema.Set).List() + dnsList := make([]string, 0, len(dnsInterface)) + for _, item := range dnsInterface { + dnsList = append(dnsList, item.(string)) + } + + req := vins.DNSApplyRequest{ + VINSID: vinsId, + DNSList: dnsList, + } + + _, err := c.CloudBroker().VINS().DNSApply(ctx, req) + if err != nil { + return err + } + + return nil +} + func resourceVinsChangeDefaultQos(ctx context.Context, d *schema.ResourceData, m interface{}) error { c := m.(*controller.ControllerCfg) diff --git a/internal/service/cloudbroker/vins/schema.go b/internal/service/cloudbroker/vins/schema.go index 747d3f5..1d4b6e7 100644 --- a/internal/service/cloudbroker/vins/schema.go +++ b/internal/service/cloudbroker/vins/schema.go @@ -215,6 +215,10 @@ func dataSourceVinsSchemaMake() map[string]*schema.Schema { Computed: true, Description: "net type", }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, @@ -1187,12 +1191,22 @@ func dataSourceVinsListSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Find by ext ip", }, + "vnfdev_id": { + Type: schema.TypeInt, + Optional: true, + Description: "find by VNF Device id", + }, "include_deleted": { Type: schema.TypeBool, Optional: true, Default: false, Description: "include deleted computes", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -1268,6 +1282,14 @@ func dataSourceVinsListSchemaMake() map[string]*schema.Schema { Type: schema.TypeString, Computed: true, }, + "extnet_id": { + Type: schema.TypeInt, + Computed: true, + }, + "free_ips": { + Type: schema.TypeInt, + Computed: true, + }, "gid": { Type: schema.TypeInt, Computed: true, @@ -1423,6 +1445,11 @@ func dataSourceVinsListDeletedSchemaMake() map[string]*schema.Schema { Optional: true, Description: "Filter by external IP", }, + "sort_by": { + Type: schema.TypeString, + Optional: true, + Description: "sort by one of supported fields, format +|-(field)", + }, "page": { Type: schema.TypeInt, Optional: true, @@ -2025,7 +2052,8 @@ func resourceVinsSchemaMake() map[string]*schema.Schema { }, "int_port": { Type: schema.TypeInt, - Required: true, + Optional: true, + Computed: true, }, "ext_port_start": { Type: schema.TypeInt, @@ -2103,6 +2131,13 @@ func resourceVinsSchemaMake() map[string]*schema.Schema { }, }, }, + "dns": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, // other resource fields "vins_id": { @@ -2309,6 +2344,10 @@ func resourceVinsSchemaMake() map[string]*schema.Schema { Computed: true, Description: "net type", }, + "node_id": { + Type: schema.TypeInt, + Computed: true, + }, "pci_slot": { Type: schema.TypeInt, Computed: true, diff --git a/internal/service/cloudbroker/vins/utility_vins_list.go b/internal/service/cloudbroker/vins/utility_vins_list.go index bfc7daa..1b9d2a4 100644 --- a/internal/service/cloudbroker/vins/utility_vins_list.go +++ b/internal/service/cloudbroker/vins/utility_vins_list.go @@ -1,80 +1,86 @@ -/* -Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. -Authors: -Petr Krutov, -Stanislav Solovev, - -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" - - log "github.com/sirupsen/logrus" - "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vins" - "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" -) - -func utilityVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vins.ListVINS, error) { - c := m.(*controller.ControllerCfg) - req := vins.ListRequest{} - - if byId, ok := d.GetOk("by_id"); ok { - req.ByID = uint64(byId.(int)) - } - if name, ok := d.GetOk("name"); ok { - req.Name = name.(string) - } - if accountId, ok := d.GetOk("account_id"); ok { - req.AccountID = uint64(accountId.(int)) - } - if rgId, ok := d.GetOk("rg_id"); ok { - req.RGID = uint64(rgId.(int)) - } - if extIp, ok := d.GetOk("ext_ip"); ok { - req.ExtIP = extIp.(string) - } - if page, ok := d.GetOk("page"); ok { - req.Page = uint64(page.(int)) - } - if size, ok := d.GetOk("size"); ok { - req.Size = uint64(size.(int)) - } - if includeDeleted, ok := d.GetOk("include_deleted"); ok { - req.IncludeDeleted = includeDeleted.(bool) - } - - log.Debugf("utilityVinsListCheckPresence") - vinsList, err := c.CloudBroker().VINS().List(ctx, req) - if err != nil { - return nil, err - } - - return vinsList, nil -} +/* +Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved. +Authors: +Petr Krutov, +Stanislav Solovev, + +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" + + log "github.com/sirupsen/logrus" + "repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/vins" + "repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func utilityVinsListCheckPresence(ctx context.Context, d *schema.ResourceData, m interface{}) (*vins.ListVINS, error) { + c := m.(*controller.ControllerCfg) + req := vins.ListRequest{} + + if byId, ok := d.GetOk("by_id"); ok { + req.ByID = uint64(byId.(int)) + } + if name, ok := d.GetOk("name"); ok { + req.Name = name.(string) + } + if accountId, ok := d.GetOk("account_id"); ok { + req.AccountID = uint64(accountId.(int)) + } + if rgId, ok := d.GetOk("rg_id"); ok { + req.RGID = uint64(rgId.(int)) + } + if extIp, ok := d.GetOk("ext_ip"); ok { + req.ExtIP = extIp.(string) + } + if VNFDevId, ok := d.GetOk("vnfdev_id"); ok { + req.VNFDevID = uint64(VNFDevId.(int)) + } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } + if page, ok := d.GetOk("page"); ok { + req.Page = uint64(page.(int)) + } + if size, ok := d.GetOk("size"); ok { + req.Size = uint64(size.(int)) + } + if includeDeleted, ok := d.GetOk("include_deleted"); ok { + req.IncludeDeleted = includeDeleted.(bool) + } + + log.Debugf("utilityVinsListCheckPresence") + vinsList, err := c.CloudBroker().VINS().List(ctx, req) + if err != nil { + return nil, err + } + + return vinsList, nil +} diff --git a/internal/service/cloudbroker/vins/utility_vins_list_deleted.go b/internal/service/cloudbroker/vins/utility_vins_list_deleted.go index f815e9e..e59dadc 100644 --- a/internal/service/cloudbroker/vins/utility_vins_list_deleted.go +++ b/internal/service/cloudbroker/vins/utility_vins_list_deleted.go @@ -60,6 +60,9 @@ func utilityVinsListDeletedCheckPresence(ctx context.Context, d *schema.Resource if ext_ip, ok := d.GetOk("ext_ip"); ok { req.ExtIP = ext_ip.(string) } + if sortBy, ok := d.GetOk("sort_by"); ok { + req.SortBy = sortBy.(string) + } if page, ok := d.GetOk("page"); ok { req.Page = uint64(page.(int)) } diff --git a/internal/validators/validator.go b/internal/validators/validator.go index d72ad64..6cca215 100644 --- a/internal/validators/validator.go +++ b/internal/validators/validator.go @@ -13,7 +13,7 @@ func DivisibleBy(divisibility int) schema.SchemaValidateFunc { errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) return warnings, errors } - if total % divisibility != 0 { + if total%divisibility != 0 { errors = append(errors, fmt.Errorf("expected value of %s to be divisible by %d", k, divisibility)) } diff --git a/samples/cloudapi/data_account/main.tf b/samples/cloudapi/account/data_account/main.tf similarity index 96% rename from samples/cloudapi/data_account/main.tf rename to samples/cloudapi/account/data_account/main.tf index 2691054..3f29cce 100644 --- a/samples/cloudapi/data_account/main.tf +++ b/samples/cloudapi/account/data_account/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации об аккаунте - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,9 +29,8 @@ provider "decort" { data "decort_account" "a" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 - } output "test" { diff --git a/samples/cloudapi/data_account_audits_list/main.tf b/samples/cloudapi/account/data_account_audits_list/main.tf similarity index 96% rename from samples/cloudapi/data_account_audits_list/main.tf rename to samples/cloudapi/account/data_account_audits_list/main.tf index 86a3bb0..786c5c7 100644 --- a/samples/cloudapi/data_account_audits_list/main.tf +++ b/samples/cloudapi/account/data_account_audits_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации об использовании аккаунта - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,9 +30,8 @@ provider "decort" { data "decort_account_audits_list" "aal" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 - } output "test" { diff --git a/samples/cloudapi/data_account_computes_list/main.tf b/samples/cloudapi/account/data_account_computes_list/main.tf similarity index 83% rename from samples/cloudapi/data_account_computes_list/main.tf rename to samples/cloudapi/account/data_account_computes_list/main.tf index 5927386..21d8adb 100644 --- a/samples/cloudapi/data_account_computes_list/main.tf +++ b/samples/cloudapi/account/data_account_computes_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка computes, используемых аккаунтом - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_account_computes_list" "acl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 1111 #фильтр по id compute #опциональный параметр - #тип - число + #тип - целое число #compute_id = 100 #фильтр по имени compute @@ -49,7 +49,7 @@ data "decort_account_computes_list" "acl" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -69,18 +69,24 @@ data "decort_account_computes_list" "acl" { #фильтр по id внешней сети #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/data_account_consumed_units/main.tf b/samples/cloudapi/account/data_account_consumed_units/main.tf similarity index 96% rename from samples/cloudapi/data_account_consumed_units/main.tf rename to samples/cloudapi/account/data_account_consumed_units/main.tf index 373a0c5..a599f9f 100644 --- a/samples/cloudapi/data_account_consumed_units/main.tf +++ b/samples/cloudapi/account/data_account_consumed_units/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о расходуемых ресурсах аккаута */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_account_consumed_units" "acu" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 22222 } diff --git a/samples/cloudapi/data_account_consumed_units_by_type/main.tf b/samples/cloudapi/account/data_account_consumed_units_by_type/main.tf similarity index 97% rename from samples/cloudapi/data_account_consumed_units_by_type/main.tf rename to samples/cloudapi/account/data_account_consumed_units_by_type/main.tf index bcaf56e..3af3554 100644 --- a/samples/cloudapi/data_account_consumed_units_by_type/main.tf +++ b/samples/cloudapi/account/data_account_consumed_units_by_type/main.tf @@ -5,8 +5,8 @@ 1. Создавать образ 2. Редактировать образ 3. Удалять образ - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,7 +33,7 @@ provider "decort" { data "decort_account_consumed_units_by_type" "acubt" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 33333 #тип вычислительной единицы diff --git a/samples/cloudapi/data_account_deleted_list/main.tf b/samples/cloudapi/account/data_account_deleted_list/main.tf similarity index 82% rename from samples/cloudapi/data_account_deleted_list/main.tf rename to samples/cloudapi/account/data_account_deleted_list/main.tf index f00b2c7..5f0caec 100644 --- a/samples/cloudapi/data_account_deleted_list/main.tf +++ b/samples/cloudapi/account/data_account_deleted_list/main.tf @@ -3,6 +3,7 @@ Получение информации об удаленных аккаунтах Информация предоставляется только по аккаунтам, удаленным без флага permanently */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +11,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,19 +30,19 @@ provider "decort" { data "decort_account_deleted_list" "adl" { #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени аккаунта @@ -53,6 +54,12 @@ data "decort_account_deleted_list" "adl" { #опциональный параметр #тип - строка #acl = "test" + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" } output "test" { diff --git a/samples/cloudapi/data_account_disks_list/main.tf b/samples/cloudapi/account/data_account_disks_list/main.tf similarity index 76% rename from samples/cloudapi/data_account_disks_list/main.tf rename to samples/cloudapi/account/data_account_disks_list/main.tf index 5f65d5f..5330826 100644 --- a/samples/cloudapi/data_account_disks_list/main.tf +++ b/samples/cloudapi/account/data_account_disks_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о дисках, которые использует аккаунт - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_account_disks_list" "adl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #disk_id = 100 #фильтр по имени диска @@ -44,7 +44,7 @@ data "decort_account_disks_list" "adl" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 100 #тип диска @@ -53,14 +53,20 @@ data "decort_account_disks_list" "adl" { #возможные типы: "b" - boot_disk, "d" - data_disk #type = "d" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 } diff --git a/samples/cloudapi/data_account_flipgroups_list/main.tf b/samples/cloudapi/account/data_account_flipgroups_list/main.tf similarity index 86% rename from samples/cloudapi/data_account_flipgroups_list/main.tf rename to samples/cloudapi/account/data_account_flipgroups_list/main.tf index dcaf205..eb253a1 100644 --- a/samples/cloudapi/data_account_flipgroups_list/main.tf +++ b/samples/cloudapi/account/data_account_flipgroups_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о flipgroups, используемых аккаунтом - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_account_flipgroups_list" "afgl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 1111 #фильтр по имени flipgroup @@ -39,7 +39,7 @@ data "decort_account_flipgroups_list" "afgl" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #vins_id = 100 #фильтр по имени vins @@ -49,7 +49,7 @@ data "decort_account_flipgroups_list" "afgl" { #фильтр по id extnet #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 #фильтр по IP @@ -59,17 +59,17 @@ data "decort_account_flipgroups_list" "afgl" { #фильтр по id flipgroup #опциональный параметр - #тип - число + #тип - целое число #flipgroup_id = 100 #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 } diff --git a/samples/cloudapi/data_account_get_resource_consumption/main.tf b/samples/cloudapi/account/data_account_get_resource_consumption/main.tf similarity index 96% rename from samples/cloudapi/data_account_get_resource_consumption/main.tf rename to samples/cloudapi/account/data_account_get_resource_consumption/main.tf index 0f60f98..09765a8 100644 --- a/samples/cloudapi/data_account_get_resource_consumption/main.tf +++ b/samples/cloudapi/account/data_account_get_resource_consumption/main.tf @@ -9,12 +9,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +28,7 @@ provider "decort" { data "decort_account_resource_consumption_get" "rc_get" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 111 } diff --git a/samples/cloudapi/data_account_list/main.tf b/samples/cloudapi/account/data_account_list/main.tf similarity index 82% rename from samples/cloudapi/data_account_list/main.tf rename to samples/cloudapi/account/data_account_list/main.tf index cfc827a..d5900ea 100644 --- a/samples/cloudapi/data_account_list/main.tf +++ b/samples/cloudapi/account/data_account_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка доступных аккаунтов - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_account_list" "al" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени аккаунта @@ -47,15 +47,21 @@ data "decort_account_list" "al" { #тип - строка #status = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/data_account_reserved_units/main.tf b/samples/cloudapi/account/data_account_reserved_units/main.tf similarity index 85% rename from samples/cloudapi/data_account_reserved_units/main.tf rename to samples/cloudapi/account/data_account_reserved_units/main.tf index b00c0e3..1fa6640 100644 --- a/samples/cloudapi/data_account_reserved_units/main.tf +++ b/samples/cloudapi/account/data_account_reserved_units/main.tf @@ -1,8 +1,8 @@ /* Пример использования -Получение информии о зарезервированных вычислительных мощностях - +Получение информации о зарезервированных вычислительных мощностях */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_account_reserved_units" "aru" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 } diff --git a/samples/cloudapi/data_account_resource_consumption_list/main.tf b/samples/cloudapi/account/data_account_resource_consumption_list/main.tf similarity index 99% rename from samples/cloudapi/data_account_resource_consumption_list/main.tf rename to samples/cloudapi/account/data_account_resource_consumption_list/main.tf index d69dbfa..e68a75c 100644 --- a/samples/cloudapi/data_account_resource_consumption_list/main.tf +++ b/samples/cloudapi/account/data_account_resource_consumption_list/main.tf @@ -9,12 +9,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = diff --git a/samples/cloudapi/data_account_rg_list/main.tf b/samples/cloudapi/account/data_account_rg_list/main.tf similarity index 80% rename from samples/cloudapi/data_account_rg_list/main.tf rename to samples/cloudapi/account/data_account_rg_list/main.tf index 5bb6671..6443835 100644 --- a/samples/cloudapi/data_account_rg_list/main.tf +++ b/samples/cloudapi/account/data_account_rg_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о ресурных группах, используемых аккаунтом */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,24 +29,24 @@ provider "decort" { data "decort_account_rg_list" "argl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 66666 #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 11111 #фильтр по имени ресурсной группы @@ -55,18 +56,24 @@ data "decort_account_rg_list" "argl" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #vins_id = 100 #фильтр по id compute #опциональный параметр - #тип - число + #тип - целое число #vm_id = 100 #фильтр по статусу #опциональный параметр #тип - строка #status = "CREATED" + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" } output "test" { diff --git a/samples/cloudapi/data_account_templates_list/main.tf b/samples/cloudapi/account/data_account_templates_list/main.tf similarity index 81% rename from samples/cloudapi/data_account_templates_list/main.tf rename to samples/cloudapi/account/data_account_templates_list/main.tf index fb7a610..364c463 100644 --- a/samples/cloudapi/data_account_templates_list/main.tf +++ b/samples/cloudapi/account/data_account_templates_list/main.tf @@ -1,21 +1,21 @@ /* Пример использования Получение информации о шаблонах, используемых аккаунтом - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -29,17 +29,17 @@ provider "decort" { data "decort_account_templates_list" "atl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 #фильтр "включая удаленные шаблоны" #опциональный параметр - #тип - булев тип + #тип - булев #include_deleted = true #фильтр по id образа #опциональный параметр - #тип - число + #тип - целое число #image_id = 1111 #фильтр по имени @@ -52,15 +52,21 @@ data "decort_account_templates_list" "atl" { #тип - строка #type = "linux" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/data_account_vins_list/main.tf b/samples/cloudapi/account/data_account_vins_list/main.tf similarity index 80% rename from samples/cloudapi/data_account_vins_list/main.tf rename to samples/cloudapi/account/data_account_vins_list/main.tf index 5b319c3..a604aa2 100644 --- a/samples/cloudapi/data_account_vins_list/main.tf +++ b/samples/cloudapi/account/data_account_vins_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка vins, используемых аккаунтом - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_account_vins_list" "avl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 22222 #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #vins_id = 100 #фильтр по имени vins @@ -44,7 +44,7 @@ data "decort_account_vins_list" "avl" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 11111 #фильтр по IP внешней сети @@ -52,15 +52,21 @@ data "decort_account_vins_list" "avl" { #тип - строка #ext_ip = "test" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/resource_account/main.tf b/samples/cloudapi/account/resource_account/main.tf similarity index 91% rename from samples/cloudapi/resource_account/main.tf rename to samples/cloudapi/account/resource_account/main.tf index 9a65271..b7836f2 100644 --- a/samples/cloudapi/resource_account/main.tf +++ b/samples/cloudapi/account/resource_account/main.tf @@ -5,8 +5,8 @@ 1. Создавать аккаунт 2. Редактировать аккаунт 3. Удалять аккаунт - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -44,20 +44,20 @@ resource "decort_account" "a" { #доступность аккаунта #необязательный параметр - #тип - булев тип + #тип - булев #может применяться при редактировании аккаунта - enable = true + #enable = true #id аккаунта, позволяет сформировать .tfstate, если аккаунт имеет в платформе #необязательный параметр - #тип - число + #тип - целое число account_id = 11111 #отправлять ли на электронную почту письмо о доступе #необязательный параметр - #тип - булев тип + #тип - булев #применяется при создании аккаунта и редактировании аккаунта - send_access_emails = true + #send_access_emails = true #добавление/редактирование/удаление пользователей, к которым привязан аккаунт #необязательный параметр @@ -79,7 +79,7 @@ resource "decort_account" "a" { #рекурсивное удаление пользователя из всех ресурсов аккаунтов #необязательный параметр - #тип - булев тип + #тип - булев #по-умолчанию - false #применяется при удалении пользователя из аккаунта recursive_delete = true @@ -96,51 +96,51 @@ resource "decort_account" "a" { resource_limits { #кол-во используемых ядер cpu #необязательный параметр - #тип - число - #если установлена -1 - кол-во неограиченно + #тип - целое число + #если установлена -1 - кол-во неограничено cu_c = 2 #кол-во используемой RAM в МБ #необязательный параметр - #тип - число - #если установлена -1 - кол-во неограиченно + #тип - целое число + #если установлена -1 - кол-во неограничено cu_m = 1024 #размер дисков, в ГБ #необязательный параметр - #тип - число - #если установлена -1 - размер неограичен + #тип - целое число + #если установлена -1 - размер неограничено cu_d = 23 #кол-во используемых публичных IP #необязательный параметр - #тип - число - #если установлена -1 - кол-во неограиченно + #тип - целое число + #если установлена -1 - кол-во неограничено cu_i = 2 #ограничения на кол-во передачи данных, в ГБ #необязательный параметр - #тип - число - #если установлена -1 - кол-во неограиченно + #тип - целое число + #если установлена -1 - кол-во неограничено cu_np = 2 #кол-во графических процессоров #необязательный параметр - #тип - число - #если установлена -1 - кол-во неограиченно + #тип - целое число + #если установлена -1 - кол-во неограничено gpu_units = 2 } #восстановление аккаунта #необязательный параметр - #тип - булев тип + #тип - булев #применяется к удаленным аккаунтам #по-умолчанию - false #restore = false #мгновеное удаление аккаунта, если да - то аккаунт невозможно будет восстановить #необязательный параметр - #тип - булев тип + #тип - булев #используется при удалении аккаунта #по-умолчанию - false #permanently = true diff --git a/samples/cloudapi/data_bservice/main.tf b/samples/cloudapi/bservice/data_bservice/main.tf similarity index 96% rename from samples/cloudapi/data_bservice/main.tf rename to samples/cloudapi/bservice/data_bservice/main.tf index 43fb722..107a5b8 100644 --- a/samples/cloudapi/data_bservice/main.tf +++ b/samples/cloudapi/bservice/data_bservice/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о basic service - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,9 +29,8 @@ provider "decort" { data "decort_bservice" "b" { #id сервиса #обязательный параметр - #тип - число + #тип - целое число service_id = 11111 - } output "test" { diff --git a/samples/cloudapi/data_bservice_deleted_list/main.tf b/samples/cloudapi/bservice/data_bservice_deleted_list/main.tf similarity index 80% rename from samples/cloudapi/data_bservice_deleted_list/main.tf rename to samples/cloudapi/bservice/data_bservice_deleted_list/main.tf index 9172fae..94f8344 100644 --- a/samples/cloudapi/data_bservice_deleted_list/main.tf +++ b/samples/cloudapi/bservice/data_bservice_deleted_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка удаленных basic service */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,25 +29,31 @@ provider "decort" { data "decort_bservice_deleted_list" "bsdl" { #id аккаунта для фильтрации данных #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #account_id = 11111 #id ресурсной группы, используется для фильтрации #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные - #rg_id = 11111 + #rg_id = 11111 + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 diff --git a/samples/cloudapi/data_bservice_group/main.tf b/samples/cloudapi/bservice/data_bservice_group/main.tf similarity index 94% rename from samples/cloudapi/data_bservice_group/main.tf rename to samples/cloudapi/bservice/data_bservice_group/main.tf index 48beb9c..cbd4aa0 100644 --- a/samples/cloudapi/data_bservice_group/main.tf +++ b/samples/cloudapi/bservice/data_bservice_group/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о вычислительной группе, принадлежащей basic service - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_bservice_group" "bsg" { #id сервиса #обязательный параметр - #тип - число + #тип - целое число service_id = 11111 #id вычислительной группы #обязательный параметр - #тип - число + #тип - целое число compgroup_id = 12121 } diff --git a/samples/cloudapi/data_bservice_list/main.tf b/samples/cloudapi/bservice/data_bservice_list/main.tf similarity index 85% rename from samples/cloudapi/data_bservice_list/main.tf rename to samples/cloudapi/bservice/data_bservice_list/main.tf index 71f2a17..c02d53b 100644 --- a/samples/cloudapi/data_bservice_list/main.tf +++ b/samples/cloudapi/bservice/data_bservice_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка доступных базовых сервисов - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_bservice_list" "bsl" { #фильтр по id базового сервиса #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени базового сервиса @@ -39,7 +39,7 @@ data "decort_bservice_list" "bsl" { #id аккаунта для фильтрации данных #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #account_id = 11111 @@ -50,7 +50,7 @@ data "decort_bservice_list" "bsl" { #id ресурсной группы, используется для фильтрации #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #rg_id = 11111 @@ -69,15 +69,21 @@ data "decort_bservice_list" "bsl" { #тип - строка #account_name = "test" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/data_bservice_snapshot_list/main.tf b/samples/cloudapi/bservice/data_bservice_snapshot_list/main.tf similarity index 96% rename from samples/cloudapi/data_bservice_snapshot_list/main.tf rename to samples/cloudapi/bservice/data_bservice_snapshot_list/main.tf index 317e183..f9058f5 100644 --- a/samples/cloudapi/data_bservice_snapshot_list/main.tf +++ b/samples/cloudapi/bservice/data_bservice_snapshot_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка снимков состояний basic service - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,7 +30,7 @@ provider "decort" { data "decort_bservice_snapshot_list" "bsl" { #id basic service #обязательный параметр - #тип - число + #тип - целое число service_id = 11111 } diff --git a/samples/cloudapi/resource_bservice/main.tf b/samples/cloudapi/bservice/resource_bservice/main.tf similarity index 94% rename from samples/cloudapi/resource_bservice/main.tf rename to samples/cloudapi/bservice/resource_bservice/main.tf index c47189e..c90581f 100644 --- a/samples/cloudapi/resource_bservice/main.tf +++ b/samples/cloudapi/bservice/resource_bservice/main.tf @@ -8,8 +8,8 @@ 4. Создавать снимки состояний basic service 5. Совершать восстановление по снимкам состояний 6. Удалять снимки состояний - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -17,8 +17,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -41,12 +41,12 @@ resource "decort_bservice" "b" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 11111 #доступность сервиса #необязательный параметр - #тип - булев тип + #тип - булев #используется при редактировании ресурса #по-умолачанию - false #enable = true @@ -65,7 +65,7 @@ resource "decort_bservice" "b" { #восстановление сервиса из снимка состояния #необязательный параметр - #тип - булев тип + #тип - булев #по-умолчанию - false #восстановление происходит только при переключении с false на true rollback = false @@ -74,32 +74,31 @@ resource "decort_bservice" "b" { #старт сервиса #необязательный параметр - #тип - булев тип + #тип - булев #используется при редактировании ресурса #по-умолачанию - false #start = false #восстановление сервиса после удаления #необязательный параметр - #тип - булев тип + #тип - булев #используется при редактировании ресурса #по-умолачанию - false #restore = true #мгновенное удаление сервиса без права восстановления #необязательный параметр - #тип - булев тип + #тип - булев #используется при удалении ресурса #по-умолачанию - false #permanently = true #id сервиса, позволяет сформировать .tfstate, если сервис есть в платформе #необязательный параметр - #тип - булев тип + #тип - булев #используется при создании ресурса #service_id = 11111 - } output "test" { diff --git a/samples/cloudapi/resource_bservice_group/main.tf b/samples/cloudapi/bservice/resource_bservice_group/main.tf similarity index 87% rename from samples/cloudapi/resource_bservice_group/main.tf rename to samples/cloudapi/bservice/resource_bservice_group/main.tf index c4a0493..9945833 100644 --- a/samples/cloudapi/resource_bservice_group/main.tf +++ b/samples/cloudapi/bservice/resource_bservice_group/main.tf @@ -6,6 +6,7 @@ 2. Редактировать группы 3. Удалять группы */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -13,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -32,7 +33,7 @@ provider "decort" { resource "decort_bservice_group" "bsg" { #id basic service #обязательный параметр - #тип - число + #тип - целое число service_id = 444444 #название группы @@ -42,37 +43,37 @@ resource "decort_bservice_group" "bsg" { #id группы #необязательный параметр - #тип - число + #тип - целое число #применяется при редактировании группы, либо при создании .tfstate - файла, если группа имеется в плафторме compgroup_id = 33333 #кол-во вычислительных ресурсов #обязательный параметр - #тип - число + #тип - целое число #используется так же для редактирования группы comp_count = 1 #кол-во ядер на выч. ресурс #обязательный параметр - #тип - число + #тип - целое число #используется так же для редактирования группы cpu = 2 #кол-во оперативной памяти на выч. ресурс, в МБ #обязательный параметр - #тип - число + #тип - целое число #используется так же для редактирования группы ram = 256 #размер диска для выч. ресурса, в ГБ #обязательный параметр - #тип - число + #тип - целое число #используется так же для редактирования группы disk = 11 #id образа диска #обязательный параметр - #тип - число + #тип - целое число image_id = 2222 #драйвер @@ -82,7 +83,7 @@ resource "decort_bservice_group" "bsg" { #id Storage endpoint provider #необязательный параметр - #тип - число + #тип - целое число sep_id = 3 #Наименование SEPPool используется если установлен sepId, также может быть пустым @@ -98,57 +99,57 @@ resource "decort_bservice_group" "bsg" { #id сетей extnet #необязательный параметр - #тип - массив чисел + #тип - массив целых чисел #должен быть использован vins или extnets extnets = [1111, 2222] #id сетей vinses #необязательный параметр - #тип - массив чисел + #тип - массив целых чисел #должен быть использован vins или extnets vinses = [1111, 2222] #время таймуата перед стартом #необязательный параметр - #тип - число + #тип - целое число #используется при создании ресурса timeout_start = 0 #Перечень аргументов для cloud-init создаваемым группам узлов Worker #необязательный параметр - #тип - файл + #тип - файл в формате YAML cloud_init = file("initconfig.tftpl") #id групп родителей #необязательный параметр - #тип - массив чисел + #тип - массив целых чисел #используется при редактировании ресурса - #parents = [] + #parents = [2222] #принудительное обновление параметров выч. мощностей (ram,disk,cpu) и имени группы #необязательный параметр - #тип - булев тип + #тип - булев #используется при редактировании ресурса #по-умолчанию - false #force_update = true #старт/стоп вычислительных мощностей #необязательный параметр - #тип - булев тип + #тип - булев #используется при редактировании ресурса #по-умолчанию - false #start = false #принудительная остановка вычислительных мощностей #необязательный параметр - #тип - булев тип + #тип - булев #используется при редактировании и остановке группы #по-умолчанию - false #force_stop = false #удаление вычислительных мощностей #необязательный параметр - #тип - массив чисел + #тип - массив целых чисел #используется при редактировании #remove_computes = [32287] diff --git a/samples/cloudapi/data_k8s_computes/main.tf b/samples/cloudapi/data_k8s_computes/main.tf deleted file mode 100644 index 8814965..0000000 --- a/samples/cloudapi/data_k8s_computes/main.tf +++ /dev/null @@ -1,32 +0,0 @@ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -data "decort_k8s_computes" "computes" { - # ID кластера - # Обязательный параметр - k8s_id = 999 -} - -output "computes_out" { - value = data.decort_k8s_computes.computes -} diff --git a/samples/cloudapi/data_rg_list_vins/main.tf b/samples/cloudapi/data_rg_list_vins/main.tf deleted file mode 100644 index 8eb0c1b..0000000 --- a/samples/cloudapi/data_rg_list_vins/main.tf +++ /dev/null @@ -1,68 +0,0 @@ -/* -Пример использования -Получение информации о списке винсов в ресурсной группе -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} */ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -data "decort_rg_list_vins" "list_vins" { - #id ресурсной группы - #обязательный параметр - #тип - число - rg_id = 123 - - # фильтр по id vins - # опциональный параметр - # тип - число - # vins_id = 100 - - # фильтр по имени vins - # опциональный параметр - # тип - строка - # name = "test" - - # id аккаунта для получения списка балансировщиков нагрузки - # опциональный параметр - # тип - число - # account_id = 11111 - - # фильтр по IP внешней сети - # опциональный параметр - # тип - строка - # ext_ip = "test" - - # номер страницы для отображения - # опциональный параметр - # тип - число - # если не задан - выводятся все доступные данные - # page = 2 - - # размер страницы - # опциональный параметр - # тип - число - # если не задан - выводятся все доступные данные - # size = 3 -} - -output "output" { - value = data.decort_rg_list_vins.list_vins -} diff --git a/samples/cloudapi/data_vins_static_route_list/main.tf b/samples/cloudapi/data_vins_static_route_list/main.tf deleted file mode 100644 index 05e001e..0000000 --- a/samples/cloudapi/data_vins_static_route_list/main.tf +++ /dev/null @@ -1,45 +0,0 @@ -/* -Пример использования -Ресурса vins static routes -Ресурс позволяет: -1. Создавать static routes -2. Удалять static routes -3. Получать информацию о всех static routes в данном Vins -4. Предоставлять доступ виртуальным машинам к static routes -5. Удалять доступ виртуальным машинам к static routes - -*/ - -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -data "decort_vins_static_route_list" "list" { - #обязательный параметр - #id vins в котором добавлены routes - #тип - число - vins_id = 1111 -} - -output "list" { - value = data.decort_vins_static_route_list.list -} diff --git a/samples/cloudapi/data_disk/main.tf b/samples/cloudapi/disk/data_disk/main.tf similarity index 83% rename from samples/cloudapi/data_disk/main.tf rename to samples/cloudapi/disk/data_disk/main.tf index 32ef443..25eb620 100644 --- a/samples/cloudapi/data_disk/main.tf +++ b/samples/cloudapi/disk/data_disk/main.tf @@ -1,20 +1,21 @@ /* Пример использования -Получение списка доступных образов +Получение данных диска */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -26,8 +27,10 @@ provider "decort" { } data "decort_disk" "acl" { + #фильтр по id диска + #обязательный параметр + #тип - целое число disk_id = 49304 - } output "test" { diff --git a/samples/cloudapi/data_disk_list/main.tf b/samples/cloudapi/disk/data_disk_list/main.tf similarity index 77% rename from samples/cloudapi/data_disk_list/main.tf rename to samples/cloudapi/disk/data_disk_list/main.tf index 20c39c9..392db8b 100644 --- a/samples/cloudapi/data_disk_list/main.tf +++ b/samples/cloudapi/disk/data_disk_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка доступных дисков */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -29,7 +29,7 @@ provider "decort" { data "decort_disk_list" "dl" { #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени диска @@ -44,7 +44,7 @@ data "decort_disk_list" "dl" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 100 #фильтр по статусу @@ -54,23 +54,23 @@ data "decort_disk_list" "dl" { #фильтр по доступности иным пользователям #опциональный параметр - #тип - булев тип + #тип - булев #shared = "false" #id аккаунта для получения списка дисков #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #тип диска #опциональный параметр #тип - строка - #возможные типы: "b" - boot_disk, "d" - data_disk - #type = "d" + #возможные типы: "B" - boot_disk, "D" - data_disk + #type = "D" #id SEP для получения списка дисков #опциональный параметр - #тип - число + #тип - целое число #sep_id = 11111 #фильтр по имени pool @@ -78,14 +78,20 @@ data "decort_disk_list" "dl" { #тип - строка #pool_name = "test" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 } diff --git a/samples/cloudapi/data_disk_list_deleted/main.tf b/samples/cloudapi/disk/data_disk_list_deleted/main.tf similarity index 78% rename from samples/cloudapi/data_disk_list_deleted/main.tf rename to samples/cloudapi/disk/data_disk_list_deleted/main.tf index 118f101..7ac5c9e 100644 --- a/samples/cloudapi/data_disk_list_deleted/main.tf +++ b/samples/cloudapi/disk/data_disk_list_deleted/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка дисков со статусом DELETED */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +30,7 @@ provider "decort" { data "decort_disk_list_deleted" "dld" { #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени диска @@ -44,17 +45,17 @@ data "decort_disk_list_deleted" "dld" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 100 #фильтр по доступности иным пользователям #опциональный параметр - #тип - булев тип + #тип - булев #shared = "false" #id аккаунта для получения списка дисков #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #тип диска @@ -63,14 +64,20 @@ data "decort_disk_list_deleted" "dld" { #возможные типы: "b" - boot_disk, "d" - data_disk #type = "d" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 } diff --git a/samples/cloudapi/data_disk_list_types/main.tf b/samples/cloudapi/disk/data_disk_list_types/main.tf similarity index 78% rename from samples/cloudapi/data_disk_list_types/main.tf rename to samples/cloudapi/disk/data_disk_list_types/main.tf index 7c5e6f1..6882571 100644 --- a/samples/cloudapi/data_disk_list_types/main.tf +++ b/samples/cloudapi/disk/data_disk_list_types/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка типов дисков */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,15 +27,21 @@ provider "decort" { } data "decort_disk_list_types" "dlt" { + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/data_disk_list_types_detailed/main.tf b/samples/cloudapi/disk/data_disk_list_types_detailed/main.tf similarity index 79% rename from samples/cloudapi/data_disk_list_types_detailed/main.tf rename to samples/cloudapi/disk/data_disk_list_types_detailed/main.tf index 4f52de7..4edb839 100644 --- a/samples/cloudapi/data_disk_list_types_detailed/main.tf +++ b/samples/cloudapi/disk/data_disk_list_types_detailed/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка типов дисков, но детально */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -28,15 +28,21 @@ provider "decort" { data "decort_disk_list_types_detailed" "dltd" { + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/data_disk_list_unattached/main.tf b/samples/cloudapi/disk/data_disk_list_unattached/main.tf similarity index 83% rename from samples/cloudapi/data_disk_list_unattached/main.tf rename to samples/cloudapi/disk/data_disk_list_unattached/main.tf index 5d97266..a0a36f5 100644 --- a/samples/cloudapi/data_disk_list_unattached/main.tf +++ b/samples/cloudapi/disk/data_disk_list_unattached/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка доступных неприсоединенных дисков */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,7 +31,7 @@ provider "decort" { data "decort_disk_list_unattached" "dlu" { #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени аккаунта @@ -40,7 +41,7 @@ data "decort_disk_list_unattached" "dlu" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 100 #фильтр по статусу @@ -56,12 +57,12 @@ data "decort_disk_list_unattached" "dlu" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #account_id = 100 #фильтр по id sep #опциональный параметр - #тип - число + #тип - целое число #sep_id = 1 #фильтр по имени pool @@ -69,15 +70,21 @@ data "decort_disk_list_unattached" "dlu" { #тип - строка #pool_name = "test" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/disk/data_disk_replication/main.tf b/samples/cloudapi/disk/data_disk_replication/main.tf new file mode 100644 index 0000000..15543e7 --- /dev/null +++ b/samples/cloudapi/disk/data_disk_replication/main.tf @@ -0,0 +1,45 @@ +/* +Пример использования +Получение статуса репликации диска +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + + +data "decort_disk_replication" "dr" { + #ID диска для которого подключена репликация + #обязательный параметр + #тип - целое число + disk_id = 49304 + + #ID реплики диска + #обязательный параметр + #тип - целое число + replica_disk_id = 1213 +} + +output "test" { + value = data.decort_disk_replication.dr +} diff --git a/samples/cloudapi/data_disk_snapshot/main.tf b/samples/cloudapi/disk/data_disk_snapshot/main.tf similarity index 96% rename from samples/cloudapi/data_disk_snapshot/main.tf rename to samples/cloudapi/disk/data_disk_snapshot/main.tf index f7f5790..880cd9a 100644 --- a/samples/cloudapi/data_disk_snapshot/main.tf +++ b/samples/cloudapi/disk/data_disk_snapshot/main.tf @@ -2,6 +2,7 @@ Пример использования Получение конкретного снапшота */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -16,7 +17,6 @@ terraform { } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -26,11 +26,10 @@ provider "decort" { allow_unverified_ssl = true } - data "decort_disk_snapshot" "ds" { #Номер диска #обязательный параметр - #тип - число + #тип - целое число disk_id = 20100 #Ярлык диска diff --git a/samples/cloudapi/data_disk_snapshot_list/main.tf b/samples/cloudapi/disk/data_disk_snapshot_list/main.tf similarity index 96% rename from samples/cloudapi/data_disk_snapshot_list/main.tf rename to samples/cloudapi/disk/data_disk_snapshot_list/main.tf index 8003250..fc05f81 100644 --- a/samples/cloudapi/data_disk_snapshot_list/main.tf +++ b/samples/cloudapi/disk/data_disk_snapshot_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка снапшотов диска */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -26,11 +26,10 @@ provider "decort" { allow_unverified_ssl = true } - data "decort_disk_snapshot_list" "ds" { #Номер диска #обязательный параметр - #тип - число + #тип - целое число disk_id = 20100 } diff --git a/samples/cloudapi/disk/resource_disk/main.tf b/samples/cloudapi/disk/resource_disk/main.tf new file mode 100644 index 0000000..b6b862d --- /dev/null +++ b/samples/cloudapi/disk/resource_disk/main.tf @@ -0,0 +1,74 @@ +/* +Пример использования +Получение информации об уже существующем диске. +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_disk" "acl" { + #id владельца диска + #обязательный параметр + #тип - целое число + account_id = 88366 + + #имя диска + #обязательный параметр + #тип - строка + disk_name = "super-disk-re" + + #размер диска в гигабайтах + #обязательный параметр + #тип - целое число + size_max = 20 + + #id платформы + #обязательный параметр + #тип - целое число + gid = 212 + + #флаг для отключения диска от ВМ при удалении + #опциональный параметр + #тип - булев + detach = false + + #флаг для удаления реплики диска безвозвратно + #опциональный параметр + #тип - булев + permanently = false + + #описание причины удаления + #опциональный параметр + #тип - строка + reason = "some" + + #Флаг, отвечающий за доступность диска дургим ресурсам + #опциональный параметр + #тип - строка + shareable = false + +} + +output "test" { + value = decort_disk.acl +} diff --git a/samples/cloudapi/disk/resource_disk_replication/main.tf b/samples/cloudapi/disk/resource_disk_replication/main.tf new file mode 100644 index 0000000..99304ef --- /dev/null +++ b/samples/cloudapi/disk/resource_disk_replication/main.tf @@ -0,0 +1,84 @@ +/* +Пример использования +Ресурс репликации диска +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_disk_replication" "dr" { + #id диска из которого будет создана реплика + #обязательный параметр + #тип - целое число + disk_id = 20100 + + #имя реплики диска + #обязательный параметр + #тип - строка + disk_name = "test" + + #sep id + #обязательный параметр + #тип - целое число + sep_id = 1 + + #название pool + #обязательный параметр + #тип - строка + pool_name = "some" + + #флаг паузы + #опциональный параметр + #тип - булев + #pause = false + + #флаг для изменения ролей дисков + #опциональный параметр + #тип - булев + #reverse = false + + #флаг для запуска связи между диском и репликой + #опциональный параметр + #тип - булев + #start = false + + #флаг для отключения диска от ВМ при удалении + #опциональный параметр + #тип - булев + #detach = false + + #флаг для удаления реплики диска безвозвратно + #опциональный параметр + #тип - булев + #permanently = false + + #описание причины удаления + #опциональный параметр + #тип - строка + #reason = "some" +} + + +output "test" { + value = decort_disk_replication.dr +} diff --git a/samples/cloudapi/resource_disk_snapshot/main.tf b/samples/cloudapi/disk/resource_disk_snapshot/main.tf similarity index 90% rename from samples/cloudapi/resource_disk_snapshot/main.tf rename to samples/cloudapi/disk/resource_disk_snapshot/main.tf index ca4f577..ac8184c 100644 --- a/samples/cloudapi/resource_disk_snapshot/main.tf +++ b/samples/cloudapi/disk/resource_disk_snapshot/main.tf @@ -2,19 +2,20 @@ Пример использования Ресурс снапшота диска */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -26,19 +27,19 @@ provider "decort" { } resource "decort_disk_snapshot" "ds" { - #Номер диска + #номер диска #обязательный параметр - #тип - число + #тип - целое число disk_id = 20100 - #Ярлык диска + #ярлык диска #обязательный параметр #тип - строка label = "label" #флаг rollback #опциональный параметр - #тип - bool + #тип - булев rollback = false } diff --git a/samples/cloudapi/data_extnet/main.tf b/samples/cloudapi/extnet/data_extnet/main.tf similarity index 96% rename from samples/cloudapi/data_extnet/main.tf rename to samples/cloudapi/extnet/data_extnet/main.tf index b465b79..dec5e1d 100644 --- a/samples/cloudapi/data_extnet/main.tf +++ b/samples/cloudapi/extnet/data_extnet/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о сети */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -29,7 +29,7 @@ provider "decort" { data "decort_extnet" "e" { #идентификатор сети #обязательный параметр - #тип - число + #тип - целое число net_id = 1111 } diff --git a/samples/cloudapi/data_extnet_computes_list/main.tf b/samples/cloudapi/extnet/data_extnet_computes_list/main.tf similarity index 73% rename from samples/cloudapi/data_extnet_computes_list/main.tf rename to samples/cloudapi/extnet/data_extnet_computes_list/main.tf index 7a1e06b..292160d 100644 --- a/samples/cloudapi/data_extnet_computes_list/main.tf +++ b/samples/cloudapi/extnet/data_extnet_computes_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о вычислительных ресурсах, использующих сеть аккаунта */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,30 +29,34 @@ provider "decort" { data "decort_extnet_computes_list" "ecl" { #идентификатор аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 1111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 11111 #фильтр по id виртуальной машины #опциональный параметр - #тип - число + #тип - целое число #compute_id = 11111 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 - - } output "test" { diff --git a/samples/cloudapi/data_extnet_default/main.tf b/samples/cloudapi/extnet/data_extnet_default/main.tf similarity index 99% rename from samples/cloudapi/data_extnet_default/main.tf rename to samples/cloudapi/extnet/data_extnet_default/main.tf index bfbc74f..79b03a3 100644 --- a/samples/cloudapi/data_extnet_default/main.tf +++ b/samples/cloudapi/extnet/data_extnet_default/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о сети по-умолчанию - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = diff --git a/samples/cloudapi/data_extnet_list/main.tf b/samples/cloudapi/extnet/data_extnet_list/main.tf similarity index 76% rename from samples/cloudapi/data_extnet_list/main.tf rename to samples/cloudapi/extnet/data_extnet_list/main.tf index 1410492..ad98a7c 100644 --- a/samples/cloudapi/data_extnet_list/main.tf +++ b/samples/cloudapi/extnet/data_extnet_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка сетей - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_extnet_list" "el" { #id аккаунта для фильтрации результата #необязательный параметр - #тип - число + #тип - целое число #account_id = 1111111 #фильтр по id внешней сети #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени внешней сети @@ -49,12 +49,12 @@ data "decort_extnet_list" "el" { #фильтр по id vlan #опциональный параметр - #тип - число + #тип - целое число #vlan_id = 100 #фильтр по id vnfDevices #опциональный параметр - #тип - число + #тип - целое число #vnfdev_id = 100 #фильтр по статусу @@ -62,14 +62,20 @@ data "decort_extnet_list" "el" { #тип - строка #status = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 } diff --git a/samples/cloudapi/data_flipgroup/main.tf b/samples/cloudapi/flipgroup/data_flipgroup/main.tf similarity index 77% rename from samples/cloudapi/data_flipgroup/main.tf rename to samples/cloudapi/flipgroup/data_flipgroup/main.tf index 20b5104..e32c31f 100644 --- a/samples/cloudapi/data_flipgroup/main.tf +++ b/samples/cloudapi/flipgroup/data_flipgroup/main.tf @@ -1,3 +1,8 @@ +/* +Пример использования +Получение группы виртуальных машин по id +*/ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -22,9 +27,9 @@ provider "decort" { } data "decort_flipgroup" "fg" { - # ID флипгруппы - # Обязательный параметр - # int + #id флипгруппы + #обязательный параметр + #тип - целое число flipgroup_id = 999 } diff --git a/samples/cloudapi/data_flipgroup_list/main.tf b/samples/cloudapi/flipgroup/data_flipgroup_list/main.tf similarity index 63% rename from samples/cloudapi/data_flipgroup_list/main.tf rename to samples/cloudapi/flipgroup/data_flipgroup_list/main.tf index 0012021..0dc80f4 100644 --- a/samples/cloudapi/data_flipgroup_list/main.tf +++ b/samples/cloudapi/flipgroup/data_flipgroup_list/main.tf @@ -1,3 +1,8 @@ +/* +Пример использования +Получение группы виртуальных машин, доступных текущему пользователю +*/ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -24,7 +29,7 @@ provider "decort" { data "decort_flipgroup_list" "fg" { #фильтр по id flipgroup #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени flipgroup @@ -34,7 +39,7 @@ data "decort_flipgroup_list" "fg" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #vins_id = 100 #фильтр по имени vins @@ -44,7 +49,7 @@ data "decort_flipgroup_list" "fg" { #фильтр по id extnet #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 #фильтр по IP @@ -54,21 +59,47 @@ data "decort_flipgroup_list" "fg" { #id ресурсной группы, используется для фильтрации #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #rg_id = 11111 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 + + #фильтр по id аккаунта + #опциональный параметр + #тип - целое число + #account_id = 100 + + #фильтр по id conn + #опциональный параметр + #тип - целое число + #conn_id = 100 + + #фильтр по id клиентов + #опциональный параметр + #тип - массив целых чисел + #client_ids = [10,11] + + #фильтр по статусу + #опциональный параметр + #тип - строка + #status = "CREATED" } output "fg_out" { diff --git a/samples/cloudapi/flipgroup/resource_flipgroup/main.tf b/samples/cloudapi/flipgroup/resource_flipgroup/main.tf new file mode 100644 index 0000000..2740b09 --- /dev/null +++ b/samples/cloudapi/flipgroup/resource_flipgroup/main.tf @@ -0,0 +1,76 @@ +/* +Управления плавающими группами (флипгруппами). +Ресурс позволяет: +1. Создать флипгруппу +2. Удалить флипгруппу +3. Добавить/удалить клиентов +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_flipgroup" "fg" { + #id аккаунта + #обязательный параметр + #тип - целое число + account_id = 999 + + #наименование Flipgroup + #обязательный параметр + #тип - строка + name = "flipgroup_name" + + #тип сети (EXTNET, ViNS) + #обязательный параметр + #тип - строка + net_type = "EXTNET" + + #id сети + #обязательный параметр + #тип - целое число + net_id = 13 + + #тип клиентов (в данный момент поддерживается только тип 'compute') + #обязательный параметр + #тип - строка + client_type = "compute" + + #ip-адрес + #опциональный параметр + #тип - строка + ip = "127.0.0.1" + + #список клиентов, прикрепленных к флипгруппе + #опциональный параметр + #тип - массив целых чисел + client_ids = [11269] + + #описание флипгруппы + #опциональный параметр + #тип - строка + desc = "CHANGED" +} + +output "fg_out" { + value = decort_flipgroup.fg +} diff --git a/samples/cloudapi/data_image/main.tf b/samples/cloudapi/image/data_image/main.tf similarity index 90% rename from samples/cloudapi/data_image/main.tf rename to samples/cloudapi/image/data_image/main.tf index 2f70535..a98e3df 100644 --- a/samples/cloudapi/data_image/main.tf +++ b/samples/cloudapi/image/data_image/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации об образе */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,10 +29,10 @@ provider "decort" { data "decort_image" "image" { #id образа #обязательный параметр - #тип - число + #тип - целое число image_id = 111 - #позывать ли информацию об удаленном образе + #показывать ли информацию об удаленном образе #опциональный параметр #тип - булево значение #по умолчанию - false diff --git a/samples/cloudapi/data_image_list/main.tf b/samples/cloudapi/image/data_image_list/main.tf similarity index 86% rename from samples/cloudapi/data_image_list/main.tf rename to samples/cloudapi/image/data_image_list/main.tf index eb477d8..19bfe71 100644 --- a/samples/cloudapi/data_image_list/main.tf +++ b/samples/cloudapi/image/data_image_list/main.tf @@ -2,18 +2,20 @@ Пример использования Получение списка доступных образов */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } +*/ provider "decort" { @@ -28,12 +30,12 @@ provider "decort" { data "decort_image_list" "il" { #фильтр по id sep #опциональный параметр - #тип - число + #тип - целое число #sep_id = 1 #фильтр по id образа #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени образа @@ -58,7 +60,7 @@ data "decort_image_list" "il" { #фильтр по размеру образа #опциональный параметр - #тип - число + #тип - целое число #image_size = 100 #фильтр по имени SEP @@ -86,15 +88,21 @@ data "decort_image_list" "il" { #тип - булевый тип #bootable = "true" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/image/resource_image/main.tf b/samples/cloudapi/image/resource_image/main.tf new file mode 100644 index 0000000..1d83200 --- /dev/null +++ b/samples/cloudapi/image/resource_image/main.tf @@ -0,0 +1,115 @@ +/* +Пример использования +Работа с образом +Ресурс позволяет: +1. Управлять образом +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_image" "img" { + #наименование образа + #обязательный параметр + #тип - строка + name = "image_name" + + #драйверы компьютов, подходящие для данного образа + #обязательный параметр + #тип - массив строк + drivers = ["KVM_X86"] + + #тип образа (linux, windows и др.) + #обязательный параметр + #тип - строка + type = "linux" + + #прямая ссылка на образ + #обязательный параметр + #тип - строка + url = "https://dl-cdn.alpinelinux.org/alpine/v3.17/releases/x86_64/alpine-virt-3.17.3-x86_64.iso" + + #тип загрузчика (bios/uefi) + #обязательный параметр + #тип - строка + boot_type = "bios" + + #id аккаунта + #обязательный параметр + #тип - целое число + account_id = 138 + + #поддержка hot resize + #опциональный параметр + #тип - булев + hot_resize = true + + #юзернейм для образа + #опциональный параметр + #тип - целое число + username = "userx" + + #пароль для образа + #опциональный параметр + #тип - строка + password = "passx" + + #юзернейм для загрузки binary media + #опциональный параметр + #тип - строка + username_dl = "userxdl" + + #пароль для загрузки binary media + #опциональный параметр + #тип - строка + password_dl = "passxdl" + + #storage endpoint provider ID + #опциональный параметр + #тип - целое число + sep_id = 1 + + #pool для образа + #опциональный параметр + #тип - строка + pool_name = "pool" + + #архитектура образа (X86_64 / PPC64_LE) + #опциональный параметр + #тип - строка + architecture = "PPC64_LE" + + #флаг окончательного удаления + #опциональный параметр + #тип - булев + permanently = true + + #наименование сетевого интерфейса для вашего компьютера с Linux, eth - встроенный, ens - pci слот + #опциональный параметр + #тип - строка + network_interface_naming = "ens" +} + +output "img_out" { + value = decort_image.img +} diff --git a/samples/cloudapi/image/resource_image_from_blank_compute/main.tf b/samples/cloudapi/image/resource_image_from_blank_compute/main.tf new file mode 100644 index 0000000..39d6f28 --- /dev/null +++ b/samples/cloudapi/image/resource_image_from_blank_compute/main.tf @@ -0,0 +1,107 @@ +/* +Ресурс образа из компьюта, созданного как blank позволяет: +1. Создавать +2. Редактировать +3. Удалять ресурс +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_image_from_blank_compute" "img" { + #id виртуальной машины, созданной как blank + #обязательный параметр + #используется для создания образа + #тип - целое число + compute_id = 1234 + + #наименование образа + #обязательный параметр + #используется для создания и обновления образа + #тип - строка + name = "image_name" + + #тип загрузчика (bios/uefi) + #обязательный параметр + #используется для создания образа + #тип - строка + boot_type = "bios" + + #тип образа (linux, windows и др.) + #обязательный параметр + #используется для создания образа + #тип - строка + type = "linux" + + #юзернейм для образа + #опциональный параметр + #используется для создания образа + #тип - строка + #username = "userx" + + #пароль для образа + #опциональный параметр + #используется для создания образа + #тип - строка + #password = "passx" + + #id аккаунта + #опциональный параметр + #используется для создания образа + #тип - целое число + #account_id = 138 + + #storage endpoint provider ID + #опциональный параметр + #используется для создания образа + #тип - целое число + #sep_id = 1 + + #pool для образа + #опциональный параметр + #используется для создания образа + #тип - строка + #pool_name = "pool" + + #поддержка hot resize + #опциональный параметр + #используется для создания образа + #тип - булев + #hot_resize = true + + #флаг для создания образа в асинхронном режиме + #опциональный параметр + #дефолтное значение - false + #тип - булев + #async_mode = true + + #флаг окончательного удаления + #опциональный параметр + #тип - булев + #permanently = true + +} + +output "img_out" { + value = decort_image_from_blank_compute.img +} diff --git a/samples/cloudapi/image/resource_image_from_platform_disk/main.tf b/samples/cloudapi/image/resource_image_from_platform_disk/main.tf new file mode 100644 index 0000000..d113407 --- /dev/null +++ b/samples/cloudapi/image/resource_image_from_platform_disk/main.tf @@ -0,0 +1,127 @@ +/* +Ресурс образа из платформенного диска позволяет: +1. Создавать +2. Редактировать +3. Удалять ресурс +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_image_from_platform_disk" "img" { + #id диска + #используется для создания образа + #обязательный параметр + #тип - целое число + disk_id = 1234 + + #наименование образа + #используется для создания и обновления образа + #обязательный параметр + #тип - строка + name = "image_name" + + #тип загрузчика + #используется для создания образа + #обязательный параметр + #возможные значения - bios, uefi + #тип - строка + boot_type = "bios" + + #тип образа (linux, windows и др.) + #используется для создания образа + #обязательный параметр + #тип - строка + type = "linux" + + #архитектура образа + #используется для создания образа + #обязательный параметр + #возможные значения - X86_64, PPC64_LE + #тип - строка + architecture = "X86_64" + + #имя пользователя для образа + #используется для создания образа + #опциональный параметр + #тип - строка + #username = "userx" + + #пароль для образа + #используется для создания образа + #опциональный параметр + #тип - строка + #password = "passx" + + #id аккаунта + #используется для создания образа + #опциональный параметр + #тип - целое число + #account_id = 138 + + #id сепа для образа + #используется для создания образа + #опциональный параметр + #тип - целое число + #sep_id = 1 + + #pool для образа + #используется для создания образа + #опциональный параметр + #тип - строка + #pool_name = "pool" + + #драйверы компьютов, подходящие для данного образа + #используется для создания образа + #опциональный параметр + #тип - массив строк + #drivers = ["KVM_X86"] + + #поддержка hot resize + #используется для создания образа + #опциональный параметр + #тип - булев + #hot_resize = true + + #флаг загрузочного образа + #используется для создания образа + #опциональный параметр + #по умолчанию - true + #тип - булев + #bootable = true + + #флаг для создания образа в асинхронном режиме + #опциональный параметр + #по умолчанию - false + #тип - булев + #async_mode = true + + #флаг окончательного удаления + #опциональный параметр + #тип - булев + #permanently = true +} + +output "img_out" { + value = decort_image_from_platform_disk.img +} \ No newline at end of file diff --git a/samples/cloudapi/resource_image_virtual/main.tf b/samples/cloudapi/image/resource_image_virtual/main.tf similarity index 89% rename from samples/cloudapi/resource_image_virtual/main.tf rename to samples/cloudapi/image/resource_image_virtual/main.tf index c001e58..01ff9fe 100644 --- a/samples/cloudapi/resource_image_virtual/main.tf +++ b/samples/cloudapi/image/resource_image_virtual/main.tf @@ -1,11 +1,10 @@ /* Пример использования -Ресурса image virtual +Управления виртуальным образом Ресурс позволяет: 1. Создавать image virtual +2. Изменять image virtual 2. Удалять image virtual -3. Переименовывать image virtual -4. Привязывать image virtual к другому образу */ #Расскомментируйте этот код, @@ -15,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -41,12 +40,12 @@ resource "decort_image_virtual" "iv" { #ID реального образа, на который будет ссылаться виртуальный #обязательный параметр #при изменении - ссылается на другой реальный образ - #тип - число + #тип - целое число link_to = 123 #Флаг для удаления диска #опциональный параметр - #тип - bool + #тип - булев permanently = false } diff --git a/samples/cloudapi/data_k8ci_list/main.tf b/samples/cloudapi/k8s/data_k8ci_list/main.tf similarity index 68% rename from samples/cloudapi/data_k8ci_list/main.tf rename to samples/cloudapi/k8s/data_k8ci_list/main.tf index 119d237..b692460 100644 --- a/samples/cloudapi/data_k8ci_list/main.tf +++ b/samples/cloudapi/k8s/data_k8ci_list/main.tf @@ -2,19 +2,20 @@ Пример использования Получение информации о k8ci */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -26,49 +27,55 @@ provider "decort" { } data "decort_k8ci_list" "k8ci_list" { - #Поиск по ID + #поиск по ID #опциональный параметр - #тип - число + #тип - целое число by_id = 12 - #Поиск по наименованию + #поиск по наименованию #опциональный параметр #тип - строка name = "name" - #Поиск по статус + #поиск по статус #опциональный параметр #тип - строка status = "status" - #Поиск по worker драйверу + #поиск по worker драйверу #опциональный параметр #тип - строка worker_driver = "wdriver" - #Поиск по master драйверу + #поиск по master драйверу #опциональный параметр #тип - строка master_driver = "wdriver" - #Поиск по network плагину + #поиск по network плагину #опциональный параметр #тип - строка network_plugin = "flannel" - #Показать выключенные K8CI + #показать выключенные K8CI #опциональный параметр - #тип - bool + #тип - булев include_disabled = true - #Номер страницы + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + sort_by = "+name" + + #номер страницы #опциональный параметр - #тип - число + #тип - целое число page = 1 - #Размер страницы + #размер страницы #опциональный параметр - #тип - число + #тип - целое число size = 5 } diff --git a/samples/cloudapi/data_k8s/main.tf b/samples/cloudapi/k8s/data_k8s/main.tf similarity index 95% rename from samples/cloudapi/data_k8s/main.tf rename to samples/cloudapi/k8s/data_k8s/main.tf index fe28e85..370e8e9 100644 --- a/samples/cloudapi/data_k8s/main.tf +++ b/samples/cloudapi/k8s/data_k8s/main.tf @@ -2,10 +2,11 @@ Пример использования Получение информации о k8s кластере */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { @@ -14,7 +15,7 @@ terraform { } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_k8s" "k8s" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 49304 } diff --git a/samples/cloudapi/k8s/data_k8s_computes/main.tf b/samples/cloudapi/k8s/data_k8s_computes/main.tf new file mode 100644 index 0000000..020f722 --- /dev/null +++ b/samples/cloudapi/k8s/data_k8s_computes/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получения информации о виртуальных машинах кластера +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_k8s_computes" "computes" { + #id кластера + #обязательный параметр + #тип - целое число + k8s_id = 999 +} + +output "computes_out" { + value = data.decort_k8s_computes.computes +} diff --git a/samples/cloudapi/data_k8s_list/main.tf b/samples/cloudapi/k8s/data_k8s_list/main.tf similarity index 81% rename from samples/cloudapi/data_k8s_list/main.tf rename to samples/cloudapi/k8s/data_k8s_list/main.tf index a058a68..c18c034 100644 --- a/samples/cloudapi/data_k8s_list/main.tf +++ b/samples/cloudapi/k8s/data_k8s_list/main.tf @@ -2,19 +2,20 @@ Пример использования Получение списка доступных кластеров */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_k8s_list" "k8s_list" { #фильтр по id кластера #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени кластера @@ -43,17 +44,17 @@ data "decort_k8s_list" "k8s_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #lb_id = 100 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #bservice_id = 100 #фильтр по статусу @@ -68,21 +69,27 @@ data "decort_k8s_list" "k8s_list" { #включение удаленных k8s в результат #опциональный параметр - #тип - будев тип + #тип - булев #если не задан - выводятся все неудаленные данные - # includedeleted = true + #includedeleted = true + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные - # page = 1 + #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные - # size = 1 + #size = 1 } output "output_k8s_list" { diff --git a/samples/cloudapi/data_k8s_list_deleted/main.tf b/samples/cloudapi/k8s/data_k8s_list_deleted/main.tf similarity index 82% rename from samples/cloudapi/data_k8s_list_deleted/main.tf rename to samples/cloudapi/k8s/data_k8s_list_deleted/main.tf index f9975bd..b5e3feb 100644 --- a/samples/cloudapi/data_k8s_list_deleted/main.tf +++ b/samples/cloudapi/k8s/data_k8s_list_deleted/main.tf @@ -2,19 +2,20 @@ Пример использования Получение списка удаленных кластеров */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_k8s_list_deleted" "k8s_list_deleted" { #фильтр по id кластера #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени кластера @@ -43,17 +44,17 @@ data "decort_k8s_list_deleted" "k8s_list_deleted" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #lb_id = 100 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #bservice_id = 100 #фильтр по техническому статусу @@ -61,15 +62,21 @@ data "decort_k8s_list_deleted" "k8s_list_deleted" { #тип - строка #tech_status = "STOPPED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } @@ -77,4 +84,3 @@ data "decort_k8s_list_deleted" "k8s_list_deleted" { output "output_k8s_list_deleted" { value = data.decort_k8s_list_deleted.k8s_list_deleted } - diff --git a/samples/cloudapi/data_k8s_wg/main.tf b/samples/cloudapi/k8s/data_k8s_wg/main.tf similarity index 93% rename from samples/cloudapi/data_k8s_wg/main.tf rename to samples/cloudapi/k8s/data_k8s_wg/main.tf index 950e0be..30d23fe 100644 --- a/samples/cloudapi/data_k8s_wg/main.tf +++ b/samples/cloudapi/k8s/data_k8s_wg/main.tf @@ -2,19 +2,20 @@ Пример использования Получение информации о k8s кластере */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,12 +29,12 @@ provider "decort" { data "decort_k8s_wg" "k8s_wg" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 49304 #id группы воркеров #обязательный параметр - #тип - число + #тип - целое число wg_id = 43329 } diff --git a/samples/cloudapi/data_k8s_wg_cloud_init/main.tf b/samples/cloudapi/k8s/data_k8s_wg_cloud_init/main.tf similarity index 93% rename from samples/cloudapi/data_k8s_wg_cloud_init/main.tf rename to samples/cloudapi/k8s/data_k8s_wg_cloud_init/main.tf index e7da906..e0ceb59 100644 --- a/samples/cloudapi/data_k8s_wg_cloud_init/main.tf +++ b/samples/cloudapi/k8s/data_k8s_wg_cloud_init/main.tf @@ -2,19 +2,20 @@ Пример использования Получение информации о мета данных рабочей группы k8s кластера */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,18 +29,15 @@ provider "decort" { data "decort_k8s_wg_cloud_init" "wg_cloud_init" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 977 #id группы воркеров #обязательный параметр - #тип - число + #тип - целое число wg_id = 2110 } output "wg_cloud_init" { value = data.decort_k8s_wg_cloud_init.wg_cloud_init } - - - diff --git a/samples/cloudapi/data_k8s_wg_list/main.tf b/samples/cloudapi/k8s/data_k8s_wg_list/main.tf similarity index 96% rename from samples/cloudapi/data_k8s_wg_list/main.tf rename to samples/cloudapi/k8s/data_k8s_wg_list/main.tf index 39e875a..b7e2480 100644 --- a/samples/cloudapi/data_k8s_wg_list/main.tf +++ b/samples/cloudapi/k8s/data_k8s_wg_list/main.tf @@ -2,19 +2,20 @@ Пример использования Получение списка доступных групп воркеров в кластере */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_k8s_wg_list" "k8s_wg_list" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 49304 } diff --git a/samples/cloudapi/resource_k8s/main.tf b/samples/cloudapi/k8s/resource_k8s/main.tf similarity index 83% rename from samples/cloudapi/resource_k8s/main.tf rename to samples/cloudapi/k8s/resource_k8s/main.tf index 23201eb..163663f 100644 --- a/samples/cloudapi/resource_k8s/main.tf +++ b/samples/cloudapi/k8s/resource_k8s/main.tf @@ -1,3 +1,11 @@ +/* +Пример использования +Управление кластером +Ресурс позволяет: +1. Создавать кластер +2. Управлять кластером +*/ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -18,26 +26,24 @@ provider "decort" { controller_url = "https://ds1.digitalenergy.online" #oauth2_url = oauth2_url = "https://sso.digitalenergy.online" - #app_id = - #app_secret = allow_unverified_ssl = true } resource "decort_k8s" "cluster" { #имя кластера #обязательный параметр - #при изменении - обновдяет имя кластера + #при изменении - обновляет имя кластера #тип - строка name = "tftest" #id resource group #обязательный параметр - #тип - число - rg_id = 907 + #тип - целое число + rg_id = 776 #id catalogue item #обязательный параметр - #тип - число + #тип - целое число k8sci_id = 9 #сетевой плагин @@ -72,41 +78,41 @@ resource "decort_k8s" "cluster" { #максимальное кол-во элементов - 1 #тип - список нод masters { - #кол-во node + #кол-во node (1, 3 или 5) #обязательный параметр - #тип - число + #тип - целое число num = 1 #кол-во cpu #обязательный параметр - #тип - число + #тип - целое число cpu = 2 #кол-во RAM в Мбайтах #обязательный параметр - #тип - число + #тип - целое число ram = 2048 #размер диска в Гбайтах #обязательный параметр - #тип - число + #тип - целое число disk = 10 #идентификатор SEP для создания загрузочных дисков для master узлов #опциональный параметр - #тип - число + #тип - целое число sep_id = 3 #наименование MasterSEPPool используется если установлен master sepId, также может быть пустым #опциональный параметр #тип - строка sep_pool = "data_01" -} + } #настройка worker группы #опциональный параметр #Первая указанная воркер-группа должна соответствовать изначально созданной вместе с кластером. - # labels, annotations, taints для дефолтной worker группы указываются в корне ресурса при создании кластера. + #labels, annotations, taints для дефолтной worker группы указываются в корне ресурса при создании кластера. workers { #имя группы #обязательный параметр @@ -115,27 +121,27 @@ resource "decort_k8s" "cluster" { #кол-во node #обязательный параметр - #тип - число + #тип - целое число num = 1 #кол-во cpu #обязательный параметр - #тип - число + #тип - целое число cpu = 2 #кол-во RAM в Мбайтах #обязательный параметр - #тип - число + #тип - целое число ram = 2048 #размер диска в Гбайтах #обязательный параметр - #тип - число + #тип - целое число disk = 10 #Идентификатор SEP #опциональный параметр - #тип - число + #тип - целое число sep_id = 1010 #Имя SEP pool'a @@ -145,7 +151,7 @@ resource "decort_k8s" "cluster" { } #...Далее можно создавать произвольное кол-во дополнительных worker групп - # labels, annotations и taints для последующих групп указываются непосредственно в блоке workers + #labels, annotations и taints для последующих групп указываются непосредственно в блоке workers workers { #наименование worker группы #обязательный параметр @@ -154,81 +160,81 @@ resource "decort_k8s" "cluster" { #кол-во node #обязательный параметр - #тип - число + #тип - целое число num = 2 #кол-во cpu #обязательный параметр - #тип - число + #тип - целое число cpu = 2 #кол-во RAM в Мбайтах #обязательный параметр - #тип - число + #тип - целое число ram = 4096 #размер диска в Гбайтах #обязательный параметр - #тип - число + #тип - целое число disk = 10 - #Идентификатор SEP + #идентификатор SEP #опциональный параметр - #тип - число + #тип - целое число sep_id = 1010 - #Имя SEP pool'a + #имя SEP pool'a #опциональный параметр #тип - строка sep_pool = "data01" - #Список лейблов + #список лейблов #опциональный параметр #тип - массив строк labels = ["label1=value1", "label2=value2"] - #Список аннотаций + #список аннотаций #опциональный параметр #тип - массив строк annotations = ["key1=value1", "key2=value2"] - #Список taints + #список taints #опциональный параметр #тип - массив строк taints = ["key1=value1:NoSchedule", "key2=value2:NoExecute"] } - # id extnet + #id extnet #опциональный параметр - #тип - число + #тип - целое число extnet_id = 0 - # id vins - # опциональный параметр - # тип - число + #id vins + #опциональный параметр + #тип - целое число vins_id = 1234 - # создать Kubernetes cluster с masters nodes с подключенным LB - # опциональный параметр - # тип - булев тип + #создать Kubernetes cluster с masters nodes с подключенным LB + #опциональный параметр + #тип - булев with_lb = true - + # пользовательские значения sysctl для LB # опциональный параметр - # тип - строка - lb_sysctl_params = "some" + # тип - список мап + lb_sysctl_params = [{ text = "1", text = "some" }] # позволяет создать схему отказоустройчивой LB # опциональный параметр - # тип - булев тип + # тип - булев ha_mode = true - + # дополнительные SAN (Subject Alternative Names) для использования в процессе автоматического выписывания сертификата Кластера Kubernetes; # возможность взаимодействовать с кластером по FQDN # параметр получает список строк – IP-адреса и/или DNS (по формату RFC 1123 c поддержкой wildcard) # опциональный параметр # тип - массив строк - additional_sans = ["192.168.201.0","192.168.201.1"] + additional_sans = ["192.168.201.0", "192.168.201.1"] # используется для определения настроек и действий, которые должны быть выполнены перед запуском любого другого компонента в кластере # это позволяет вам настраивать такие вещи, как регистрация node, настройка network и другие задачи инициализации @@ -267,37 +273,31 @@ resource "decort_k8s" "cluster" { # перечень аргументов для cloud-init создаваемым группам узлов Worker # необязательный параметр - # тип - файл + # тип - файл с форматом в виде yaml cloud_init = file("initconfig.tftpl") # при создании кластре использовать подключение только к сети ExtNet # опциональный параметр - # тип - булев тип + # тип - булев extnet_only = true # добавить ssl-сертификат в формате x509 pem # необязательный параметр - # тип - файл + # тип - файл с форматом в виде x509 pem oidc_cert = file("ca.crt") # запуск,остановка кластера # опциональный параметр - # тип - булев тип + # тип - булев start = true # команда destroy удаляет кластер без возможности восстановления # опциональный параметр - # тип - булев тип + # тип - булев permanently = true + } output "test_cluster" { value = decort_k8s.cluster } - -/* -output "kubeconfig"{ - value = decort_k8s.cluster.kubeconfig -} - -*/ diff --git a/samples/cloudapi/resource_k8s/initconfig.tftpl b/samples/cloudapi/k8s/resource_k8s_cp/initconfig.tftpl similarity index 100% rename from samples/cloudapi/resource_k8s/initconfig.tftpl rename to samples/cloudapi/k8s/resource_k8s_cp/initconfig.tftpl diff --git a/samples/cloudapi/k8s/resource_k8s_cp/main.tf b/samples/cloudapi/k8s/resource_k8s_cp/main.tf new file mode 100644 index 0000000..7e53040 --- /dev/null +++ b/samples/cloudapi/k8s/resource_k8s_cp/main.tf @@ -0,0 +1,176 @@ +/* +Пример использования +Управление control plane кластера k8s +Ресурс позволяет: +1. Создать кластер +2. Удалить кластер +3. Настроить мастер-узел +4. Изменить кол-во ВМ в мастер-узле +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_k8s_cp" "cp" { + #название кластера + #обязательный параметр + #тип - строка + name = "k8s-cp" + + #K8sCI ID + #обязательный параметр + #тип - целое число + k8sci_id = 55 + + #плагин сети (flannel, weavenet или calico) + #обязательный параметр + #тип - строка + network_plugin = "flannel" + + #id ресурсной группы + #обязательный параметр + #тип - целое число + rg_id = 1387 + + #кол-во ядер мастер-узла + #опциональный параметр + #тип - целое число + cpu = 2 + + #объем RAM мастер-узла + #опциональный параметр + #тип - целое число + ram = 2048 + + #кол-во ВМ мастер-узла (1, 3 или 5) + #опциональный параметр + #тип - целое число + num = 1 + + #размер диска мастер-узла + #опциональный параметр + #тип - целое число + disk = 10 + + #описание кластера + #опциональный параметр + #тип - строка + desc = "" + + #id extnet + #опциональный параметр + #тип - целое число + extnet_id = 0 + + #id vins + #опциональный параметр + #тип - целое число + vins_id = 1234 + + #storage Endpoint ID + #опциональный параметр + #тип - целое число + sep_id = 0 + + #SEP Pool + #опциональный параметр + #тип - строка + sep_pool = "pool" + + #старт/стоп кластера + #опциональный параметр + #тип - булев + start = true + + #создать кластер с/без балансировщика нагрузки + #опциональный параметр + #тип - булев + with_lb = true + + #позволяет создать схему отказоустройчивой LB + #опциональный параметр + #тип - булев + ha_mode = true + + #дополнительные SAN (Subject Alternative Names) для использования в процессе автоматического выписывания сертификата Кластера Kubernetes; + #возможность взаимодействовать с кластером по FQDN + #параметр получает список строк – IP-адреса и/или DNS (по формату RFC 1123 c поддержкой wildcard) + #опциональный параметр + #тип - массив строк + additional_sans = ["192.168.201.0","192.168.201.1"] + + #используется для определения настроек и действий, которые должны быть выполнены перед запуском любого другого компонента в кластере + #это позволяет вам настраивать такие вещи, как регистрация node, настройка network и другие задачи инициализации + #опциональный параметр + #тип - строка + init_config = "{JSON string}" + + #используется для определения глобальных настроек и конфигураций для всего кластера + #он включает в себя такие параметры, как имя кластера, настройки DNS, методы аутентификации и другие конфигурации в масштабах кластера + #опциональный параметр + #тип - строка + cluster_config = "{JSON string}" + + #используется для настройки поведения и параметров Kubelet, который является агентом primary node, запускаемым на каждом node кластера + #он включает в себя такие параметры, как IP-адрес node, распределение ресурсов, политики удаления модулей и другие конфигурации, специфичные для Kubelet + #опциональный параметр + #тип - строка + kubelet_config = "{JSON string}" + + #используется для настройки поведения и параметров присоединения node к кластеру + #он включает в себя такие параметры, как режим прокси-сервера, диапазоны IP-адресов кластера и другие конфигурации, специфичные для Kube-proxy + #опциональный параметр + #тип - строка + kube_proxy_config = "{JSON string}" + + #используется для настройки поведения и параметров присоединения node к кластеру + #он включает в себя такие параметры, как cluster's control plane endpoint, токен и ключ сертификата + #опциональный параметр + #тип - строка + join_config = "{JSON string}" + + #при создании кластре использовать подключение только к сети ExtNet + #опциональный параметр + #тип - булев + extnet_only = true + + #добавить ssl-сертификат в формате x509 pem + #необязательный параметр + #тип - файл с форматом в виде x509 pem + oidc_cert = file("ca.crt") + + #пользовательские значения sysctl для LB + #опциональный параметр + #тип - список мап + lb_sysctl_params = [{text = "1", text = "some"}] + + #команда destroy удаляет кластер без возможности восстановления + #опциональный параметр + #тип - булев + permanently = true + +} + +output "cp_out" { + value = decort_k8s_cp.cp +} diff --git a/samples/cloudapi/resource_k8s_cp/initconfig.tftpl b/samples/cloudapi/k8s/resource_k8s_wg/initconfig.tftpl similarity index 100% rename from samples/cloudapi/resource_k8s_cp/initconfig.tftpl rename to samples/cloudapi/k8s/resource_k8s_wg/initconfig.tftpl diff --git a/samples/cloudapi/resource_k8s_wg/main.tf b/samples/cloudapi/k8s/resource_k8s_wg/main.tf similarity index 80% rename from samples/cloudapi/resource_k8s_wg/main.tf rename to samples/cloudapi/k8s/resource_k8s_wg/main.tf index 0a3b59d..6048535 100644 --- a/samples/cloudapi/resource_k8s_wg/main.tf +++ b/samples/cloudapi/k8s/resource_k8s_wg/main.tf @@ -1,8 +1,13 @@ +/* +Пример использования +Управления worker groups (рабочики группами, wg) кластера +Ресурс позволяет: +1. Создавать wg +*/ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - /* terraform { required_providers { @@ -20,8 +25,6 @@ provider "decort" { controller_url = "https://ds1.digitalenergy.online" #oauth2_url = oauth2_url = "https://sso.digitalenergy.online" - #app_id = - #app_secret = allow_unverified_ssl = true } @@ -29,7 +32,7 @@ provider "decort" { resource "decort_k8s_wg" "wg" { #id экземпляра k8s #обязательный параметр - #тип - число + #тип - целое число k8s_id = 1234 #имя worker group @@ -39,34 +42,35 @@ resource "decort_k8s_wg" "wg" { #количество worker node для создания #опциональный параметр - #тип - число + #тип - целое число #по - умолчанию - 1 num = 2 #количество cpu для 1 worker node #опциональный параметр - #тип - число + #тип - целое число #по - умолчанию - 1 cpu = 1 #количество RAM для одной worker node в Мбайтах #опциональный параметр - #тип - число + #тип - целое число #по-умолчанию - 1024 ram = 1024 #размер загрузочного диска для worker node, в Гбайтах #опциональный параметр - #тип - число + #тип - целое число #по - умолчанию - 0 #если установлен параметр 0, то размер диска будет равен размеру образа disk = 10 #Перечень аргументов для cloud-init для виртуальных машин worker групп #опциональный параметр - #тип - файл + #тип - файл с форматом в виде yaml #используется при создании и обновлении ресурса cloud_init = file("initconfig.tftpl") + } diff --git a/samples/cloudapi/data_kvmvm/main.tf b/samples/cloudapi/kvmvm/data_kvmvm/main.tf similarity index 86% rename from samples/cloudapi/data_kvmvm/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm/main.tf index 36b3112..8b7074c 100644 --- a/samples/cloudapi/data_kvmvm/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных о compute (виртуальной машине) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,10 +28,9 @@ provider "decort" { data "decort_kvmvm" "comp" { #получение информации по идентификатору машины - compute_id - - # id виртуальной машины - # обязательный параметр - # тип - число + #id виртуальной машины + #обязательный параметр + #тип - целое число compute_id = 11346 } diff --git a/samples/cloudapi/data_kvmvm_audits/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_audits/main.tf similarity index 96% rename from samples/cloudapi/data_kvmvm_audits/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_audits/main.tf index 0ad21a8..fd2507e 100644 --- a/samples/cloudapi/data_kvmvm_audits/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_audits/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных об аудитах compute (виртуальной машине) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_audits" "kvmvm_audits" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 } diff --git a/samples/cloudapi/data_kvmvm_get_audits/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_get_audits/main.tf similarity index 96% rename from samples/cloudapi/data_kvmvm_get_audits/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_get_audits/main.tf index 0c01b89..8a5f0b7 100644 --- a/samples/cloudapi/data_kvmvm_get_audits/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_get_audits/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных об аудитах compute (виртуальной машине) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_get_audits" "kvmvm_get_audits" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 } diff --git a/samples/cloudapi/data_kvmvm_get_console_url/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_get_console_url/main.tf similarity index 96% rename from samples/cloudapi/data_kvmvm_get_console_url/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_get_console_url/main.tf index 1009ebc..9c3fdab 100644 --- a/samples/cloudapi/data_kvmvm_get_console_url/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_get_console_url/main.tf @@ -2,6 +2,7 @@ Пример использования Получение url compute (виртуальной машины) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_get_console_url" "kvmvm_get_console_url" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 } diff --git a/samples/cloudapi/data_kvmvm_get_log/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_get_log/main.tf similarity index 97% rename from samples/cloudapi/data_kvmvm_get_log/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_get_log/main.tf index 15ae92c..1593237 100644 --- a/samples/cloudapi/data_kvmvm_get_log/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_get_log/main.tf @@ -2,6 +2,7 @@ Пример использования Получение логов compute (виртуальной машины) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_get_log" "kvmvm_get_log" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 #путь до log файла diff --git a/samples/cloudapi/data_kvmvm_list/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_list/main.tf similarity index 86% rename from samples/cloudapi/data_kvmvm_list/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_list/main.tf index b3d52be..84cbfc4 100644 --- a/samples/cloudapi/data_kvmvm_list/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных об списке compute (виртуальных машин) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_list" "compute_list" { #фильтр по id ВМ #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени ВМ @@ -37,7 +39,7 @@ data "decort_kvmvm_list" "compute_list" { #id аккаунта для получения списка ВМ #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по имени ресурсной группы @@ -47,7 +49,7 @@ data "decort_kvmvm_list" "compute_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -72,32 +74,34 @@ data "decort_kvmvm_list" "compute_list" { #фильтр по id extnet #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 #флаг влючения в результат удаленных балансироващиков нагрузки #опциональный параметр - #тип - булев тип + #тип - булев #значение по-умолчанию - false #если не задан - выводятся все доступные неудаленные балансировщики #includedeleted = true + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 - - #Включить в список вывода ВМ, принадлежащие k8s кластерам (при значении параметра true) - #опциональный параметр - #bool (default = false) - #ignore_k8s = true + } output "output" { diff --git a/samples/cloudapi/data_kvmvm_list_deleted/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_list_deleted/main.tf similarity index 84% rename from samples/cloudapi/data_kvmvm_list_deleted/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_list_deleted/main.tf index 2d3d9dd..e56e2c3 100644 --- a/samples/cloudapi/data_kvmvm_list_deleted/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_list_deleted/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных о списке удаленных compute (виртуальных машин) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_list_deleted" "compute_list" { #фильтр по id виртуальной машины #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени виртуальной машины @@ -37,7 +39,7 @@ data "decort_kvmvm_list_deleted" "compute_list" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #account_id = 100 #фильтр по имени ресурсной группы @@ -47,7 +49,7 @@ data "decort_kvmvm_list_deleted" "compute_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -67,18 +69,24 @@ data "decort_kvmvm_list_deleted" "compute_list" { #фильтр по id extNet #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/data_kvmvm_pci_device_list/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_pci_device_list/main.tf similarity index 81% rename from samples/cloudapi/data_kvmvm_pci_device_list/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_pci_device_list/main.tf index 1cb86d6..fde4f0e 100644 --- a/samples/cloudapi/data_kvmvm_pci_device_list/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_pci_device_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных о списке подключенных устройств (PCI) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,17 +29,17 @@ provider "decort" { data "decort_kvmvm_pci_device_list" "pci_device_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 100 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по id устройства #опциональный параметр - #тип - число + #тип - целое число #device_id = 100 #фильтр по имени устройства @@ -50,15 +52,21 @@ data "decort_kvmvm_pci_device_list" "pci_device_list" { #тип - строка #status = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/data_kvmvm_pfw_list/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_pfw_list/main.tf similarity index 96% rename from samples/cloudapi/data_kvmvm_pfw_list/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_pfw_list/main.tf index d03ebd1..59dda91 100644 --- a/samples/cloudapi/data_kvmvm_pfw_list/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_pfw_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных об списке port forwarding compute (виртуальных машин) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -15,6 +16,7 @@ terraform { } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_pfw_list" "kvmvm_pfw_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10524 } diff --git a/samples/cloudapi/kvmvm/data_kvmvm_snapshot_usage/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_snapshot_usage/main.tf new file mode 100644 index 0000000..46bc66c --- /dev/null +++ b/samples/cloudapi/kvmvm/data_kvmvm_snapshot_usage/main.tf @@ -0,0 +1,43 @@ +/* +Пример использования +Получение информации об использовании снапшотов +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_kvmvm_snapshot_usage" "snapshot_usage" { + #id виртуальной машины + #обязательный параметр + #тип - целое число + compute_id = 10154 + + #название снапшота + #опциональный параметр + #тип - строка + label = "label 1" +} + +output "output" { + value = data.decort_kvmvm_snapshot_usage.snapshot_usage +} diff --git a/samples/cloudapi/data_kvmvm_user_list/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_user_list/main.tf similarity index 96% rename from samples/cloudapi/data_kvmvm_user_list/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_user_list/main.tf index ea1cec7..39a8997 100644 --- a/samples/cloudapi/data_kvmvm_user_list/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_user_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных об юзерах compute (виртуальной машины) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_kvmvm_user_list" "kvmvm_user_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 } diff --git a/samples/cloudapi/data_kvmvm_vgpu_list/main.tf b/samples/cloudapi/kvmvm/data_kvmvm_vgpu_list/main.tf similarity index 82% rename from samples/cloudapi/data_kvmvm_vgpu_list/main.tf rename to samples/cloudapi/kvmvm/data_kvmvm_vgpu_list/main.tf index c5c5745..4982a55 100644 --- a/samples/cloudapi/data_kvmvm_vgpu_list/main.tf +++ b/samples/cloudapi/kvmvm/data_kvmvm_vgpu_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных о списке подключенных графических процессоров */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,12 +28,12 @@ provider "decort" { data "decort_kvmvm_vgpu_list" "vgpu_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 100 #фильтр по id графического процессора #опциональный параметр - #тип - число + #тип - целое число #gpu_id = 100 #фильтр по типу графического процессора @@ -47,18 +48,24 @@ data "decort_kvmvm_vgpu_list" "vgpu_list" { #фильтр "включая удаленные графические процессоры" #опциональный параметр - #тип - булев тип + #тип - булев #includedeleted = "false" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/resource_kvmvm/initconfig.tftpl b/samples/cloudapi/kvmvm/resource_kvmvm/initconfig.tftpl similarity index 100% rename from samples/cloudapi/resource_kvmvm/initconfig.tftpl rename to samples/cloudapi/kvmvm/resource_kvmvm/initconfig.tftpl diff --git a/samples/cloudapi/kvmvm/resource_kvmvm/main.tf b/samples/cloudapi/kvmvm/resource_kvmvm/main.tf new file mode 100644 index 0000000..acc2d44 --- /dev/null +++ b/samples/cloudapi/kvmvm/resource_kvmvm/main.tf @@ -0,0 +1,425 @@ +/* +Пример использования +Работа с ресурсом kvmvm (compute) +Ресурс позволяет: +1. Создавать compute +2. Редактировать compute +3. Удалять compute +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_kvmvm" "comp" { + #имя compute + #может быть изменен + #обязательный параметр + #тип - строка + name = "test-tf-compute-update-new" + + #id resource group + #обязательный параметр + #тип - целое число + rg_id = 1111 + + #тип драйвера для compute + #обязательный параметр + #тип - строка + driver = "KVM_X86" + + #число cpu + #обязательный параметр + #тип - целое число + cpu = 1 + + #кол-во оперативной памяти, МБ + #обязательный параметр + #тип - целое число + ram = 2048 + + #размер загрузочного диска + #опциональный параметр + #тип - целое число + boot_disk_size = 20 + + #id сепа для boot диска + #опциональный параметр + #тип - целое число + sep_id = 1 + + #название пула + #опциональный параметр + #тип - строка + pool = "data02" + + #конфигурация cloud init + #опциональный параметр + #тип - файл в формате JSON/YAML + cloud_init = file("initconfig.tftpl") + + #описание compute + #опциональный параметр + #тип - строка + description = "test update description in tf words update" + + #id образа диска для создания compute + #опциональный параметр + #тип - целое число + image_id = 111 + + #создание без загрузочного диска в остановленном состоянии + #опциональный параметр + #если значение равно True, параметры image_id, boot_disk_size, sep_id, pool игнорируются + #тип - булев + without_boot_disk = true + + #необходимость выравнивать ВМ по NUMA + #опциональный параметр + #возможные значения - "none, "strict", "loose" + #значение по умолчанию - "none" + #тип - строка + numa_affinity = "loose" + + #необходимость запускать ВМ на выделенных CPU ядрах + #опциональный параметр + #значение по умолчанию - false + #тип - булев + cpu_pin = true + + #необходимость использовать для выделения RAM виртуальной машины Huge Pages + #опциональный параметр + #значение по умолчанию - false + #тип - булев + hp_backed = true + + #создание и добавление диска дял compute + #опциональный параметр + #тип - список дисков + disks { + #Имя диска + #Обязательный для диска параметр + #тип - строка + disk_name = "disk_name" + + #Размер диска + #Обязательный для диска параметр + #тип - целоетчисло + size = 5 + + #тип диска + #опциональный параметр + #тип - строка + disk_type = "D" + + #id стораджа + #опциональный параметр + #тип - целое число + sep_id = 1 + + #название пула + #опциональный параметр + #тип - строка + pool = "data01" + + #описание диска + #опциональный параметр + #тип - строка + desc = "" + + #id образа + #опциональный параметр + #тип - целое число + image_id = 378 + + #флаг для удаления диска + #опциональный параметр + #тип - булев + permanently = false + } + + #правила affinity + #опциональный параметр + #может быть один, несколько или ни одного блока + #тип - блок правил + affinity_rules { + #тип правила + #обязательный параметр + #возможные значения - compute или node + #тип - строка + topology = "compute" + + #строгость правила + #обязательный параметр + #возможные значения - RECOMMENDED и REQUIRED + #тип - строка + policy = "RECOMMENDED" + + #режим проверки + #обязательный параметр + #возможные значения - ANY, EQ, NE + #тип - строка + mode = "ANY" + + #ключ правила + #обязательный параметр + #тип - строка + key = "testkey" + + #ключ правила + #необязательный параметр + #тип - строка + value = "testvalue" + } + + #правила anti-affinity + #опциональный параметр + #может быть один, несколько или ни одного блока + # тип - список правил + anti_affinity_rules { + #тип правила + #обязательный параметр + #возможные значения - compute или node + #тип - строка + topology = "compute" + + #строгость правила + #обязательный параметр + #возможные значения - RECOMMENDED и REQUIRED + #тип - строка + policy = "RECOMMENDED" + + #режим проверки + #обязательный параметр + #возможные значения - ANY, EQ, NE + #тип - строка + mode = "ANY" + + #ключ правила + #обязательный параметр + #тип - строка + key = "testkey" + + #ключ правила + #необязательный параметр + #тип -строка + value = "testvalue" + } + + #установка метки для вм + #опциональный параметр + #тип - строка + affinity_label = "test4" + + + #наименование системы + #опциональный параметр + #используется при создании вм + #по умолчанию - не задан + #тип - строка + is = "" + + #назначение вм + #опциональный параметр + #используется при создании вм + #по умолчанию - не задан + #тип - строка + ipa_type = "" + + #id экстра дисков + #опциональный параметр + #тип - список целых чисел + extra_disks = [1234, 4322, 1344] + + #присоеденения сетей и удаление сетей в компьюте + #опциональный параметр + #тип - блок сетей + network { + #тип сети VINS/EXTNET (для любого драйвера) и VFNIC (для KVM_X86) + #обязательный параметр + #тип - строка + net_type = "VINS" + + #id сети + #обязательный параметр + #тип - целое число + net_id = 1234 + + #ip адрес входящий в сеть + #опциональный параметр + #тип - строка + ip_address = "127.0.0.1" + } + + #добавление и удаление тэгов + #опциональный параметр + #тип - блок тэгов + tags { + #Ключ для тэга + #Обязательный параметр + #тип - строка + key = "key" + + #значения тэга + #обязательный параметр + #тип - строка + value = "value" + } + + #добавление и удаление port forwarding + #опциональный параметр + #тип - блок переадресации портов + port_forwarding { + #номер внешнего начального порта для правила + #Обязательный параметр + #тип - целое число + public_port_start = 2023 + + #номер внешнего последнего порта для правила + #опциональный параметр + #тип - целое число + #по умолчанию - -1 + public_port_end = 2023 + + #номер внутреннего базового порта + #обязательный параметр + #тип - целое число + local_port = 80 + + #сетевой протокол + #Обязательный параметр + #тип - строка + proto = "tcp" + } + + #предоставить/забрать пользователю доступ к компьюту + #опциональный параметр + #тип - блок прав пользователя + user_access { + #имя юзера, которому предоставляем доступ + #обязательный параметр + #тип - строка + username = "kasim_baybikov_1@decs3o" + + #права: 'R' - только на чтение, 'RCX' - чтение/запись, 'ARCXDU' - админ + #обязательный параметр + #тип - строка + access_type = "ARCXDU" + } + + #создать/удалить снапшот компьюта + #опциональный параметр + #тип - блок снапшотов + snapshot { + #лейбл снапшота + #обязательный параметр + #тип - строка + label = "label1" + } + + #rollback на нужный снапшот + #опциональный параметр + #Не имеет смысла при отсутсвии снапшотов + #тип - блок rollback + rollback { + #Лейбл снапшота + #Обязательный параметр + #тип - строка + label = "label1" + } + + #вставить/удалить СD rom + #опциональный параметр + #максимальное кол-во - 1 + #тип - блок cd + cd { + #id образа диска CD rom + #обязательный параметр + #тип - целое число + cdrom_id = 344 + } + + #добавить компьют на стэк + #опциональный параметр + #тип - булев + pin_to_stack = true + + #флаг доступности компьюта для проведения с ним операций + #опциональный параметр + #тип - булев + enabled = true + + #pause/resume компьюта + #опциональный параметр + #тип - булев + pause = true + + #сделать компьют заново + #опциональный параметр + #тип - булев + reset = true + + #восстановить компьют из корзины + #опциональный параметр + #тип - булев + restore = true + + #флаг для редеплоя компьюта + #опциональный параметр + #тип - булев + auto_start = true + + #флаг для редеплоя компьюта + #опциональный параметр + #тип - булев + force_stop = true + + #флаг для ресайза компьюта + #опциональный параметр + #тип - булев + force_resize = true + + #поле для редеплоя компьюта + #опциональный параметр + #тип - строка + data_disks = "KEEP" + + #запуск/стоп компьюта + #опциональный параметр + #тип - булев + started = true + + #detach диска при удалении компьюта + #опциональный параметр + #тип - булев + detach_disks = true + + #флаг для удаления компьюта + #опциональный параметр + #тип - булев + permanently = false + +} + +output "test" { + value = decort_kvmvm.comp +} diff --git a/samples/cloudapi/data_lb/main.tf b/samples/cloudapi/lb/data_lb/main.tf similarity index 96% rename from samples/cloudapi/data_lb/main.tf rename to samples/cloudapi/lb/data_lb/main.tf index 9c6d68c..03d9377 100644 --- a/samples/cloudapi/data_lb/main.tf +++ b/samples/cloudapi/lb/data_lb/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о load balancer (балансировщик нагрузок) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_lb" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 238 } diff --git a/samples/cloudapi/data_lb_list/main.tf b/samples/cloudapi/lb/data_lb_list/main.tf similarity index 81% rename from samples/cloudapi/data_lb_list/main.tf rename to samples/cloudapi/lb/data_lb_list/main.tf index 6e97ff8..7ae1af7 100644 --- a/samples/cloudapi/data_lb_list/main.tf +++ b/samples/cloudapi/lb/data_lb_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка load balancer (балансировщиков нагрузки) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +30,7 @@ provider "decort" { data "decort_lb_list" "lbl" { #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени балансировщика нагрузки @@ -39,12 +40,12 @@ data "decort_lb_list" "lbl" { #id аккаунта для получения списка балансировщиков нагрузки #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -67,22 +68,28 @@ data "decort_lb_list" "lbl" { #тип - строка #back_ip = "ENABLED" - #флаг влючения в результат удаленных балансироващиков нагрузки + #флаг влючения в результат удаленных балансировщиков нагрузки #опциональный параметр - #тип - булев тип + #тип - булев #значение по-умолчанию - false #если не задан - выводятся все доступные неудаленные балансировщики #includedeleted = true + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/data_lb_list_deleted/main.tf b/samples/cloudapi/lb/data_lb_list_deleted/main.tf similarity index 81% rename from samples/cloudapi/data_lb_list_deleted/main.tf rename to samples/cloudapi/lb/data_lb_list_deleted/main.tf index 6481a84..dcc862f 100644 --- a/samples/cloudapi/data_lb_list_deleted/main.tf +++ b/samples/cloudapi/lb/data_lb_list_deleted/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка удаленных load balancer (балансировщиков нагрузок) - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_lb_list_deleted" "lbld" { #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени балансировщика нагрузки @@ -39,12 +39,12 @@ data "decort_lb_list_deleted" "lbld" { #id аккаунта для получения списка балансировщиков нагрузки #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -62,15 +62,21 @@ data "decort_lb_list_deleted" "lbld" { #тип - строка #back_ip = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudbroker/resource_lb/main.tf b/samples/cloudapi/lb/resource_lb/main.tf similarity index 58% rename from samples/cloudbroker/resource_lb/main.tf rename to samples/cloudapi/lb/resource_lb/main.tf index 077479d..99e26eb 100644 --- a/samples/cloudbroker/resource_lb/main.tf +++ b/samples/cloudapi/lb/resource_lb/main.tf @@ -1,107 +1,120 @@ -/* -Пример использования -Ресурса load balancer -Ресурс позволяет: -1. Создавать load balancer -2. Редактировать load balancer -3. Удалять load balancer - -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_cb_lb" "lb" { - #id ресурсной группы для создания балансировщика - #обязательный параметр - #тип - число - rg_id = 1111 - - #наименование load balancer - #обязательный параметр - #тип - строка - name = "tf-test-lb" - - #id внешней сети и id виртуальной сети не могут быть одновременно = 0 - - #id внешней сети - #опциональный параметр - #тип - число - extnet_id = 6 - - #id виртуальной сети - #опциональный параметр - #тип - число - vins_id = 758 - - #флаг запуска load balancer - #обязательный параметр - #тип - булев тип - #по умолчанию - true - #если load balancer был в статусе "stopped" (start = false), - #то для успешного старта, он должен быть доступен (enable = true) - start = true - - # позволяет создать схему отказоустройчивой LB - # опциональный параметр - # тип - булев тип - #ha_mode = true - - #описание - #опциональный параметр - #тип - строка - #desc = "temp super lb for testing tf provider" - - #флаг доступности load balancer - #необязательный параметр - #тип - булев тип - #enable = true - - #флаг перезапуска load balancer - #необязательный параметр - #тип - булев тип - #перезагрузка срабатывает только при изменении флага с false на true - #restart = false - - #флаг сброса конфигурации load balancer - #необязательный параметр - #тип - булев тип - #сброс срабатывает только при изменении флага с false на true - #config_reset = false - - #флаг моментального удаления load balancer - #необязательный параметр - #тип - булев тип - #по умолчанию - false - #применяется при выполнении команды terraform destroy - #permanently = false - - #флаг восстановления load balancer - #необязательный параметр - #тип - булев тип - #восстановить можно load balancer, удаленным с флагом permanently = false - #restore = true -} - -output "test" { - value = decort_cb_lb.lb -} +/* +Пример использования +Управление балансировщиком нагрузки (load balancer) +Ресурс позволяет: +1. Создавать load balancer +2. Редактировать load balancer +3. Удалять load balancer +/* + +#Расскомментируйте этот код +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_lb" "lb" { + #id ресурсной группы для со + #обязательный параметр + #тип - целое число + rg_id = 1111 + + #наименование load balancer + #обязательный параметр + #тип - строка + name = "tf-test-lb" + + #id внешней сети + #опциональный параметр + #id внешней сети и id виртуальной сети не могут быть одновременно = 0 + #тип - целое число + extnet_id = 6 + + #id виртуальной сети + #опциональный параметр + #id внешней сети и id виртуальной сети не могут быть одновременно = 0 + #тип - целое число + vins_id = 758 + + #флаг запуска load balancer + #обязательный параметр + #если load balancer был в статусе "stopped" (start = false), + #то для успешного старта, он должен быть доступен (enable = true) + #по умолчанию - true + #тип - булев + start = true + + #позволяет создать схему отказоустройчивой LB + #опциональный параметр + #тип - булев + ha_mode = true + + #описание + #опциональный параметр + #тип - строка + desc = "temp super lb for testing tf provider" + + #флаг доступности load balancer + #опциональный параметр + #тип - булев + enable = true + + #флаг перезапуска load balancer + #перезагрузка срабатывает только при изменении флага с false на true + #опциональный параметр + #тип - булев + restart = false + + #флаг сброса конфигурации load balancer + #сброс срабатывает только при изменении флага с false на true + #опциональный параметр + #тип - булев + config_reset = false + + #флаг моментального удаления load balancer + #опциональный параметр + #применяется при выполнении команды terraform destroy + #по умолчанию - false + #тип - булев + permanently = false + + #флаг восстановления load balancer + #опциональный параметр + #восстановить можно load balancer, удаленным с флагом permanently = false + #тип - булев + restore = true + + #флаг используемый при рестарте load balancer + #опциональный параметр + #при значении "true" рестарт производится на обоих нодах в HA mode + #значение по умолчанию - true + #тип - булев + safe = true + + #пользовательские значения sysctl для LB + #опциональный параметр + #тип - список мап + sysctl_params = [{ text = "1", text = "some" }] + +} + +output "test" { + value = decort_lb.lb +} diff --git a/samples/cloudapi/resource_lb_backend/main.tf b/samples/cloudapi/lb/resource_lb_backend/main.tf similarity index 76% rename from samples/cloudapi/resource_lb_backend/main.tf rename to samples/cloudapi/lb/resource_lb_backend/main.tf index b98b3df..89e0322 100644 --- a/samples/cloudapi/resource_lb_backend/main.tf +++ b/samples/cloudapi/lb/resource_lb_backend/main.tf @@ -5,8 +5,8 @@ 1. Создавать backend 2. Редактировать backend 3. Удалять backend - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,7 +33,7 @@ provider "decort" { resource "decort_lb_backend" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя бекенда для создания сервера @@ -42,65 +42,65 @@ resource "decort_lb_backend" "lb" { name = "testBackend" #алгоритм балансировки - #опицональный параметр - #тип - строка + #опциональный параметр #по умолчанию - "roundrobin" #доступные значения - "roundrobin", "static-rr", "leastconn" - #algorithm = "roundrobin" + #тип - строка + lgorithm = "roundrobin" #------------------- #настройки для серверов по умолчанию #------------------- #интервал между проверками, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 5000 - #inter = 5000 + #тип - целое число + inter = 5000 #интервал между проверками доступности сервера после восстановления, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 1000 - #downinter = 1000 + #тип - целое число + downinter = 1000 #кол-во проверок, которые сервер должен успешно пройти - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 2 - #rise = 2 + #тип - целое число + rise = 2 #кол-во проверок, которые сервер может не пройти и после этого получить статус "unavailable" - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 2 - #fall = 2 + #тип - целое число + fall = 2 #кол-во миллисекунд - время между получением сервера статуса "available" и открытием соединений - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 60000 - #slowstart = 60000 + #тип - целое число + slowstart = 60000 #максимальное кол-во соединений сервера, при достижении этого кол-ва, сервер выходит из схемы балансирования - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 250 - #maxconn = 250 + #тип - целое число + maxconn = 250 #максимальное кол-во соединений в очереди серевера, при достижении этого кол-ва, соединения будут перенаправлены на другой сервер - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 256 - #maxqueue = 256 + #тип - целое число + maxqueue = 256 #вес сервера для балансировки - #опицональный параметр - #тип - число + #опциональный параметр #мин - 0 #макс - 255 #по умолчанию - 100 - #weight = 100 + #тип - целое число + weight = 100 timeouts { create = "5m" @@ -108,6 +108,7 @@ resource "decort_lb_backend" "lb" { update = "5m" delete = "5m" } + } output "test" { diff --git a/samples/cloudapi/resource_lb_backend_server/main.tf b/samples/cloudapi/lb/resource_lb_backend_server/main.tf similarity index 80% rename from samples/cloudapi/resource_lb_backend_server/main.tf rename to samples/cloudapi/lb/resource_lb_backend_server/main.tf index f20e09c..b796d38 100644 --- a/samples/cloudapi/resource_lb_backend_server/main.tf +++ b/samples/cloudapi/lb/resource_lb_backend_server/main.tf @@ -5,8 +5,8 @@ 1. Создавать server 2. Редактировать server 3. Удалять server - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,7 +33,7 @@ provider "decort" { resource "decort_lb_backend_server" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя бекенда для создания сервера @@ -53,64 +53,64 @@ resource "decort_lb_backend_server" "lb" { #порт сервера #обязательный параметр - #тип - число + #тип - целое число port = 6553 #проверка доступности сервера - #опицональный параметр - #тип - строка + #опциональный параметр #по умолчанию - "enabled" #доступные значения - "disabled", "enabled" + #тип - строка #check = "enabled" #интервал между проверками, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 5000 + #тип - целое число #inter = 5000 #интервал между проверками доступности сервера после восстановления, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 1000 + #тип - целое число #downinter = 1000 #кол-во проверок, которые сервер должен успешно пройти - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #по умолчанию - 2 #rise = 2 #кол-во проверок, которые сервер может не пройти и после этого получить статус "unavailable" - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 2 + #тип - целое число #fall = 2 #кол-во миллисекунд - время между получением сервера статуса "available" и открытием соединений - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 60000 + #тип - целое число #slowstart = 60000 #максимальное кол-во соединений сервера, при достижении этого кол-ва, сервер выходит из схемы балансирования - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 250 + #тип - целое число #maxconn = 250 #максимальное кол-во соединений в очереди серевера, при достижении этого кол-ва, соединения будут перенаправлены на другой сервер - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 256 + #тип - целое число #maxqueue = 256 #вес сервера для балансировки - #опицональный параметр - #тип - число + #опциональный параметр #мин - 0 #макс - 255 #по умолчанию - 100 + #тип - целое число #weight = 100 timeouts { @@ -119,6 +119,7 @@ resource "decort_lb_backend_server" "lb" { update = "5m" delete = "5m" } + } output "test" { diff --git a/samples/cloudapi/resource_lb_frontend/main.tf b/samples/cloudapi/lb/resource_lb_frontend/main.tf similarity index 93% rename from samples/cloudapi/resource_lb_frontend/main.tf rename to samples/cloudapi/lb/resource_lb_frontend/main.tf index 12ee631..718419d 100644 --- a/samples/cloudapi/resource_lb_frontend/main.tf +++ b/samples/cloudapi/lb/resource_lb_frontend/main.tf @@ -4,8 +4,8 @@ Ресурс позволяет: 1. Создавать frontend 2. Удалять frontend - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -13,8 +13,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -32,7 +32,7 @@ provider "decort" { resource "decort_lb_frontend" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя бекенда для создания фронтенда @@ -51,6 +51,7 @@ resource "decort_lb_frontend" "lb" { update = "5m" delete = "5m" } + } output "test" { diff --git a/samples/cloudapi/resource_lb_frontend_bind/main.tf b/samples/cloudapi/lb/resource_lb_frontend_bind/main.tf similarity index 93% rename from samples/cloudapi/resource_lb_frontend_bind/main.tf rename to samples/cloudapi/lb/resource_lb_frontend_bind/main.tf index 40cd7ef..582fd9f 100644 --- a/samples/cloudapi/resource_lb_frontend_bind/main.tf +++ b/samples/cloudapi/lb/resource_lb_frontend_bind/main.tf @@ -5,8 +5,8 @@ 1. Создавать привязку 2. Редактировать привязку 3. Удалять привязку - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,7 +33,7 @@ provider "decort" { resource "decort_lb_frontend_bind" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя фронтенда для создания привязки @@ -53,7 +53,7 @@ resource "decort_lb_frontend_bind" "lb" { #порт для привязки фронтенда #обязательный параметр - #тип - число + #тип - целое число port = 1111 timeouts { @@ -62,6 +62,7 @@ resource "decort_lb_frontend_bind" "lb" { update = "5m" delete = "5m" } + } output "test" { diff --git a/samples/cloudapi/location/data_location_url/main.tf b/samples/cloudapi/location/data_location_url/main.tf new file mode 100644 index 0000000..ca85b20 --- /dev/null +++ b/samples/cloudapi/location/data_location_url/main.tf @@ -0,0 +1,36 @@ +/* +Пример использования +Получение информации о площадках +Ресурс позволяет: +1. получать информацию об url площадки (grid/location). +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_location_url" "lu" { +} + +output "test" { + value = data.decort_location_url.lu +} diff --git a/samples/cloudapi/data_locations_list/main.tf b/samples/cloudapi/location/data_locations_list/main.tf similarity index 74% rename from samples/cloudapi/data_locations_list/main.tf rename to samples/cloudapi/location/data_locations_list/main.tf index 25b4ec2..4135371 100644 --- a/samples/cloudapi/data_locations_list/main.tf +++ b/samples/cloudapi/location/data_locations_list/main.tf @@ -1,19 +1,19 @@ /* Пример использования -Получение информации о доступных локациях +Получение информации о доступных локациях. Ресурс позволяет: -Используется для получения информации о grid_id для создания ресурсов +1) получать информацию о grid_id для создания ресурсов */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -36,7 +36,7 @@ data "decort_locations_list" "ll" { #фильтр по id локации #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени локации @@ -49,14 +49,20 @@ data "decort_locations_list" "ll" { #тип - строка #location_code = "europe" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода #опицональный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #опицональный параметр - #тип - число + #тип - целое число #size = 1 } diff --git a/samples/cloudapi/pfw/resource_pfw/main.tf b/samples/cloudapi/pfw/resource_pfw/main.tf new file mode 100644 index 0000000..618b788 --- /dev/null +++ b/samples/cloudapi/pfw/resource_pfw/main.tf @@ -0,0 +1,61 @@ +/* +Пример использования +Управление правилами трансляции сетевых портов для виртуальных серверов +Ресурс позволяет: +1. Создавать правила для трансляции сетевых портов +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_pfw" "pfw" { + #id виртуальной машины + #обязательный параметр + #тип - целое число + compute_id = 11269 + + #начальный порт правила + #обязательный параметр + #тип - целое число + public_port_start = 200 + + #внутренний порт + #обязательный параметр + #тип - целое число + local_base_port = 22 + + #протокол соединения (tcp / udp) + #обязательный параметр + ##тип - строка + proto = "tcp" + + #конечный порт (включительно) + #опциональный параметр + #тип - целое число + public_port_end = 21321 + +} + +output "pfw_out" { + value = decort_pfw.pfw +} diff --git a/samples/cloudapi/resource_disk/main.tf b/samples/cloudapi/resource_disk/main.tf deleted file mode 100644 index 5581c98..0000000 --- a/samples/cloudapi/resource_disk/main.tf +++ /dev/null @@ -1,56 +0,0 @@ -/* -Пример использования -Получение списка доступных образов -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} - - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_disk" "acl" { - account_id = 88366 - gid = 212 - disk_name = "super-disk-re" - size_max = 20 - permanently = true - reason = "delete" - shareable = false - iotune { - read_bytes_sec = 0 - read_bytes_sec_max = 0 - read_iops_sec = 0 - read_iops_sec_max = 0 - size_iops_sec = 0 - total_bytes_sec = 0 - total_bytes_sec_max = 0 - total_iops_sec = 3000 - total_iops_sec_max = 0 - write_bytes_sec = 0 - write_bytes_sec_max = 0 - write_iops_sec = 0 - write_iops_sec_max = 0 - } - -} - -output "test" { - value = decort_disk.acl -} diff --git a/samples/cloudapi/resource_flipgroup/main.tf b/samples/cloudapi/resource_flipgroup/main.tf deleted file mode 100644 index e9428ca..0000000 --- a/samples/cloudapi/resource_flipgroup/main.tf +++ /dev/null @@ -1,68 +0,0 @@ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_flipgroup" "fg" { - # ID аккаунта - # Обязательный параметр - # int - account_id = 999 - - # Наименование Flipgroup - # Обязательный параметр - # string - name = "flipgroup_name" - - # Тип сети (EXTNET, ViNS) - # Обязательный параметр - # string - net_type = "EXTNET" - - # ID сети - # Обязательный параметр - # int - net_id = 13 - - # Тип клиентов (в данный момент поддерживается только тип 'compute') - # Обязательный параметр - # string - client_type = "compute" - - # IP-адрес - # Опциональный параметр - # string - ip = "127.0.0.1" - - # Список клиентов, прикрепленных к флипгруппе - # Опциональный параметр - # []int - client_ids = [11269] - - # Описание флипгруппы - # Опциональный параметр - # string - desc = "CHANGED" -} - -output "fg_out" { - value = decort_flipgroup.fg -} diff --git a/samples/cloudapi/resource_image/main.tf b/samples/cloudapi/resource_image/main.tf deleted file mode 100644 index eb5e555..0000000 --- a/samples/cloudapi/resource_image/main.tf +++ /dev/null @@ -1,108 +0,0 @@ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_image" "img" { - # Наименование образа - # Обязательный параметр - # string - name = "image_name" - - # grid ID платформы - # Обязательный параметр - # int - gid = 2002 - - # Драйверы компьютов, подходящие для данного образа - # Обязательный параметр - # []string - drivers = ["KVM_X86"] - - # Тип образа (linux, windows и др.) - # Обязательный параметр - # string - type = "linux" - - # Прямая ссылка на образ - # Обязательный параметр - # string - url = "https://dl-cdn.alpinelinux.org/alpine/v3.17/releases/x86_64/alpine-virt-3.17.3-x86_64.iso" - - # Тип загрузчика (bios/uefi) - # Обязательный параметр - # string - boot_type = "bios" - - # ID аккаунта - # Опциональный параметр - # int - account_id = 138 - - # Поддержка hot resize - # Опциональный параметр - # bool - hot_resize = true - - # Юзернейм для образа - # Опциональный параметр - # string - username = "userx" - - # Пароль для образа - # Опциональный параметр - # string - password = "passx" - - # Юзернейм для загрузки binary media - # Опциональный параметр - # string - username_dl = "userxdl" - - # Пароль для загрузки binary media - # Опциональный параметр - # string - password_dl = "passxdl" - - # Storage endpoint provider ID - # Опциональный параметр - # int - sep_id = 1 - - # Pool для образа - # Опциональный параметр - # string - pool_name = "pool" - - # Архитектура обраща (X86_64 / PPC64_LE) - # Опциональный параметр - # string - architecture = "PPC64_LE" - - # Флаг окончательного удаления - # Опциональный параметр - # булев тип - permanently = true -} - -output "img_out" { - value = decort_image.img -} diff --git a/samples/cloudapi/resource_k8s_cp/main.tf b/samples/cloudapi/resource_k8s_cp/main.tf deleted file mode 100644 index 9129276..0000000 --- a/samples/cloudapi/resource_k8s_cp/main.tf +++ /dev/null @@ -1,164 +0,0 @@ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - #app_id = - #app_secret = - allow_unverified_ssl = true -} - -resource "decort_k8s_cp" "cp" { - # Название кластера - # Обязательный параметр - # string - name = "k8s-cp" - - # K8sCI ID - # Обязательный параметр - # int - k8sci_id = 55 - - # Плагин сети (flannel, weavenet или calico) - # Обязательный параметр - # string - network_plugin = "flannel" - - # ID ресурсной группы - # Обязательный параметр - # int - rg_id = 1387 - - # Кол-во ядер мастер-узла - # Опциональный параметр - # int - cpu = 2 - - # Объем RAM мастер-узла - # Опциональный параметр - # int - ram = 2048 - - # Кол-во ВМ мастер-узла (1 или 3) - # Опциональный параметр - # int - num = 1 - - # Размер диска мастер-узла - # Опциональный параметр - # int - disk = 10 - - # Описание кластера - # Опциональный параметр - # string - desc = "" - - # id extnet - #опциональный параметр - #тип - число - extnet_id = 0 - - # id vins - # опциональный параметр - # тип - число - vins_id = 1234 - - # Storage Endpoint ID - # Опциональный параметр - # id - sep_id = 0 - - # SEP Pool - # Опциональный параметр - # string - sep_pool = "pool" - - # Старт/Стоп кластера - # Опциональный параметр - # bool - start = true - - # Создать кластер с/без балансировщика нагрузки - # Опциональный параметр - # bool - with_lb = true - - # позволяет создать схему отказоустройчивой LB - # опциональный параметр - # тип - булев тип - ha_mode = true - - # дополнительные SAN (Subject Alternative Names) для использования в процессе автоматического выписывания сертификата Кластера Kubernetes; - # возможность взаимодействовать с кластером по FQDN - # параметр получает список строк – IP-адреса и/или DNS (по формату RFC 1123 c поддержкой wildcard) - # опциональный параметр - # тип - массив строк - additional_sans = ["192.168.201.0","192.168.201.1"] - - # используется для определения настроек и действий, которые должны быть выполнены перед запуском любого другого компонента в кластере - # это позволяет вам настраивать такие вещи, как регистрация node, настройка network и другие задачи инициализации - # опциональный параметр - # тип - строка - init_config = "{JSON string}" - - # используется для определения глобальных настроек и конфигураций для всего кластера - # он включает в себя такие параметры, как имя кластера, настройки DNS, методы аутентификации и другие конфигурации в масштабах кластера - # опциональный параметр - # тип - строка - cluster_config = "{JSON string}" - - # используется для настройки поведения и параметров Kubelet, который является агентом primary node, запускаемым на каждом node кластера - # он включает в себя такие параметры, как IP-адрес node, распределение ресурсов, политики удаления модулей и другие конфигурации, специфичные для Kubelet - # опциональный параметр - # тип - строка - kubelet_config = "{JSON string}" - - # используется для настройки поведения и параметров присоединения node к кластеру - # он включает в себя такие параметры, как режим прокси-сервера, диапазоны IP-адресов кластера и другие конфигурации, специфичные для Kube-proxy - # опциональный параметр - # тип - строка - kube_proxy_config = "{JSON string}" - - # используется для настройки поведения и параметров присоединения node к кластеру - # он включает в себя такие параметры, как cluster's control plane endpoint, токен и ключ сертификата - # опциональный параметр - # тип - строка - join_config = "{JSON string}" - - # при создании кластер использовать подключение только к сети ExtNet - # опциональный параметр - # тип - булев тип - extnet_only = true - - # добавить ssl-сертификат в формате x509 pem - # необязательный параметр - # тип - файл - oidc_cert = file("ca.crt") - - # команда destroy удаляет кластер без возможности восстановления - # опциональный параметр - # тип - булев тип - permanently = true - -} - -output "cp_out" { - value = decort_k8s_cp.cp -} diff --git a/samples/cloudapi/resource_kvmvm/main.tf b/samples/cloudapi/resource_kvmvm/main.tf deleted file mode 100644 index 01e68a9..0000000 --- a/samples/cloudapi/resource_kvmvm/main.tf +++ /dev/null @@ -1,400 +0,0 @@ -/* -Пример использования -Работа с ресурсом kvmvm (compute) -Ресурс позволяет: -1. Создавать compute -2. Редактировать compute -3. Удалять compute -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - #app_id = - #app_secret = - allow_unverified_ssl = true -} - -resource "decort_kvmvm" "comp" { - #имя compute - #обязательный параметр - #мб изменен - #тип - строка - name = "test-tf-compute-update-new" - - #id resource group - #обязательный параметр - #тип - число - rg_id = 1111 - - #тип драйвера для compute - #обязательный параметр - #тип - строка - driver = "KVM_X86" - - #число cpu - #обязательный параметр - #тип - число - cpu = 1 - - #кол-во оперативной памяти, МБ - #обязательный параметр - #тип - число - ram = 2049 - - #id образа диска для создания compute - #обязательный параметр - #тип - число - image_id = 111 - - #размер загрузочного диска - #обязательный параметр - #тип - число - boot_disk_size = 20 - - #ID сепа для boot диска - #опциональный параметр - #тип - число - sep_id = 1 - - #Название пула - #опциональный параметр - #тип - строка - pool = "data02" - - #конфигурация cloud init - #опциональный параметр - #тип - файл в формате JSON/YAML - cloud_init = file("initconfig.tftpl") - - #описание compute - #опциональный параметр - #тип - строка - description = "test update description in tf words update" - - #Создание и добавление диска дял compute - #опциональный параметр - #тип - список дисков - disks { - #Имя диска - #Обязательный для диска параметр - #Тип - строка - disk_name = "disk_name" - - #Размер диска - #Обязательный для диска параметр - #Тип - число - size = 5 - - #Тип диска - #опциональный параметр - #тип - строка - disk_type = "D" - - #опциональный параметр - #тип - число - sep_id = 1 - - #Название пула - #опциональный параметр - #тип - строка - pool = "data01" - - #Описание диска - #опциональный параметр - #тип - строка - desc = "" - - #Айди образа - #опциональный параметр - #опциональный параметр - image_id = 378 - - #Флаг для удаления диска - #опциональный параметр - #тип - bool - permanently = false - } - - #правила affinity - #опциональный параметр - #может быть один, несколько или ни одного блока - #тип - блок - affinity_rules { - #тип правила - #возможные значения - compute или node - #обязательный параметр - #тип - строка - topology = "compute" - - #строгость правила - #возможные значения - RECOMMENDED и REQUIRED - #обязательный параметр - #тип - строка - policy = "RECOMMENDED" - - #режим проверки - #возможные значения - ANY, EQ, NE - #обязательный параметр - #тип - строка - mode = "ANY" - - #ключ правила - #обязательный параметр - #тип строка - key = "testkey" - - #ключ правила - #необязательный параметр - #тип строка - value = "testvalue" - } - - #правила anti-affinity - #опциональный параметр - #может быть один, несколько или ни одного блока - #тип - блок - anti_affinity_rules { - #тип правила - #возможные значения - compute или node - #обязательный параметр - #тип - строка - topology = "compute" - - #строгость правила - #возможные значения - RECOMMENDED и REQUIRED - #обязательный параметр - #тип - строка - policy = "RECOMMENDED" - - #режим проверки - #возможные значения - ANY, EQ, NE - #обязательный параметр - #тип - строка - mode = "ANY" - - #ключ правила - #обязательный параметр - #тип строка - key = "testkey" - - #ключ правила - #необязательный параметр - #тип строка - value = "testvalue" - } - - #установка метки для вм - #опциональный параметр - #тип - строка - affinity_label = "test4" - - - #наименование системы - #опциональный параметр - #используется при создании вм - #по умолчанию - не задан - #тип - строка - is="" - - #назначение вм - #опциональный параметр - #используется при создании вм - #по умолчанию - не задан - #тип - строка - ipa_type = "" - - #Id экстра дисков - #опциональный параметр - #тип - список чисел - extra_disks = [1234, 4322, 1344] - - #Присоеденения сетей и удаление сетей в компьюте - #опциональный параметр - #тип - блок - network { - #Тип сети VINS/EXTNET - #Обязательный параметр - #тип - строка - net_type = "VINS" - - #ID сети - #Обязательный параметр - #тип - число - net_id = 1234 - - #IP адрес входящий в сеть - #опциональный параметр - #тип - строка - ip_address = "127.0.0.1" - } - - #добавление и удаление тэгов - #опциональный параметр - #тип - блок - tags { - #Ключ для тэга - #Обязательный параметр - #тип - строка - key = "key" - - #Значения тэга - #Обязательный параметр - #тип - строка - value = "value" - } - - #добавление и удаление port forwarding - #опциональный параметр - #тип - блок - port_forwarding { - #номер внешнего начального порта для правила - #Обязательный параметр - #тип - число - public_port_start = 2023 - - #номер внешнего последнего порта для правила - #опциональный параметр - #тип - число - #по умолчанию - -1 - public_port_end = 2023 - - #номер внутреннего базового порта - #Обязательный параметр - #тип - число - local_port = 80 - - #сетевой протокол - #Обязательный параметр - #тип - строка - proto = "tcp" - } - - #предоставить/забрать пользователю доступ к компьюту - #опциональный параметр - #тип - блок - user_access { - #Имя юзера, которому предоставляем доступ - #Обязательный параметр - #тип - строка - username = "kasim_baybikov_1@decs3o" - - #Права: 'R' - только на чтение, 'RCX' - чтение/запись, 'ARCXDU' - админ - #Обязательный параметр - #тип - строка - access_type = "ARCXDU" - } - - #Создать/удалить снапшот компьюта - #опциональный параметр - #тип - блок - snapshot { - #Лейбл снапшота - #Обязательный параметр - #тип - строка - label = "label1" - } - - #Rollback на нужный снапшот - #опциональный параметр - #Не имеет смысла при отсутсвии снапшотов - #тип - блок - rollback { - #Лейбл снапшота - #Обязательный параметр - #тип - строка - label = "label1" - } - - #Вставить/удалить СD rom - #опциональный параметр - #Максимальное кол-во - 1 - #тип - блок - cd { - #ID образа диска CD rom - #Обязательный параметр - #тип - число - cdrom_id = 344 - } - - #Добавить компьют на стэк - #опциональный параметр - #тип - булев - pin_to_stack = true - - #Флаг доступности компьюта для проведения с ним операций - #опциональный параметр - #тип - булев - enabled = true - - #pause/resume компьюта - #опциональный параметр - #тип - булев - pause = true - - #сделать компьют заново - #опциональный параметр - #тип - булев - reset = true - - #восстановить компьют из корзины - #опциональный параметр - #тип - булев - restore = true - - #флаг для редеплоя компьюта - #опциональный параметр - #тип - булев - auto_start = true - - #флаг для редеплоя компьюта - #опциональный параметр - #тип - булев - force_stop = true - - #флаг для ресайза компьюта - #опциональный параметр - #тип - булев - force_resize = true - - #поле для редеплоя компьюта - #опциональный параметр - #тип - строка - data_disks = "KEEP" - - #запуск/стоп компьюта - #опциональный параметр - #тип - булев - started = true - - #detach диска при удалении компьюта - #опциональный параметр - #тип - булев - detach_disks = true - - #Флаг для удаления компьюта - #опциональный параметр - #тип - bool - permanently = false -} - -output "test" { - value = decort_kvmvm.comp -} diff --git a/samples/cloudapi/resource_pfw/main.tf b/samples/cloudapi/resource_pfw/main.tf deleted file mode 100644 index 650e977..0000000 --- a/samples/cloudapi/resource_pfw/main.tf +++ /dev/null @@ -1,53 +0,0 @@ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_pfw" "pfw" { - # ID виртуальной машины - # Обязательный параметр - # int - compute_id = 11269 - - # Начальный порт правила - # Обязательный параметр - # int - public_port_start = 200 - - # Внутренний порт - # Обязательный параметр - # int - local_base_port = 22 - - # Протокол соединения (tcp / udp) - # Обязательный параметр - # string - proto = "tcp" - - # Конечный порт (включительно) - # Опциональный параметр - # int - public_port_end = 21321 -} - -output "pfw_out" { - value = decort_pfw.pfw -} diff --git a/samples/cloudapi/resource_vins_static_route/main.tf b/samples/cloudapi/resource_vins_static_route/main.tf deleted file mode 100644 index 9b1588a..0000000 --- a/samples/cloudapi/resource_vins_static_route/main.tf +++ /dev/null @@ -1,67 +0,0 @@ -/* -Пример использования -Ресурса vins static routes -Ресурс позволяет: -1. Создавать static routes -2. Удалять static routes -3. Получать информацию о всех static routes в данном Vins -4. Предоставлять доступ виртуальным машинам к static routes -5. Удалять доступ виртуальным машинам к static routes - -*/ - -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_vins_static_route" "sr" { - -#id Vins -#обязательный параметр -#тип - число -vins_id = 1111 - -# destination network -# обязательный параметр -#тип - строка -destination = "192.168.201.0" - -# destination network mask -#обязательный параметр -#тип - строка -netmask = "255.255.255.255" - -# IP-адрес из пула свободных IP-адресов ViNS ID -#обязательный параметр -#тип - строка -gateway = "192.168.201.40" - -# список виртуальных машин, которым будет предоставлен доступ к роуту -#опциональный параметр -#тип - массив чисел -compute_ids = [111,222] -} - -output "sr" { - value = decort_vins_static_route.sr -} - diff --git a/samples/cloudapi/data_rg/main.tf b/samples/cloudapi/rg/data_rg/main.tf similarity index 88% rename from samples/cloudapi/data_rg/main.tf rename to samples/cloudapi/rg/data_rg/main.tf index 721f801..a6951ff 100644 --- a/samples/cloudapi/data_rg/main.tf +++ b/samples/cloudapi/rg/data_rg/main.tf @@ -1,17 +1,17 @@ /* Пример использования -Получение информации о ресурсной группе RG +Получение информации о ресурсной группе (RG) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,9 +29,10 @@ provider "decort" { data "decort_resgroup" "rg" { #id ресурсной группы #обязательный параметр - #тип - число - rg_id = 1535 - #причина для выполняния действия + #тип - целое число + rg_id = 1535 + + #причина для выполнения действия #необязятельный параметр #тип - строка reason = "TEST" diff --git a/samples/cloudapi/data_rg_affinity_group_computes/main.tf b/samples/cloudapi/rg/data_rg_affinity_group_computes/main.tf similarity index 95% rename from samples/cloudapi/data_rg_affinity_group_computes/main.tf rename to samples/cloudapi/rg/data_rg_affinity_group_computes/main.tf index d81a5e5..6549bb9 100644 --- a/samples/cloudapi/data_rg_affinity_group_computes/main.tf +++ b/samples/cloudapi/rg/data_rg_affinity_group_computes/main.tf @@ -2,18 +2,20 @@ Пример использования Получение информации о специальной группе компьютов */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,8 +29,9 @@ provider "decort" { data "decort_rg_affinity_group_computes" "lc" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 + #название специальной группы компьютов #обязательное поле #тип - строка diff --git a/samples/cloudapi/data_rg_affinity_groups_get/main.tf b/samples/cloudapi/rg/data_rg_affinity_groups_get/main.tf similarity index 95% rename from samples/cloudapi/data_rg_affinity_groups_get/main.tf rename to samples/cloudapi/rg/data_rg_affinity_groups_get/main.tf index 8b0e7d0..3733b8e 100644 --- a/samples/cloudapi/data_rg_affinity_groups_get/main.tf +++ b/samples/cloudapi/rg/data_rg_affinity_groups_get/main.tf @@ -2,19 +2,20 @@ Пример использования Получение информации о списке компьютов из определенной группы */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ - +} +*/ provider "decort" { authenticator = "decs3o" @@ -28,8 +29,9 @@ provider "decort" { data "decort_rg_affinity_groups_get" "get_groups" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 + #название специальной группы компьютов #обязательное поле #тип - строка diff --git a/samples/cloudapi/data_rg_affinity_groups_list/main.tf b/samples/cloudapi/rg/data_rg_affinity_groups_list/main.tf similarity index 92% rename from samples/cloudapi/data_rg_affinity_groups_list/main.tf rename to samples/cloudapi/rg/data_rg_affinity_groups_list/main.tf index d192185..6b8e6a4 100644 --- a/samples/cloudapi/data_rg_affinity_groups_list/main.tf +++ b/samples/cloudapi/rg/data_rg_affinity_groups_list/main.tf @@ -2,18 +2,20 @@ Пример использования Получение информации о списке специальных групп компьютов */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,18 +29,18 @@ provider "decort" { data "decort_rg_affinity_groups_list" "list_groups" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/data_rg_audits/main.tf b/samples/cloudapi/rg/data_rg_audits/main.tf similarity index 94% rename from samples/cloudapi/data_rg_audits/main.tf rename to samples/cloudapi/rg/data_rg_audits/main.tf index 546fbd8..612bc19 100644 --- a/samples/cloudapi/data_rg_audits/main.tf +++ b/samples/cloudapi/rg/data_rg_audits/main.tf @@ -2,18 +2,20 @@ Пример использования Получение информации о списке аудитов ресурсной группы */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,7 +29,7 @@ provider "decort" { data "decort_rg_audits" "rg_audits" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 } diff --git a/samples/cloudapi/data_rg_get_resource_consumption/main.tf b/samples/cloudapi/rg/data_rg_get_resource_consumption/main.tf similarity index 93% rename from samples/cloudapi/data_rg_get_resource_consumption/main.tf rename to samples/cloudapi/rg/data_rg_get_resource_consumption/main.tf index 495a1ab..2544904 100644 --- a/samples/cloudapi/data_rg_get_resource_consumption/main.tf +++ b/samples/cloudapi/rg/data_rg_get_resource_consumption/main.tf @@ -1,4 +1,5 @@ /* +Пример использования Получение списка текущего потребления ресурсов ресурсной группы */ @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_rg_resource_consumption_get" "rc_get" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 111 } diff --git a/samples/cloudapi/data_rg_list/main.tf b/samples/cloudapi/rg/data_rg_list/main.tf similarity index 80% rename from samples/cloudapi/data_rg_list/main.tf rename to samples/cloudapi/rg/data_rg_list/main.tf index 9ee9504..4cb7035 100644 --- a/samples/cloudapi/data_rg_list/main.tf +++ b/samples/cloudapi/rg/data_rg_list/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение информации о списке всех ресурсных группах к которым есть доступ +Получение информации о списке всех ресурсных групп к которым есть доступ */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ @@ -27,7 +28,7 @@ provider "decort" { data "decort_rg_list" "rg_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени ресурсной группы @@ -37,7 +38,7 @@ data "decort_rg_list" "rg_list" { #id аккаунта для получения списка ресурсных групп #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по имени аккаунта @@ -47,12 +48,12 @@ data "decort_rg_list" "rg_list" { #фильтр по времени создания (после указанного времени) #опциональный параметр - #тип - число + #тип - целое число #created_after = "123" #фильтр по времени создания (перед указанным временем) #опциональный параметр - #тип - число + #тип - целое число #created_before = "123" #фильтр по статусу @@ -67,17 +68,23 @@ data "decort_rg_list" "rg_list" { #отображать удаленные ресурсные группы или нет #необязательный параметр - #тип - булевый + #тип - булев #includedeleted = false + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" #номер страницы #необязательный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #необязательный параметр - #тип - число + #тип - целое число #size = 2 } diff --git a/samples/cloudapi/data_rg_list_computes/main.tf b/samples/cloudapi/rg/data_rg_list_computes/main.tf similarity index 83% rename from samples/cloudapi/data_rg_list_computes/main.tf rename to samples/cloudapi/rg/data_rg_list_computes/main.tf index 6dd2d06..cc0cc8e 100644 --- a/samples/cloudapi/data_rg_list_computes/main.tf +++ b/samples/cloudapi/rg/data_rg_list_computes/main.tf @@ -2,18 +2,20 @@ Пример использования Получение информации о списке компьютов в ресурсной группе */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,12 +29,12 @@ provider "decort" { data "decort_rg_list_computes" "list_computes" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #фильтр по id compute #опциональный параметр - #тип - число + #тип - целое число #compute_id = 100 #фильтр по имени compute @@ -42,7 +44,7 @@ data "decort_rg_list_computes" "list_computes" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #account_id = 100 #фильтр по техническому статусу @@ -67,18 +69,24 @@ data "decort_rg_list_computes" "list_computes" { #фильтр по id внешней сети #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/data_rg_list_deleted/main.tf b/samples/cloudapi/rg/data_rg_list_deleted/main.tf similarity index 81% rename from samples/cloudapi/data_rg_list_deleted/main.tf rename to samples/cloudapi/rg/data_rg_list_deleted/main.tf index d118109..ec1998d 100644 --- a/samples/cloudapi/data_rg_list_deleted/main.tf +++ b/samples/cloudapi/rg/data_rg_list_deleted/main.tf @@ -2,18 +2,20 @@ Пример использования Получение информации о списке удаленных ресурсных групп */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,7 +29,7 @@ provider "decort" { data "decort_rg_list_deleted" "list_deleted" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени ресурсной группы @@ -37,7 +39,7 @@ data "decort_rg_list_deleted" "list_deleted" { #id аккаунта для получения списка ресурсных групп #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по имени аккаунта @@ -47,12 +49,12 @@ data "decort_rg_list_deleted" "list_deleted" { #фильтр по времени создания (после указанного времени) #опциональный параметр - #тип - число + #тип - целое число #created_after = "123" #фильтр по времени создания (перед указанным временем) #опциональный параметр - #тип - число + #тип - целое число #created_before = "123" #фильтр по lock status @@ -60,14 +62,20 @@ data "decort_rg_list_deleted" "list_deleted" { #тип - строка #lock_status = "UNLOCKED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы #необязательный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #необязательный параметр - #тип - число + #тип - целое число #size = 2 } diff --git a/samples/cloudapi/data_rg_list_lb/main.tf b/samples/cloudapi/rg/data_rg_list_lb/main.tf similarity index 84% rename from samples/cloudapi/data_rg_list_lb/main.tf rename to samples/cloudapi/rg/data_rg_list_lb/main.tf index 6b123ba..8b6e758 100644 --- a/samples/cloudapi/data_rg_list_lb/main.tf +++ b/samples/cloudapi/rg/data_rg_list_lb/main.tf @@ -5,15 +5,16 @@ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,12 +28,12 @@ provider "decort" { data "decort_rg_list_lb" "list_lb" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени балансировщика нагрузки @@ -40,11 +41,6 @@ data "decort_rg_list_lb" "list_lb" { #тип - строка #name = "test" - #id аккаунта для получения списка балансировщиков нагрузки - #опциональный параметр - #тип - число - #account_id = 11111 - #фильтр по техническому статусу #опциональный параметр #тип - строка @@ -65,15 +61,21 @@ data "decort_rg_list_lb" "list_lb" { #тип - строка #back_ip = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/data_rg_list_pfw/main.tf b/samples/cloudapi/rg/data_rg_list_pfw/main.tf similarity index 95% rename from samples/cloudapi/data_rg_list_pfw/main.tf rename to samples/cloudapi/rg/data_rg_list_pfw/main.tf index 03d81c0..5f83a68 100644 --- a/samples/cloudapi/data_rg_list_pfw/main.tf +++ b/samples/cloudapi/rg/data_rg_list_pfw/main.tf @@ -2,18 +2,20 @@ Пример использования Получение информации о списке правил переадресации портов для ресурсной группы. */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,7 +29,7 @@ provider "decort" { data "decort_rg_list_pfw" "list_pfw" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 } diff --git a/samples/cloudapi/rg/data_rg_list_vins/main.tf b/samples/cloudapi/rg/data_rg_list_vins/main.tf new file mode 100644 index 0000000..ddbeaa1 --- /dev/null +++ b/samples/cloudapi/rg/data_rg_list_vins/main.tf @@ -0,0 +1,76 @@ +/* +Пример использования +Получение информации о списке винсов в ресурсной группе +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* + terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_rg_list_vins" "list_vins" { + #id ресурсной группы + #обязательный параметр + #тип - целое число + rg_id = 123 + + #фильтр по id vins + #опциональный параметр + #тип - целое число + #vins_id = 100 + + #фильтр по имени vins + #опциональный параметр + #тип - строка + #name = "test" + + #id аккаунта для получения списка балансировщиков нагрузки + #опциональный параметр + #тип - целое число + #account_id = 11111 + + #фильтр по IP внешней сети + #опциональный параметр + #тип - строка + #ext_ip = "test" + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + + #номер страницы для отображения + #опциональный параметр + #тип - целое число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - целое число + #если не задан - выводятся все доступные данные + #size = 3 +} + +output "output" { + value = data.decort_rg_list_vins.list_vins +} diff --git a/samples/cloudapi/data_rg_resource_consumption_list/main.tf b/samples/cloudapi/rg/data_rg_resource_consumption_list/main.tf similarity index 91% rename from samples/cloudapi/data_rg_resource_consumption_list/main.tf rename to samples/cloudapi/rg/data_rg_resource_consumption_list/main.tf index a4e8b92..22f768e 100644 --- a/samples/cloudapi/data_rg_resource_consumption_list/main.tf +++ b/samples/cloudapi/rg/data_rg_resource_consumption_list/main.tf @@ -1,4 +1,5 @@ /* +Пример использования Получение списка текущего потребления ресурсов */ @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -25,7 +27,7 @@ provider "decort" { } data "decort_rg_resource_consumption_list" "rc_list" { - #Нет входных параметров + #нет входных параметров } output "test" { diff --git a/samples/cloudapi/data_rg_usage/main.tf b/samples/cloudapi/rg/data_rg_usage/main.tf similarity index 90% rename from samples/cloudapi/data_rg_usage/main.tf rename to samples/cloudapi/rg/data_rg_usage/main.tf index 858ad8c..5d6e4d3 100644 --- a/samples/cloudapi/data_rg_usage/main.tf +++ b/samples/cloudapi/rg/data_rg_usage/main.tf @@ -1,19 +1,21 @@ /* Пример использования -Получение информации об использовании ресурсов на ресурсной группе +Получение информации об использовании ресурсов в ресурсной группе */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { +/* + terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" + } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,7 +29,8 @@ provider "decort" { data "decort_rg_usage" "rg_usage" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число + rg_id = 123 #причина для действия #необязательный параметр diff --git a/samples/cloudapi/resource_rg/main.tf b/samples/cloudapi/rg/resource_rg/main.tf similarity index 70% rename from samples/cloudapi/resource_rg/main.tf rename to samples/cloudapi/rg/resource_rg/main.tf index 00a3d1d..0c39e3d 100644 --- a/samples/cloudapi/resource_rg/main.tf +++ b/samples/cloudapi/rg/resource_rg/main.tf @@ -2,10 +2,11 @@ Пример использования Ресурсов RG Ресурс позволяет: -1. Создавать -2. Редактировать -3. Удалять +1. Создавать RG +2. Редактировать RG +3. Удалять RG */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -13,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -37,139 +38,146 @@ resource "decort_resgroup" "rg" { #id аккаунта которому будет принадлежать ресурсная группа #обязательный параметр - #тип - число + #тип - целое число account_id = 123 #id сети #обязательный параметр - #тип - число + #тип - целое число gid = 1234 - #тип сети по умолчанию для этой ресурсной группы. - #виртуальные машины, созданные в этой RG, по умолчанию будут подключены к этой сети. - #Допустимые значения: PRIVATE, PUBLIC, NONE. - #необязательный параметр + #тип сети по умолчанию для этой ресурсной группы + #опциональный параметр + #виртуальные машины, созданные в этой RG, по умолчанию будут подключены к этой сети + #допустимые значения: PRIVATE, PUBLIC, NONE #тип - строка def_net_type = "NONE" #ip cidr частной сети, если сеть по умолчанию PRIVATE - #необязательный параметр + #опциональный параметр #тип - строка ipcidr = "1.1.1.1" #id внешней сети - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число ext_net_id = 123 #ip внешней сети - #необязательный параметр + #опциональный параметр #тип - строка ext_ip = "1.1.1.1" #причина выполнения - #необязательный параметр + #опциональный параметр #тип - строка reason = "TEST" #описание - #необязательный параметр + #опциональный параметр #тип - строка description = "qwerty" - + #флаг доступности ресурсной группы - #необязательный параметр - #тип - булевый + #опциональный параметр + #тип - булев enable = true #имя пользователя - #необязательный параметр + #опциональный параметр #тип - строка owner = "name_user" #блок для предоставления прав на ресурсную группу - #необязательный параметр - #тип - блок - access { + #опциональный параметр + #тип - блок прав доступа + access { #имя юзера предоставляемому права #обязательный праметр при использовании блока #тип - строка user = "kasim_baybikov_1@decs3o" + #тип прав - #необязательный параметр + #опциональный параметр #тип - строка right = "RCX" } - #Установить сеть по умолчанию - #необязательный параметр - #тип - блок + #установить сеть по умолчанию + #опциональный параметр #при добавлении блока, удалять его нельзя + #тип - блок сетей def_net { #тип сети #обязательный параметр при использовании блока #тип - строка net_type = "PUBLIC" + #id сети + #опциональный параметр #идентификатор сегмента сети. Если net_type — PUBLIC, а net_id — 0, #то будет выбран сегмент внешней сети по умолчанию. Если net_type - #имеет значение PRIVATE и net_id=0, будет выбран первый vins, определенный для этой ресурсной группы. - #В противном случае net_id идентифицирует либо существующий сегмент внешней сети, либо vins. - #необязательный параметр - #тип - число + #имеет значение PRIVATE и net_id=0, будет выбран первый vins, определенный для этой ресурсной группы + #в противном случае net_id идентифицирует либо существующий сегмент внешней сети, либо vins + #тип - целое число net_id = 1234 + #причина выполнения - #необязательный параметр + #опциональный параметр #тип - строка reason = "TEST" } - + #лимиты ресурсов для ресурсной группы - #необязательный параметр - #тип - блок + #опциональный параметр + #тип - блок конфигураций quota { #максимальное количество ядер процессора - #необязательный параметр - #тип - число + #опциональный параметр #значение по умолчанию: -1 + #тип - целое число cpu = 5 + #максимальный размер памяти в мегабайтах - #необязательный параметр - #тип - число + #опциональный параметр #значение по умолчанию: -1 + #тип - целое число ram = 1024 + #максимальный размер объединенных виртуальных дисков в ГБ - #необязательный параметр - #тип - число + #опциональный параметр #значение по умолчанию: -1 + #тип - целое число disk = 180 + #максимальное количество отправленных/полученных сетевых узлов - #необязательный параметр - #тип - число + #опциональный параметр #значение по умолчанию: -1 + #тип - целое число ext_traffic = 21 + #максимальное количество назначенных общедоступных IP-адресов - #необязательный параметр - #тип - число + #опциональный параметр #значение по умолчанию: -1 + #тип - целое число ext_ips = 29 - } + } #флаг для принудительного удаления ресурсной группы - #необязательный параметр - #тип - булевый + #опциональный параметр + #тип - булев force = true #флаг для моментального удаления ресурсной группы - #необязательный параметр - #тип - булевый + #опциональный параметр + #тип - булев permanently = true #восстановление группы после удаления - #необязательный параметр - #тип - булев тип + #опциональный параметр #используется при редактировании ресурса #по-умолачанию - false + #тип - булев restore = true } diff --git a/samples/cloudapi/data_snapshot_list/main.tf b/samples/cloudapi/snapshot/data_snapshot_list/main.tf similarity index 93% rename from samples/cloudapi/data_snapshot_list/main.tf rename to samples/cloudapi/snapshot/data_snapshot_list/main.tf index f160291..a50181e 100644 --- a/samples/cloudapi/data_snapshot_list/main.tf +++ b/samples/cloudapi/snapshot/data_snapshot_list/main.tf @@ -1,7 +1,6 @@ /* Пример использования Получение списка snapshot - */ #Расскомментируйте этот код, @@ -11,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -31,7 +30,7 @@ provider "decort" { data "decort_snapshot_list" "sl" { #обязательный параметр #id вычислительной мощности - #тип - число + #тип - целое число compute_id = 24074 } diff --git a/samples/cloudapi/resource_snapshot/main.tf b/samples/cloudapi/snapshot/resource_snapshot/main.tf similarity index 90% rename from samples/cloudapi/resource_snapshot/main.tf rename to samples/cloudapi/snapshot/resource_snapshot/main.tf index a410b7c..fe2fbc3 100644 --- a/samples/cloudapi/resource_snapshot/main.tf +++ b/samples/cloudapi/snapshot/resource_snapshot/main.tf @@ -1,11 +1,10 @@ /* Пример использования -Ресурса snapshot +Управление snapshot Ресурс позволяет: 1. Создавать snapshot 2. Удалять snapshot 3. Откатывать snapshot - */ #Расскомментируйте этот код, @@ -15,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -31,11 +30,10 @@ provider "decort" { allow_unverified_ssl = true } - resource "decort_snapshot" "s" { #обязательный параметр #id вычислительной мощности - #тип - число + #тип - целое число compute_id = 24074 #обязательный параметр @@ -43,12 +41,13 @@ resource "decort_snapshot" "s" { #тип - строка label = "test_ssht_3" - #опциональный параметр #флаг отката - #тип - булев тип - #по-уолчанию - false + #опциональный параметр #если флаг был измеен с false на true, то произойдет откат + #по-уолчанию - false + #тип - булев #rollback = false + } output "test" { diff --git a/samples/cloudapi/data_stack/main.tf b/samples/cloudapi/stack/data_stack/main.tf similarity index 86% rename from samples/cloudapi/data_stack/main.tf rename to samples/cloudapi/stack/data_stack/main.tf index 185733d..4bd56be 100644 --- a/samples/cloudapi/data_stack/main.tf +++ b/samples/cloudapi/stack/data_stack/main.tf @@ -1,4 +1,5 @@ /* +Пример использования Получение stack по его id */ @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "4.4.0" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -26,7 +28,7 @@ provider "decort" { data "decort_stack" "stack" { #обязательный параметр - #тип - число + #тип - целое число #идентификатор стека stack_id = 2 } @@ -34,4 +36,3 @@ data "decort_stack" "stack" { output "test" { value = data.decort_stack.stack } - diff --git a/samples/cloudapi/data_stack_list/main.tf b/samples/cloudapi/stack/data_stack_list/main.tf similarity index 79% rename from samples/cloudapi/data_stack_list/main.tf rename to samples/cloudapi/stack/data_stack_list/main.tf index a3de1aa..32347e5 100644 --- a/samples/cloudapi/data_stack_list/main.tf +++ b/samples/cloudapi/stack/data_stack_list/main.tf @@ -1,4 +1,5 @@ /* +Пример использования Получение списка stack */ @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "4.4.0" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -25,9 +27,9 @@ provider "decort" { } data "decort_stack_list" "stack_list" { #необязательный параметр - #тип - число + #тип - целое число #фильтрация списка для получения информации о конкретном stack по его id - #by_id = + #by_id = 2 #необязательный параметр #тип - строка @@ -44,15 +46,21 @@ data "decort_stack_list" "stack_list" { #фильтрация списка для получения информации о конкретном stack по его статусу #status = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 3 } diff --git a/samples/cloudapi/vfpool/data_vfpool/main.tf b/samples/cloudapi/vfpool/data_vfpool/main.tf new file mode 100644 index 0000000..c9b1560 --- /dev/null +++ b/samples/cloudapi/vfpool/data_vfpool/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информации о vfpool по его id +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_vfpool" "vfpool" { + #обязательный параметр + #тип - целое число + #идентификатор vfpool + vfpool_id = 2 +} + +output "test" { + value = data.decort_vfpool.vfpool +} + diff --git a/samples/cloudapi/vfpool/data_vfpool_list/main.tf b/samples/cloudapi/vfpool/data_vfpool_list/main.tf new file mode 100644 index 0000000..3f18e1f --- /dev/null +++ b/samples/cloudapi/vfpool/data_vfpool_list/main.tf @@ -0,0 +1,87 @@ +/* +Пример использования +Получение списка vfpool +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_vfpool_list" "vfpool_list" { + #фильтрация списка для получения информации о конкретном vfpool по его id + #необязательный параметр + #тип - целое число + #by_id = 1 + + #фильтрация списка для получения информации о vfpool, которые принадлежат к определенному GRID + #необязательный параметр + #тип - целое число + #gid = 1 + + #фильтрация списка для получения информации о конкретном vfpool по его имени + #необязательный параметр + #тип - строка + #name = "alpha-cpu-04" + + #фильтрация списка для получения информации о конкретном vfpool по его описанию + #необязательный параметр + #тип - строка + #description = "some" + + #фильтрация списка для получения информации о vfpool, которые имеют соответствующий статус + #необязательный параметр + #тип - строка + #status = "ENABLED" + + #фильтрация списка для получения информации о vfpool, которые доступны конкретному аккаунту + #необязательный параметр + #тип - целое число + #account_access = 1 + + #фильтрация списка для получения информации о vfpool, которые доступны конкретной ресурсной группе + #необязательный параметр + #тип - целое число + #rg_access = 1 + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + + #номер страницы для отображения + #опциональный параметр + #тип - целое число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - целое число + #если не задан - выводятся все доступные данные + #size = 3 +} + +output "test" { + value = data.decort_vfpool_list.vfpool_list +} + diff --git a/samples/cloudapi/data_vgpu/main.tf b/samples/cloudapi/vgpu/data_vgpu/main.tf similarity index 92% rename from samples/cloudapi/data_vgpu/main.tf rename to samples/cloudapi/vgpu/data_vgpu/main.tf index 8c2530b..90c155f 100644 --- a/samples/cloudapi/data_vgpu/main.tf +++ b/samples/cloudapi/vgpu/data_vgpu/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных vgpu */ + #Расскомментируйте код ниже, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_vgpu" "vgpu" { #id vgpu #обязательный параметр - #тип - число + #тип - целое число vgpu_id = 1111 } diff --git a/samples/cloudapi/vins/data_vins/main.tf b/samples/cloudapi/vins/data_vins/main.tf new file mode 100644 index 0000000..eb91c52 --- /dev/null +++ b/samples/cloudapi/vins/data_vins/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение информации об уже существующем виртуальном сетевом сегменте (Virtual Network Segment, ViNS). +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_vins" "vins" { + #обязательный параметр + #id желаемого vins + #тип - целое число + vins_id = 10101 + +} + +output "test" { + value = data.decort_vins.vins +} diff --git a/samples/cloudapi/data_vins_audits/main.tf b/samples/cloudapi/vins/data_vins_audits/main.tf similarity index 84% rename from samples/cloudapi/data_vins_audits/main.tf rename to samples/cloudapi/vins/data_vins_audits/main.tf index 5e510fc..4c96eff 100644 --- a/samples/cloudapi/data_vins_audits/main.tf +++ b/samples/cloudapi/vins/data_vins_audits/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение списка vins audits +Получение списка записей аудита для внутренней сети vins. */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,8 +28,8 @@ provider "decort" { data "decort_vins_audits" "vins_audits" { #обязательный параметр - #id жедаемого vins - #тип - число + #id желаемого vins + #тип - целое число vins_id = 10101 } diff --git a/samples/cloudapi/data_vins_ext_net_list/main.tf b/samples/cloudapi/vins/data_vins_ext_net_list/main.tf similarity index 84% rename from samples/cloudapi/data_vins_ext_net_list/main.tf rename to samples/cloudapi/vins/data_vins_ext_net_list/main.tf index 2abac95..5ed476d 100644 --- a/samples/cloudapi/data_vins_ext_net_list/main.tf +++ b/samples/cloudapi/vins/data_vins_ext_net_list/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение списка vins extnet +Получение информации о внешних сетях виртуальной сети (Vins). */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,8 +28,8 @@ provider "decort" { data "decort_vins_ext_net_list" "vins_ext_net_list" { #обязательный параметр - #id жедаемого vins - #тип - число + #id желаемого vins + #тип - целое число vins_id = 10101 } diff --git a/samples/cloudapi/data_vins_ip_list/main.tf b/samples/cloudapi/vins/data_vins_ip_list/main.tf similarity index 81% rename from samples/cloudapi/data_vins_ip_list/main.tf rename to samples/cloudapi/vins/data_vins_ip_list/main.tf index 81d8e65..2c01628 100644 --- a/samples/cloudapi/data_vins_ip_list/main.tf +++ b/samples/cloudapi/vins/data_vins_ip_list/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение списка vins_ip +Получение информации о списке зарезервированных IP адресов виртуальной сети (Vins) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,8 +28,8 @@ provider "decort" { data "decort_vins_ip_list" "vins_ip_list" { #обязательный параметр - #id жедаемого vins - #тип - число + #id желаемого vins + #тип - целое число vins_id = 10101 } diff --git a/samples/cloudapi/data_vins_list/main.tf b/samples/cloudapi/vins/data_vins_list/main.tf similarity index 76% rename from samples/cloudapi/data_vins_list/main.tf rename to samples/cloudapi/vins/data_vins_list/main.tf index 166cd6d..c27d721 100644 --- a/samples/cloudapi/data_vins_list/main.tf +++ b/samples/cloudapi/vins/data_vins_list/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение списка vins +Получение списка удаленных виртуальных сетей (Vins). */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_vins_list" "vl" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени vins @@ -38,12 +39,12 @@ data "decort_vins_list" "vl" { #id аккаунта для получения списка балансировщиков нагрузки #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по IP внешней сети @@ -53,19 +54,25 @@ data "decort_vins_list" "vl" { #включение удаленных vins в результат #опциональный параметр - #тип - будев тип + #тип - булев #если не задан - выводятся все неудаленные данные #include_deleted = true + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 diff --git a/samples/cloudapi/data_vins_list_deleted/main.tf b/samples/cloudapi/vins/data_vins_list_deleted/main.tf similarity index 72% rename from samples/cloudapi/data_vins_list_deleted/main.tf rename to samples/cloudapi/vins/data_vins_list_deleted/main.tf index 583b7e4..67906b3 100644 --- a/samples/cloudapi/data_vins_list_deleted/main.tf +++ b/samples/cloudapi/vins/data_vins_list_deleted/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка удаленных vins */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_vins_list_deleted" "vins_list_deleted" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени vins @@ -38,12 +39,12 @@ data "decort_vins_list_deleted" "vins_list_deleted" { #id аккаунта для получения списка балансировщиков нагрузки #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по IP внешней сети @@ -51,17 +52,28 @@ data "decort_vins_list_deleted" "vins_list_deleted" { #тип - строка #ext_ip = "test" + #фильтр по id vnfDevices + #опциональный параметр + #тип - целое число + #vnfdev_id = 11111 + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода #опицональный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #опицональный параметр - #тип - число + #тип - целое число #size = 1 } output "test" { - value = data.decort_vins_list_deleted.vinslist_deleted + value = data.decort_vins_list_deleted.vins_list_deleted } diff --git a/samples/cloudapi/data_vins_nat_rule_list/main.tf b/samples/cloudapi/vins/data_vins_nat_rule_list/main.tf similarity index 93% rename from samples/cloudapi/data_vins_nat_rule_list/main.tf rename to samples/cloudapi/vins/data_vins_nat_rule_list/main.tf index e86aefc..d0568cf 100644 --- a/samples/cloudapi/data_vins_nat_rule_list/main.tf +++ b/samples/cloudapi/vins/data_vins_nat_rule_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка natRule vins */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,8 +28,8 @@ provider "decort" { data "decort_vins_nat_rule_list" "vins_nat_rule_list" { #обязательный параметр - #id жедаемого vins - #тип - число + #id желаемого vins + #тип - целое число vins_id = 10101 } diff --git a/samples/cloudapi/vins/data_vins_static_route/main.tf b/samples/cloudapi/vins/data_vins_static_route/main.tf new file mode 100644 index 0000000..e8a5b45 --- /dev/null +++ b/samples/cloudapi/vins/data_vins_static_route/main.tf @@ -0,0 +1,43 @@ +/* +Пример использования +Получение информации о статическом пути +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_vins_static_route" "route" { + #обязательный параметр + #id vins в котором добавлены routes + #тип - целое число + vins_id = 1111 + + #обязательный параметр + #id route + #тип - целое число + route_id = 1 +} + +output "route" { + value = data.decort_vins_static_route.route +} diff --git a/samples/cloudapi/vins/data_vins_static_route_list/main.tf b/samples/cloudapi/vins/data_vins_static_route_list/main.tf new file mode 100644 index 0000000..da504b6 --- /dev/null +++ b/samples/cloudapi/vins/data_vins_static_route_list/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информации о списке статических путей +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_vins_static_route_list" "list" { + #обязательный параметр + #id vins в котором добавлены routes + #тип - целое число + vins_id = 1111 +} + +output "list" { + value = data.decort_vins_static_route_list.list +} diff --git a/samples/cloudapi/resource_vins/main.tf b/samples/cloudapi/vins/resource_vins/main.tf similarity index 73% rename from samples/cloudapi/resource_vins/main.tf rename to samples/cloudapi/vins/resource_vins/main.tf index d1cc025..dccfd42 100644 --- a/samples/cloudapi/resource_vins/main.tf +++ b/samples/cloudapi/vins/resource_vins/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Ресурса vins +Управление vins Ресурс позволяет: 1. Создавать vins 2. Удалять vins @@ -9,7 +9,6 @@ 5. Резервировать и освобождать ip для vins 6. Добавлять и удалять natrule 7. Перезапускать и редеплоить vnfdev - */ #Расскомментируйте этот код, @@ -19,8 +18,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -37,132 +36,140 @@ provider "decort" { resource "decort_vins" "vins" { - #обязательный параметр #имя создаваемого ресурса + #обязательный параметр #тип - строка name = "Test_name" + #id ресурсной группы для создаения ресурса #опциональный параметр - #id ресурсной группы для создаения ресруса - #тип - число + #тип - целое число rg_id = 10101 - #опциональный параметр #id аккаунта для создаения ресруса - #тип - число + #опциональный параметр + #тип - целое число account_id = 2023 + #id внешней сети для подключения к ней ресурса #опциональный параметр - #id внешней сети для подключения к ней ресруса - #тип - число - ext_net_id = 2222 + #тип - целое число + ext_net_id = 2222 + #ip внешней сети для подключения к нему ресурса #опциональный параметр - #ip внешней сети для подключения к нему ресруса #тип - строка ext_ip_addr = "1.1.1.1" - - #опциональный параметр #private network IP CIDR + #опциональный параметр #тип - строка - ipcidr = "192.168.0.1" + ipcidr = "192.168.0.1" - #опциональный параметр #количество зарезервированных адресов на момент создания - #тип - число + #опциональный параметр #значение по умолчанию 32 + #тип - целое число pre_reservations_num = 2 - #опциональный параметр #grid (platform) ID - #тип - число - gid = 2002 + #опциональный параметр + #тип - целое число + gid = 2002 + #описание #опциональный параметр - #Description #тип - строка desc = "Description" - #опциональный параметр #ручное подключение и отключение ресурса - #тип - булев тип - enable = true - #опциональный параметр - #удаление навсегда - #тип - булев тип - permanently = true + #тип - булев + enable = true + #удаление навсегда #опциональный параметр - #удаляет за собой все зависимые ресурсы - #тип - булев тип - force = true + #тип - булев + permanently = true + #удаляет за собой все зависимые ресурсы #опциональный параметр + #тип - булев + force = true + #блок для резервирования ip - #тип - блок + #опциональный параметр + #тип - блок ip ip { - #обязательный параметр #тип подключения + #обязательный параметр #тип - строка - type = "DHCP" + type = "DHCP" - #опциональный параметр #ip который необходимо зарезервировать + #опциональный параметр #тип - строка - ip_addr = "192.168.5.5" + ip_addr = "192.168.5.5" - #опциональный параметр #mac который необходимо зарезервировать + #опциональный параметр #тип - строка mac_addr = "ff:ff:ff:ff:ff:ff" } - #опциональный параметр #блок для добавления natRule - #тип - блок + #опциональный параметр + #тип - блок правил nat nat_rule { - #опциональный параметр #ip внутренний + #опциональный параметр #тип - строка - int_ip = "192.168.0.28" + int_ip = "192.168.0.28" - #опциональный параметр #внутренний порт - #тип - число - int_port = 80 - #опциональный параметр + #тип - целое число + int_port = 80 + #начало диапазона внешних портов - #тип - число + #опциональный параметр + #тип - целое число ext_port_start = 8001 - #опциональный параметр #конец диапазона внешних портов - #тип - число - ext_port_end = 8001 - #опциональный параметр + #тип - целое число + ext_port_end = 8001 + #протокол natRule + #опциональный параметр #тип - строка - proto = "tcp" + proto = "tcp" } - #опциональный параметр #восстановление ресурса - #тип - булев тип - restore = true - #опциональный параметр - #перезапуск vnfDev - ##тип - булев тип - vnfdev_restart = true + #тип - булев + restore = true + #перезапуск vnfDev #опциональный параметр + #тип - булев + vnfdev_restart = true + #редеплой vnfDev - #тип - булев тип + #опциональный параметр + #тип - булев vnfdev_redeploy = true + + #список dns + #опциональный параметр + #применяется при создании и редактировании ресурса + #если при создании указать пустой список, то ресурс создается с полем vnfs.dhcp.config.dns, имеющим значение по умолчанию + #если при обновлении указать пустой список, то ресурс обновит в модели поле vnfs.dhcp.config.dns с текущего значения на пустой список + #тип - список строк + #dns = ["1.1.1.1", "2.2.2.2"] + } output "test" { diff --git a/samples/cloudapi/data_vins_static_route/main.tf b/samples/cloudapi/vins/resource_vins_static_route/main.tf similarity index 60% rename from samples/cloudapi/data_vins_static_route/main.tf rename to samples/cloudapi/vins/resource_vins_static_route/main.tf index db99f36..c431d1f 100644 --- a/samples/cloudapi/data_vins_static_route/main.tf +++ b/samples/cloudapi/vins/resource_vins_static_route/main.tf @@ -1,13 +1,12 @@ /* Пример использования -Ресурса vins static routes +Работа с vins static routes Ресурс позволяет: 1. Создавать static routes 2. Удалять static routes 3. Получать информацию о всех static routes в данном Vins 4. Предоставлять доступ виртуальным машинам к static routes 5. Удалять доступ виртуальным машинам к static routes - */ #Расскомментируйте этот код, @@ -17,8 +16,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,18 +32,35 @@ provider "decort" { allow_unverified_ssl = true } -data "decort_vins_static_route" "route" { +resource "decort_vins_static_route" "sr" { + #id Vins #обязательный параметр - #id vins в котором добавлены routes - #тип - число + #тип - целое число vins_id = 1111 + #destination network + #обязательный параметр + #тип - строка + destination = "192.168.201.0" + + #destination network mask #обязательный параметр - #id route - #тип - число - route_id = 1 + #тип - строка + netmask = "255.255.255.255" + + #ip-адрес из пула свободных IP-адресов ViNS ID + #обязательный параметр + #тип - строка + gateway = "192.168.201.40" + + #список виртуальных машин, которым будет предоставлен доступ к роуту + #опциональный параметр + #тип - массив целых чисел + compute_ids = [111, 222] + } -output "route" { - value = data.decort_vins_static_route.route +output "sr" { + value = decort_vins_static_route.sr } + diff --git a/samples/cloudbroker/data_account/main.tf b/samples/cloudbroker/account/data_account/main.tf similarity index 96% rename from samples/cloudbroker/data_account/main.tf rename to samples/cloudbroker/account/data_account/main.tf index ab83117..ebdf6ef 100644 --- a/samples/cloudbroker/data_account/main.tf +++ b/samples/cloudbroker/account/data_account/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации об аккаунте - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_account" "acc" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 } diff --git a/samples/cloudbroker/data_account_audits_list/main.tf b/samples/cloudbroker/account/data_account_audits_list/main.tf similarity index 96% rename from samples/cloudbroker/data_account_audits_list/main.tf rename to samples/cloudbroker/account/data_account_audits_list/main.tf index 0b6997f..a92dc34 100644 --- a/samples/cloudbroker/data_account_audits_list/main.tf +++ b/samples/cloudbroker/account/data_account_audits_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации об использовании аккаунта - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -30,7 +29,7 @@ provider "decort" { data "decort_cb_account_audits_list" "aal" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 } diff --git a/samples/cloudbroker/account/data_account_available_templates/main.tf b/samples/cloudbroker/account/data_account_available_templates/main.tf new file mode 100644 index 0000000..80d4cfe --- /dev/null +++ b/samples/cloudbroker/account/data_account_available_templates/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение информации о доступных образах, которые использует аккаунт +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_account_available_templates_list" "atl" { + #id аккаунта + #обязательный параметр + #тип - целое число + account_id = 11111 + +} + +output "test" { + value = data.decort_cb_account_available_templates_list.atl +} diff --git a/samples/cloudbroker/data_account_computes_list/main.tf b/samples/cloudbroker/account/data_account_computes_list/main.tf similarity index 83% rename from samples/cloudbroker/data_account_computes_list/main.tf rename to samples/cloudbroker/account/data_account_computes_list/main.tf index 21fe102..5c79928 100644 --- a/samples/cloudbroker/data_account_computes_list/main.tf +++ b/samples/cloudbroker/account/data_account_computes_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка computes, используемых аккаунтом - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_cb_account_computes_list" "acl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 1111 #фильтр по id compute #опциональный параметр - #тип - число + #тип - целое число #compute_id = 100 #фильтр по имени compute @@ -49,7 +49,7 @@ data "decort_cb_account_computes_list" "acl" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -69,20 +69,27 @@ data "decort_cb_account_computes_list" "acl" { #фильтр по id внешней сети #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 1 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 1 + } output "test" { diff --git a/samples/cloudbroker/data_account_disks_list/main.tf b/samples/cloudbroker/account/data_account_disks_list/main.tf similarity index 80% rename from samples/cloudbroker/data_account_disks_list/main.tf rename to samples/cloudbroker/account/data_account_disks_list/main.tf index 5b60f7c..ee98198 100644 --- a/samples/cloudbroker/data_account_disks_list/main.tf +++ b/samples/cloudbroker/account/data_account_disks_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о дисках, которые использует аккаунт - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_cb_account_disks_list" "adl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 11111 #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #disk_id = 100 #фильтр по имени диска @@ -44,7 +44,7 @@ data "decort_cb_account_disks_list" "adl" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 100 #тип диска @@ -53,15 +53,22 @@ data "decort_cb_account_disks_list" "adl" { #возможные типы: "b" - boot_disk, "d" - data_disk #type = "d" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #кол-во страниц для вывода #опицональный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #опицональный параметр - #тип - число + #тип - целое число #size = 1 + } output "test" { diff --git a/samples/cloudbroker/data_account_flipgroups_list/main.tf b/samples/cloudbroker/account/data_account_flipgroups_list/main.tf similarity index 79% rename from samples/cloudbroker/data_account_flipgroups_list/main.tf rename to samples/cloudbroker/account/data_account_flipgroups_list/main.tf index 89dae3d..adc6534 100644 --- a/samples/cloudbroker/data_account_flipgroups_list/main.tf +++ b/samples/cloudbroker/account/data_account_flipgroups_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о flipgroups, используемых аккаунтом - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,9 +27,9 @@ provider "decort" { } data "decort_cb_account_flipgroups_list" "afgl" { - #id аккаунта + #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 1111 #фильтр по имени flipgroup @@ -39,7 +39,7 @@ data "decort_cb_account_flipgroups_list" "afgl" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #vins_id = 100 #фильтр по имени vins @@ -49,7 +49,7 @@ data "decort_cb_account_flipgroups_list" "afgl" { #фильтр по id extnet #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 #фильтр по IP @@ -59,17 +59,23 @@ data "decort_cb_account_flipgroups_list" "afgl" { #фильтр по id flipgroup #опциональный параметр - #тип - число + #тип - целое число #flipgroup_id = 100 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #кол-во страниц для вывода #опицональный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #опицональный параметр - #тип - число + #тип - целое число #size = 1 } diff --git a/samples/cloudbroker/data_account_get_resource_consumption/main.tf b/samples/cloudbroker/account/data_account_get_resource_consumption/main.tf similarity index 93% rename from samples/cloudbroker/data_account_get_resource_consumption/main.tf rename to samples/cloudbroker/account/data_account_get_resource_consumption/main.tf index b46ecbc..68d8ec6 100644 --- a/samples/cloudbroker/data_account_get_resource_consumption/main.tf +++ b/samples/cloudbroker/account/data_account_get_resource_consumption/main.tf @@ -1,4 +1,5 @@ /* +Пример использования Получение списка текущего потребления ресурсов аккаунта */ @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,11 +29,11 @@ provider "decort" { data "decort_cb_account_resource_consumption_get" "rc_get" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 111 + } output "test" { value = data.decort_cb_account_resource_consumption_get.rc_get } - diff --git a/samples/cloudbroker/data_account_list/main.tf b/samples/cloudbroker/account/data_account_list/main.tf similarity index 79% rename from samples/cloudbroker/data_account_list/main.tf rename to samples/cloudbroker/account/data_account_list/main.tf index 88ee113..5a70a6a 100644 --- a/samples/cloudbroker/data_account_list/main.tf +++ b/samples/cloudbroker/account/data_account_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение всех аккаунтов,имеющихся в системе */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_account_list" "al" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени аккаунта @@ -46,17 +47,24 @@ data "decort_cb_account_list" "al" { #тип - строка #status = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/data_account_list_deleted/main.tf b/samples/cloudbroker/account/data_account_list_deleted/main.tf similarity index 82% rename from samples/cloudbroker/data_account_list_deleted/main.tf rename to samples/cloudbroker/account/data_account_list_deleted/main.tf index ba78cdd..2b40a3c 100644 --- a/samples/cloudbroker/data_account_list_deleted/main.tf +++ b/samples/cloudbroker/account/data_account_list_deleted/main.tf @@ -3,6 +3,7 @@ Получение информации об удаленных аккаунтах Информация предоставляется только по аккаунтам, удаленным без флага permanently */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +11,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,21 +28,27 @@ provider "decort" { } data "decort_cb_account_list_deleted" "adl" { + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени аккаунта @@ -53,7 +60,7 @@ data "decort_cb_account_list_deleted" "adl" { #опциональный параметр #тип - строка #acl = "test" - + } output "test" { diff --git a/samples/cloudbroker/data_account_resource_consumption_list/main.tf b/samples/cloudbroker/account/data_account_resource_consumption_list/main.tf similarity index 95% rename from samples/cloudbroker/data_account_resource_consumption_list/main.tf rename to samples/cloudbroker/account/data_account_resource_consumption_list/main.tf index 7bb8e8f..b156ac6 100644 --- a/samples/cloudbroker/data_account_resource_consumption_list/main.tf +++ b/samples/cloudbroker/account/data_account_resource_consumption_list/main.tf @@ -1,4 +1,5 @@ /* +Пример использования Получение списка текущего потребления ресурсов */ @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = diff --git a/samples/cloudbroker/data_account_rg_list/main.tf b/samples/cloudbroker/account/data_account_rg_list/main.tf similarity index 79% rename from samples/cloudbroker/data_account_rg_list/main.tf rename to samples/cloudbroker/account/data_account_rg_list/main.tf index 5544b0c..50794d0 100644 --- a/samples/cloudbroker/data_account_rg_list/main.tf +++ b/samples/cloudbroker/account/data_account_rg_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о ресурных группах, используемых аккаунтом */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,26 +27,32 @@ provider "decort" { } data "decort_cb_account_rg_list" "argl" { - #id аккаунта + #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 66666 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 11111 #фильтр по имени ресурсной группы @@ -55,18 +62,19 @@ data "decort_cb_account_rg_list" "argl" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #vins_id = 100 #фильтр по id compute #опциональный параметр - #тип - число + #тип - целое число #vm_id = 100 #фильтр по статусу #опциональный параметр #тип - строка #status = "CREATED" + } output "test" { diff --git a/samples/cloudbroker/data_account_vins_list/main.tf b/samples/cloudbroker/account/data_account_vins_list/main.tf similarity index 79% rename from samples/cloudbroker/data_account_vins_list/main.tf rename to samples/cloudbroker/account/data_account_vins_list/main.tf index 6cc6103..23526cb 100644 --- a/samples/cloudbroker/data_account_vins_list/main.tf +++ b/samples/cloudbroker/account/data_account_vins_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка vins, используемых аккаунтом - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,14 +27,14 @@ provider "decort" { } data "decort_cb_account_vins_list" "avl" { - #id аккаунта + #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 22222 #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #vins_id = 100 #фильтр по имени vins @@ -44,7 +44,7 @@ data "decort_cb_account_vins_list" "avl" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 11111 #фильтр по IP внешней сети @@ -52,19 +52,24 @@ data "decort_cb_account_vins_list" "avl" { #тип - строка #ext_ip = "test" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 - } output "test" { diff --git a/samples/cloudbroker/resource_account/main.tf b/samples/cloudbroker/account/resource_account/main.tf similarity index 68% rename from samples/cloudbroker/resource_account/main.tf rename to samples/cloudbroker/account/resource_account/main.tf index c80f7cf..b04b064 100644 --- a/samples/cloudbroker/resource_account/main.tf +++ b/samples/cloudbroker/account/resource_account/main.tf @@ -5,8 +5,8 @@ 1. Создавать аккаунт 2. Редактировать аккаунт 3. Удалять аккаунт - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -43,75 +43,75 @@ resource "decort_cb_account" "acc" { username = "username@decs3o" #доступность аккаунта - #необязательный параметр - #тип - булев тип + #опциональный параметр + #тип - булев #может применяться при создании аккаунта и редактировании аккаунта enable = true #электронная почта, на которую будет отправлена информация о доступе - #необязательный параметр + #опциональный параметр #тип - строка #применяется при создании аккаунта emailaddress = "fff@fff.ff" #отправлять ли на электронную почту письмо о доступе - #необязательный параметр - #тип - булев тип + #опциональный параметр + #тип - булев #применяется при создании аккаунта и редактировании аккаунта send_access_emails = true #пары sep_id и sep_pool_name - #необязательный параметр - #тип - список строк + #опциональный параметр + #тип - массив строк #применяется при создании аккаунта и редактировании аккаунта #каждая строка представляет собой пару, sepID_sepPoolName uniq_pools = ["sep1_poolName1", "sep2_poolName2"] #ограничение используемых ресурсов - #необязательный параметр - #тип - объект + #опциональный параметр + #тип - блок #используется при создании и редактировании resource_limits { #кол-во используемых ядер cpu - #необязательный параметр - #тип - число - #если установлена -1 - кол-во неограничено - cu_c = 2 + #опциональный параметр + #тип - целое число + #если установлена -1 - кол-во неограниченно + #cu_c = 2 #кол-во используемой RAM в МБ - #необязательный параметр - #тип - число - #если установлена -1 - кол-во неограничено - cu_m = 1024 + #опциональный параметр + #тип - целое число + #если установлена -1 - кол-во неограниченно + #cu_m = 1024 #размер дисков, в ГБ - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число #если установлена -1 - размер неограничен - cu_dm = 23 + #cu_dm = 23 #кол-во используемых публичных IP - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число #если установлена -1 - кол-во неограничено - cu_i = 2 + #cu_i = 2 #ограничения на кол-во передачи данных, в ГБ - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число #если установлена -1 - кол-во неограничено - cu_np = 2 + #cu_np = 2 #кол-во графических процессоров - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число #если установлена -1 - кол-во неограничено - gpu_units = 2 + #gpu_units = 2 } - #добавление/редактирование/удаление пользователей, к которым привязан аккаунт - #необязательный параметр - #тип - объект, кол-во таких объектов не ограничено + #добавление/редактирование/удаление пользователей, к которым привязан аккаунт + #опциональный параметр + #тип - блок, кол-во таких блоков не ограничено /*users { #id пользователя #обязательный параметр @@ -128,8 +128,8 @@ resource "decort_cb_account" "acc" { access_type = "R" #рекурсивное удаление пользователя из всех ресурсов аккаунтов - #необязательный параметр - #тип - булев тип + #опциональный параметр + #тип - булев #по-умолчанию - false #применяется при удалении пользователя из аккаунта recursive_delete = true @@ -137,29 +137,40 @@ resource "decort_cb_account" "acc" { */ #параметр распределения CPU - #необязательный параметр + #опциональный параметр #тип - строка #если "strict" виртуальная машина не может быть запущена из-за нехватки ресурсов. #"loose" позволяет запускать виртуальную машину, если недостаточно ресурсов. #cpu_allocation_parameter = "strict" #параметр коэффициента распределения CPU - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число #один pCPU = коэффициент*vCPU (принимает нулевое или положительное значение) #cpu_allocation_ratio = 1 - #мгновеное удаление аккаунта, если да - то аккаунт невозможно будет восстановить - #необязательный параметр - #тип - булев тип + #мгновенное удаление аккаунта, если да - то аккаунт невозможно будет восстановить + #опциональный параметр + #тип - булев #используется при удалении аккаунта #по-умолчанию - false #permanently = true #флаг для восстановление аккаунта из корзины - #необязательный параметр - #тип - булев тип + #опциональный параметр + #тип - булев #restore = true + + #предоставление аккаунту доступа к конкретным образам + #опциональный параметр + #тип - массив целых чисел + #available_templates = [1,2] + + #доступ к дополнительным функциям управления ВМ + #опциональный параметр + #возможные значенния - "hugepages", "numa", "cpupin", "vfnic" + #тип - массив строк + #compute_features = ["hugepages", "numa", "cpupin", "vfnic"] } output "test" { diff --git a/samples/cloudbroker/data_audit/main.tf b/samples/cloudbroker/audit/data_audit/main.tf similarity index 99% rename from samples/cloudbroker/data_audit/main.tf rename to samples/cloudbroker/audit/data_audit/main.tf index 25d62d5..d63a5c8 100644 --- a/samples/cloudbroker/data_audit/main.tf +++ b/samples/cloudbroker/audit/data_audit/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -31,6 +31,7 @@ data "decort_cb_audit" "audit" { #обязательный параметр #тип - строка audit_guid = "abcdefg" + } output "test" { diff --git a/samples/cloudbroker/data_audit_linked_jobs/main.tf b/samples/cloudbroker/audit/data_audit_linked_jobs/main.tf similarity index 99% rename from samples/cloudbroker/data_audit_linked_jobs/main.tf rename to samples/cloudbroker/audit/data_audit_linked_jobs/main.tf index fe05812..e8c750a 100644 --- a/samples/cloudbroker/data_audit_linked_jobs/main.tf +++ b/samples/cloudbroker/audit/data_audit_linked_jobs/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -31,6 +31,7 @@ data "decort_cb_audit_linked_jobs" "jobs" { #обязательный параметр #тип - строка audit_guid = "abcdefg" + } output "test" { diff --git a/samples/cloudbroker/data_audit_list/main.tf b/samples/cloudbroker/audit/data_audit_list/main.tf similarity index 72% rename from samples/cloudbroker/data_audit_list/main.tf rename to samples/cloudbroker/audit/data_audit_list/main.tf index 60d931d..de2846f 100644 --- a/samples/cloudbroker/data_audit_list/main.tf +++ b/samples/cloudbroker/audit/data_audit_list/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +29,12 @@ provider "decort" { data "decort_cb_audit_list" "al" { #фильтр по аудитам с временной меткой после указанного значения #опциональный параметр - #тип - число + #тип - целое число #timestamp_at = 123456 #фильтр по аудитам с временной меткой до указанного значения #опциональный параметр - #тип - число + #тип - целое число #timestamp_to = 123456 #фильтр по пользователю (Mongo RegExp поддерживаются) @@ -47,20 +47,32 @@ data "decort_cb_audit_list" "al" { #тип - строка #call = "/restmachine/cloudbroker/audit/list" - #фильтр по HTTP статус-коду + #фильтр по минимальному HTTP статус-коду + #опциональный параметр + #тип - целое число + #min_status_code = 200 + + #фильтр по максимальному HTTP статус-коду #опциональный параметр - #тип - число - #status_code = 200 + #тип - целое число + #max_status_code = 500 + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/data_flipgroup/main.tf b/samples/cloudbroker/data_flipgroup/main.tf deleted file mode 100644 index 3e26c92..0000000 --- a/samples/cloudbroker/data_flipgroup/main.tf +++ /dev/null @@ -1,37 +0,0 @@ -/* -Пример использования -Получение flipgroup по id -*/ - -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - oauth2_url = "https://sso-alpha.dev.decs.online" - controller_url = "https://alpha.dev.decs.online" - app_id = "" - app_secret = "" -} - -data "decort_cb_flipgroup" "fg" { - # ID флипгруппы - # Обязательный параметр - # int - flipgroup_id = 999 -} - -output "fg_out" { - value = data.decort_cb_flipgroup.fg -} diff --git a/samples/cloudbroker/data_flipgroup_list/main.tf b/samples/cloudbroker/data_flipgroup_list/main.tf deleted file mode 100644 index 9bce6c1..0000000 --- a/samples/cloudbroker/data_flipgroup_list/main.tf +++ /dev/null @@ -1,79 +0,0 @@ -/* -Пример использования -Получение списка flipgroup -*/ - -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - oauth2_url = "https://sso-alpha.dev.decs.online" - controller_url = "https://alpha.dev.decs.online" - app_id = "" - app_secret = "" -} - -data "decort_cb_flipgroup_list" "fg" { - #фильтр по id flipgroup - #опциональный параметр - #тип - число - #by_id = 100 - - #фильтр по имени flipgroup - #опциональный параметр - #тип - строка - #name = "test" - - #фильтр по id vins - #опциональный параметр - #тип - число - #vins_id = 100 - - #фильтр по имени vins - #опциональный параметр - #тип - строка - #vins_name = "test" - - #фильтр по id extnet - #опциональный параметр - #тип - число - #extnet_id = 100 - - #фильтр по IP - #опциональный параметр - #тип - строка - #by_ip = "1.1.1.1.1" - - #фильтр по id ресурсной группы - #опциональный параметр - #тип - число - #rg_id = 11111 - - #номер страницы для отображения - #опциональный параметр - #тип - число - #если не задан - выводятся все доступные данные - #page = 2 - - #размер страницы - #опциональный параметр - #тип - число - #если не задан - выводятся все доступные данные - #size = 3 -} - -output "fg_out" { - value = data.decort_cb_flipgroup_list.fg -} diff --git a/samples/cloudbroker/data_grid_get_post_diagnosis/main.tf b/samples/cloudbroker/data_grid_get_post_diagnosis/main.tf deleted file mode 100644 index 14c7022..0000000 --- a/samples/cloudbroker/data_grid_get_post_diagnosis/main.tf +++ /dev/null @@ -1,50 +0,0 @@ -/* -Пример использования -Получение снимка платформы с дополнительной диагностической информацией -(журналы и т. д.). -*/ - -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -data "decort_cb_grid_get_diagnosis" "gd" { - #id grid для получения информации - #обязательный параметр - #тип - число - gid = 215 -} - -data "decort_cb_grid_post_diagnosis" "pd" { - #id grid для получения информации - #обязательный параметр - #тип - число - gid = 215 -} - -output "test-gd" { - value = data.decort_cb_grid_get_diagnosis.gd -} - -output "test-pd" { - value = data.decort_cb_grid_post_diagnosis.pd -} diff --git a/samples/cloudbroker/data_rg_list_vins/main.tf b/samples/cloudbroker/data_rg_list_vins/main.tf deleted file mode 100644 index c9dd5f5..0000000 --- a/samples/cloudbroker/data_rg_list_vins/main.tf +++ /dev/null @@ -1,68 +0,0 @@ -/* -Пример использования -Получение информации о списке винсов в ресурсной группе -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -/* terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} */ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -data "decort_cb_rg_list_vins" "list_vins" { - #id ресурсной группы - #обязательный параметр - #тип - число - rg_id = 123 - - # фильтр по id vins - # опциональный параметр - # тип - число - # vins_id = 100 - - # фильтр по имени vins - # опциональный параметр - # тип - строка - # name = "test" - - # id аккаунта для получения списка балансировщиков нагрузки - # опциональный параметр - # тип - число - # account_id = 11111 - - # фильтр по IP внешней сети - # опциональный параметр - # тип - строка - # ext_ip = "test" - - # номер страницы для отображения - # опциональный параметр - # тип - число - # если не задан - выводятся все доступные данные - # page = 2 - - # размер страницы - # опциональный параметр - # тип - число - # если не задан - выводятся все доступные данные - # size = 3 -} - -output "output" { - value = data.decort_cb_rg_list_vins.list_vins -} diff --git a/samples/cloudbroker/data_disk/main.tf b/samples/cloudbroker/disk/data_disk/main.tf similarity index 87% rename from samples/cloudbroker/data_disk/main.tf rename to samples/cloudbroker/disk/data_disk/main.tf index 5d7b892..073383b 100644 --- a/samples/cloudbroker/data_disk/main.tf +++ b/samples/cloudbroker/disk/data_disk/main.tf @@ -1,20 +1,21 @@ /* Пример использования -Получение данных диска +Получение информации об уже существующем диске. */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,8 +29,9 @@ provider "decort" { data "decort_cb_disk" "acl" { #id диска #обязательный параметр - #тип - число + #тип - целое число disk_id = 49304 + } output "test" { diff --git a/samples/cloudbroker/data_disk_list/main.tf b/samples/cloudbroker/disk/data_disk_list/main.tf similarity index 80% rename from samples/cloudbroker/data_disk_list/main.tf rename to samples/cloudbroker/disk/data_disk_list/main.tf index cda9e79..09f9e01 100644 --- a/samples/cloudbroker/data_disk_list/main.tf +++ b/samples/cloudbroker/disk/data_disk_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка доступных дисков */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_disk_list" "dl" { #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #by_id = 11111 #фильтр по имени диска @@ -44,7 +44,7 @@ data "decort_cb_disk_list" "dl" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 3 #фильтр по статусу @@ -59,7 +59,7 @@ data "decort_cb_disk_list" "dl" { #id аккаунта для получения списка дисков #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #тип диска @@ -70,7 +70,7 @@ data "decort_cb_disk_list" "dl" { #фильтр по sep id #опциональный параметр - #тип - число + #тип - целое число #sep_id = 1 #фильтр по названию pool @@ -78,15 +78,22 @@ data "decort_cb_disk_list" "dl" { #тип - строка #pool = "pool name" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 + } output "test" { diff --git a/samples/cloudbroker/data_disk_list_deleted/main.tf b/samples/cloudbroker/disk/data_disk_list_deleted/main.tf similarity index 78% rename from samples/cloudbroker/data_disk_list_deleted/main.tf rename to samples/cloudbroker/disk/data_disk_list_deleted/main.tf index 2c26a8a..a74192c 100644 --- a/samples/cloudbroker/data_disk_list_deleted/main.tf +++ b/samples/cloudbroker/disk/data_disk_list_deleted/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка удаленных дисков */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_disk_list_deleted" "dld" { #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #by_id = 11111 #фильтр по имени диска @@ -44,7 +44,7 @@ data "decort_cb_disk_list_deleted" "dld" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 3 #фильтр по полю shared @@ -54,24 +54,31 @@ data "decort_cb_disk_list_deleted" "dld" { #id аккаунта для получения списка дисков #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #тип диска - #опциональный параметр - #тип - строка + #опциональный параметр #возможные типы: "b" - boot_disk, "d" - data_disk + #тип - строка #type = "d" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 + } output "test" { diff --git a/samples/cloudbroker/data_disk_list_types/main.tf b/samples/cloudbroker/disk/data_disk_list_types/main.tf similarity index 79% rename from samples/cloudbroker/data_disk_list_types/main.tf rename to samples/cloudbroker/disk/data_disk_list_types/main.tf index 1aa6b4d..a543b2e 100644 --- a/samples/cloudbroker/data_disk_list_types/main.tf +++ b/samples/cloudbroker/disk/data_disk_list_types/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка типов дисков (недетализированное) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,17 +27,24 @@ provider "decort" { } data "decort_cb_disk_list_types" "dlt" { + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/data_disk_list_types_detailed/main.tf b/samples/cloudbroker/disk/data_disk_list_types_detailed/main.tf similarity index 79% rename from samples/cloudbroker/data_disk_list_types_detailed/main.tf rename to samples/cloudbroker/disk/data_disk_list_types_detailed/main.tf index 99af944..141785f 100644 --- a/samples/cloudbroker/data_disk_list_types_detailed/main.tf +++ b/samples/cloudbroker/disk/data_disk_list_types_detailed/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка типов дисков, но детально */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -26,19 +26,25 @@ provider "decort" { allow_unverified_ssl = true } - data "decort_cb_disk_list_types_detailed" "dltd" { + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/data_disk_list_unattached/main.tf b/samples/cloudbroker/disk/data_disk_list_unattached/main.tf similarity index 82% rename from samples/cloudbroker/data_disk_list_unattached/main.tf rename to samples/cloudbroker/disk/data_disk_list_unattached/main.tf index 4120e84..eb90678 100644 --- a/samples/cloudbroker/data_disk_list_unattached/main.tf +++ b/samples/cloudbroker/disk/data_disk_list_unattached/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка доступных неприсоединенных дисков */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,9 +29,9 @@ provider "decort" { data "decort_cb_disk_list_unattached" "dlu" { #фильтр по id диска #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 - + #фильтр по имени аккаунта #опциональный параметр #тип - строка @@ -38,7 +39,7 @@ data "decort_cb_disk_list_unattached" "dlu" { #фильтр по максимальному размеру диска #опциональный параметр - #тип - число + #тип - целое число #disk_max_size = 100 #фильтр по статусу @@ -54,12 +55,12 @@ data "decort_cb_disk_list_unattached" "dlu" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #account_id = 100 #фильтр по id sep #опциональный параметр - #тип - число + #тип - целое число #sep_id = 1 #фильтр по имени pool @@ -67,17 +68,24 @@ data "decort_cb_disk_list_unattached" "dlu" { #тип - строка #pool = "test" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/disk/data_disk_replication/main.tf b/samples/cloudbroker/disk/data_disk_replication/main.tf new file mode 100644 index 0000000..7ece417 --- /dev/null +++ b/samples/cloudbroker/disk/data_disk_replication/main.tf @@ -0,0 +1,44 @@ +/* +Пример использования +Получение статуса репликации диска +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_disk_replication" "dr" { + #id диска для которого подключена репликация + #обязательный параметр + #тип - целое число + disk_id = 49304 + + #id реплики диска + #обязательный параметр + #тип - целое число + replica_disk_id = 1213 + +} + +output "test" { + value = data.decort_cb_disk_replication.dr +} diff --git a/samples/cloudbroker/data_disk_snapshot/main.tf b/samples/cloudbroker/disk/data_disk_snapshot/main.tf similarity index 92% rename from samples/cloudbroker/data_disk_snapshot/main.tf rename to samples/cloudbroker/disk/data_disk_snapshot/main.tf index 2428fac..2bca628 100644 --- a/samples/cloudbroker/data_disk_snapshot/main.tf +++ b/samples/cloudbroker/disk/data_disk_snapshot/main.tf @@ -2,6 +2,7 @@ Пример использования Получение конкретного снапшота */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,15 +27,16 @@ provider "decort" { } data "decort_cb_disk_snapshot" "ds" { - #Номер диска + #номер диска #обязательный параметр - #тип - число + #тип - целое число disk_id = 20100 - #Ярлык диска + #ярлык диска #обязательный параметр #тип - строка label = "label" + } output "test" { diff --git a/samples/cloudbroker/data_disk_snapshot_list/main.tf b/samples/cloudbroker/disk/data_disk_snapshot_list/main.tf similarity index 93% rename from samples/cloudbroker/data_disk_snapshot_list/main.tf rename to samples/cloudbroker/disk/data_disk_snapshot_list/main.tf index 64cdb20..7e39ba2 100644 --- a/samples/cloudbroker/data_disk_snapshot_list/main.tf +++ b/samples/cloudbroker/disk/data_disk_snapshot_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка снапшотов диска */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,10 +27,11 @@ provider "decort" { } data "decort_cb_disk_snapshot_list" "ds" { - #Номер диска + #номер диска #обязательный параметр - #тип - число + #тип - целое число disk_id = 20100 + } output "test" { diff --git a/samples/cloudbroker/resource_disk/main.tf b/samples/cloudbroker/disk/resource_disk/main.tf similarity index 87% rename from samples/cloudbroker/resource_disk/main.tf rename to samples/cloudbroker/disk/resource_disk/main.tf index 64dd85d..e0834a9 100644 --- a/samples/cloudbroker/resource_disk/main.tf +++ b/samples/cloudbroker/disk/resource_disk/main.tf @@ -1,22 +1,25 @@ /* Пример использования -Ресура диска: +Ресурса диска: 1. Создание ресурса 2. Изменение ресурса 3. Удаление ресурса */ + #Раскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } +*/ provider "decort" { authenticator = "decs3o" @@ -30,12 +33,12 @@ provider "decort" { resource "decort_cb_disk" "acl" { #id аккаунта #обязательный параметр - #тип - число + #тип - целое число account_id = 88366 #gid #обязательный параметр - #тип - число + #тип - целое число gid = 212 #название диска диска @@ -47,11 +50,11 @@ resource "decort_cb_disk" "acl" { #обязательный параметр #тип - строка #допустимые значения: "D", "B", "T" - type = "d" + type = "D" #максимальный размер диска #обязательный параметр - #тип - число + #тип - целое число #значение по умолчанию 10 size_max = 20 @@ -62,19 +65,19 @@ resource "decort_cb_disk" "acl" { #размер ssd #опциональный параметр - #тип - число + #тип - целое число #значение по умолчанию 0 #ssd_size = 1 #max IOPS disk can perform #опциональный параметр - #тип - число + #тип - целое число #значение по умолчанию 2000 #iops = 1 #sep id #опциональный параметр - #тип - число + #тип - целое число #значение по умолчанию 0 #sep_id = 1 @@ -83,6 +86,11 @@ resource "decort_cb_disk" "acl" { #тип - строка #pool = 1 + #список node + #опциональный параметр + #тип - массив целых чисел + #node_ids = [10,11] + #флаг для восстановления диска #опциональный параметр #тип - булев @@ -110,7 +118,8 @@ resource "decort_cb_disk" "acl" { #настройки лимитов операций записи/чтения с диска #опциональный параметр - #тип - блок, тип вложенных полей - число + #тип - блок + #тип вложенных полей - целое число iotune { read_bytes_sec = 0 read_bytes_sec_max = 0 diff --git a/samples/cloudbroker/disk/resource_disk_replication/main.tf b/samples/cloudbroker/disk/resource_disk_replication/main.tf new file mode 100644 index 0000000..5604840 --- /dev/null +++ b/samples/cloudbroker/disk/resource_disk_replication/main.tf @@ -0,0 +1,84 @@ +/* +Пример использования +Ресурс репликации диска +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_disk_replication" "dr" { + #ID диска из которого будет создана реплика + #обязательный параметр + #тип - целое число + disk_id = 20100 + + #Имя реплики диска + #обязательный параметр + #тип - строка + disk_name = "test" + + #sep id + #обязательный параметр + #тип - целое число + sep_id = 1 + + #название pool + #обязательный параметр + #тип - строка + pool_name = "some" + + #флаг паузы + #опциональный параметр + #тип - булев + #pause = false + + #флаг для изменения ролей дисков + #опциональный параметр + #тип - булев + #reverse = false + + #флаг для запуска связи между диском и репликой + #опциональный параметр + #тип - булев + #start = false + + #флаг для отключения диска от ВМ при удалении + #опциональный параметр + #тип - булев + #detach = false + + #флаг для удаления реплики диска безвозвратно + #опциональный параметр + #тип - булев + #permanently = false + + #описание причины удаления + #опциональный параметр + #тип - строка + #reason = "some" +} + +output "test" { + value = decort_cb_disk_replication.dr +} diff --git a/samples/cloudbroker/resource_disk_snapshot/main.tf b/samples/cloudbroker/disk/resource_disk_snapshot/main.tf similarity index 89% rename from samples/cloudbroker/resource_disk_snapshot/main.tf rename to samples/cloudbroker/disk/resource_disk_snapshot/main.tf index d1a199a..757fb55 100644 --- a/samples/cloudbroker/resource_disk_snapshot/main.tf +++ b/samples/cloudbroker/disk/resource_disk_snapshot/main.tf @@ -2,18 +2,21 @@ Пример использования Ресурс снапшота диска */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } +*/ provider "decort" { authenticator = "decs3o" @@ -25,25 +28,25 @@ provider "decort" { } resource "decort_cb_disk_snapshot" "ds" { - #Номер диска + #номер диска #обязательный параметр - #тип - число + #тип - целое число disk_id = 20100 - #Ярлык диска + #ярлык диска #обязательный параметр #тип - строка label = "label" #флаг rollback #опциональный параметр - #тип - bool + #тип - булев #значение по умолчанию - false #rollback = true #timestamp #опциональный параметр - #тип - число + #тип - целое число #применимо совместно с rollback = true #timestamp = 15 } diff --git a/samples/cloudbroker/data_extnet/main.tf b/samples/cloudbroker/extnet/data_extnet/main.tf similarity index 83% rename from samples/cloudbroker/data_extnet/main.tf rename to samples/cloudbroker/extnet/data_extnet/main.tf index bc02ddc..898d83f 100644 --- a/samples/cloudbroker/data_extnet/main.tf +++ b/samples/cloudbroker/extnet/data_extnet/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение информации о сети +Получение информации о внешней сети */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,10 +27,11 @@ provider "decort" { } data "decort_cb_extnet" "ex" { - # ID сети - # Обязательный параметр - # Тип - число + #id сети + #обязательный параметр + #тип - целое число extnet_id = 13 + } output "ex_out" { diff --git a/samples/cloudbroker/data_extnet_default/main.tf b/samples/cloudbroker/extnet/data_extnet_default/main.tf similarity index 88% rename from samples/cloudbroker/data_extnet_default/main.tf rename to samples/cloudbroker/extnet/data_extnet_default/main.tf index 67ac0d3..3bdfa5a 100644 --- a/samples/cloudbroker/data_extnet_default/main.tf +++ b/samples/cloudbroker/extnet/data_extnet_default/main.tf @@ -1,8 +1,8 @@ /* Пример использования -Получение информации о сети по-умолчанию - +Получение информации о доступной внешней сети по-умолчанию */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = diff --git a/samples/cloudbroker/data_extnet_list/main.tf b/samples/cloudbroker/extnet/data_extnet_list/main.tf similarity index 72% rename from samples/cloudbroker/data_extnet_list/main.tf rename to samples/cloudbroker/extnet/data_extnet_list/main.tf index 29f2eee..c77bf50 100644 --- a/samples/cloudbroker/data_extnet_list/main.tf +++ b/samples/cloudbroker/extnet/data_extnet_list/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение списка сетей +Получение списка внешних сетей */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -28,13 +28,13 @@ provider "decort" { data "decort_cb_extnet_list" "ex_list" { #id аккаунта для фильтрации результата - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число #account_id = 1111111 #фильтр по id внешней сети #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени внешней сети @@ -49,12 +49,12 @@ data "decort_cb_extnet_list" "ex_list" { #фильтр по id vlan #опциональный параметр - #тип - число + #тип - целое число #vlan_id = 100 #фильтр по id vnfDevices #опциональный параметр - #тип - число + #тип - целое число #vnfdev_id = 100 #фильтр по статусу @@ -62,15 +62,22 @@ data "decort_cb_extnet_list" "ex_list" { #тип - строка #status = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 + } output "ex_out" { diff --git a/samples/cloudbroker/data_extnet_static_route/main.tf b/samples/cloudbroker/extnet/data_extnet_static_route/main.tf similarity index 94% rename from samples/cloudbroker/data_extnet_static_route/main.tf rename to samples/cloudbroker/extnet/data_extnet_static_route/main.tf index 00f0fe3..985e6ed 100644 --- a/samples/cloudbroker/data_extnet_static_route/main.tf +++ b/samples/cloudbroker/extnet/data_extnet_static_route/main.tf @@ -1,7 +1,6 @@ /* Пример использования Получение информации о static routes по id в данном extnet - */ #Расскомментируйте этот код, @@ -11,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,12 +29,12 @@ provider "decort" { data "decort_cb_extnet_static_route" "route" { #обязательный параметр #id extnet в котором добавлены routes - #тип - число + #тип - целое число extnet_id = 1111 #обязательный параметр #id route - #тип - число + #тип - целое число route_id = 1 } diff --git a/samples/cloudbroker/data_extnet_static_route_list/main.tf b/samples/cloudbroker/extnet/data_extnet_static_route_list/main.tf similarity index 96% rename from samples/cloudbroker/data_extnet_static_route_list/main.tf rename to samples/cloudbroker/extnet/data_extnet_static_route_list/main.tf index 09d2050..9fb387d 100644 --- a/samples/cloudbroker/data_extnet_static_route_list/main.tf +++ b/samples/cloudbroker/extnet/data_extnet_static_route_list/main.tf @@ -3,7 +3,6 @@ Получение списка static routes в данном extnet */ -/* #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -30,7 +29,7 @@ provider "decort" { data "decort_cb_extnet_static_route_list" "list" { #обязательный параметр #id extnet в котором добавлены routes - #тип - число + #тип - целое число extnet_id = 1111 } diff --git a/samples/cloudbroker/extnet/resource_extnet/main.tf b/samples/cloudbroker/extnet/resource_extnet/main.tf new file mode 100644 index 0000000..4d6c1e1 --- /dev/null +++ b/samples/cloudbroker/extnet/resource_extnet/main.tf @@ -0,0 +1,184 @@ +/* +Пример использования +Ресурса extnet +Ресурс позволяет: +1. Создавать extnet +2. Удалять extnet +3. Получать информацию о extnet +4. Предоставлять доступ аккаунтов к extnet +5. Удалять доступ аккаунтов к extnet +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +/* + terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } + } +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_extnet" "new_extnet" { + #наименование внешней сети + #обязательный параметр + #тип - строка + name = "test_extnet" + + #id платформы + #обязательный параметр + #тип - целое число + gid = 500 + + #CIDR + #обязательный параметр + #тип - строка + ipcidr = "192.168.0.0/24" + + #id виртуальной локальной сети + #обязательный параметр + #тип - целое число + vlan_id = 111 + + #IP-адрес шлюза внешней сети + #опциональный параметр + #тип - строка + #gateway = "test desc" + + #cписок DNS адресов + #опциональный параметр + #тип - массив строк + #dns = ["8.8.8.8", "9.9.9.9"] + + #список NTP адресов + #опциональный параметр + #тип - массив строк + #ntp = ["ntp0.ntp-servers.net", "ntp1.ntp-servers.net"] + + #IP-адреса для проверки доступности сети + #опциональный параметр + #тип - массив строк + #check_ips = ["191.255.0.0,", "191.255.0.0,"] + + #если true - DHCP-сервер создан не будет + #опциональный параметр + #тип - булев + #virtual = true + + #описание + #опциональный параметр + #тип - строка + #desc = "test desc" + + #начало диапазона IP-адресов + #опциональный параметр + #тип - строка + #start_ip = "191.255.0.0" + + #окончание диапазона IP-адресов + #опциональный параметр + #тип - строка + #end_ip = "191.255.0.40" + + #IP с которым будет создан vnfdev + #опциональный параметр + #тип - строка + #vnfdev_ip = "191.255.0.20" + + #количество предварительно созданных бронирований + #опциональный параметр + #тип - целое число + #по умолчанию - 128 + #pre_reservations_num = 128 + + #имя bridge Openvswitch для подключения к внешней сети + #опциональный параметр + #тип - строка + #ovs_bridge = "some" + + #включение/выключение внешней сети + #опциональный параметр + #тип - булев + #enable = true + + #сделать сеть сетью по умолчанию + #опциональный параметр + #тип - булев + #set_default = true + + #список исключенных IP адресов + #опциональный параметр + #тип - массив строк + #excluded_ips = ["192.168.0.4", "192.168.0.5"] + + #диапазон исключенных IP адресов + #опциональный параметр + #тип - блок, + #тип вложенных полей - строка + excluded_ips_range { + #начало диапазона + #обязательный параметр + #тип - строка + ip_start = "192.168.0.4" + + #окончание диапазона + #обязательный параметр + #тип - строка + ip_end = "192.168.0.50" + } + + #список id аккаунтов, которым предоставлен доступ к extnet + #опциональный параметр + #тип - массив целых чисел + #shared_with = [112, 123] + + #изменение настроек ограничения трафика сети + #значение по умолчанию 0, то есть без ограничений + #опциональный параметр + #тип - блок, + #тип вложенных полей - целое число + default_qos { + #ограничение внутреннего трафика в кбит + #опциональный параметр + #тип - целое число + #in_rate = 0 + + #ограничение внутреннего burst трафика в кбит + #опциональный параметр + #тип - целое число + #in_burst = 0 + + #ограничение внешнего трафика в кбит + #опциональный параметр + #тип - целое число + #e_rate = 0 + } + + #ID stack на который происходит миграция + #опциональный параметр + #тип - целое число + #migrate = 1 + + #перезапустить сеть + #опциональный параметр + #тип - булев + #restart = true +} + +output "extnet" { + value = decort_cb_extnet.new_extnet +} \ No newline at end of file diff --git a/samples/cloudbroker/resource_extnet_static_route/main.tf b/samples/cloudbroker/extnet/resource_extnet_static_route/main.tf similarity index 61% rename from samples/cloudbroker/resource_extnet_static_route/main.tf rename to samples/cloudbroker/extnet/resource_extnet_static_route/main.tf index bc67cbb..7056ec3 100644 --- a/samples/cloudbroker/resource_extnet_static_route/main.tf +++ b/samples/cloudbroker/extnet/resource_extnet_static_route/main.tf @@ -7,7 +7,6 @@ 3. Получать информацию о всех static routes в данном extnet 4. Предоставлять доступ виртуальным машинам к static routes 5. Удалять доступ виртуальным машинам к static routes - */ #Расскомментируйте этот код, @@ -17,8 +16,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -35,30 +34,30 @@ provider "decort" { resource "decort_cb_extnet_static_route" "sr" { -#id extnet -#обязательный параметр -#тип - число -extnet_id = 1111 + #id extnet + #обязательный параметр + #тип - целое число + extnet_id = 1111 -# destination network -# обязательный параметр -#тип - строка -destination = "192.168.201.0" + #destination network + #обязательный параметр + #тип - строка + destination = "192.168.201.0" -# destination network mask -#обязательный параметр -#тип - строка -netmask = "255.255.255.255" + #destination network mask + #обязательный параметр + #тип - строка + netmask = "255.255.255.255" -# IP-адрес из пула свободных IP-адресов extnet ID -#обязательный параметр -#тип - строка -gateway = "192.168.201.40" + #IP-адрес из пула свободных IP-адресов extnet ID + #обязательный параметр + #тип - строка + gateway = "192.168.201.40" -# список виртуальных машин, которым будет предоставлен доступ к роуту -#опциональный параметр -#тип - массив чисел -compute_ids = [111,222] + #список виртуальных машин, которым будет предоставлен доступ к роуту + #опциональный параметр + #тип - массив целых чисел + #compute_ids = [111,222] } output "sr" { diff --git a/samples/cloudbroker/flipgroup/data_flipgroup/main.tf b/samples/cloudbroker/flipgroup/data_flipgroup/main.tf new file mode 100644 index 0000000..4a5d8dd --- /dev/null +++ b/samples/cloudbroker/flipgroup/data_flipgroup/main.tf @@ -0,0 +1,39 @@ +/* +Пример использования +Получение flipgroup по id +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_flipgroup" "fg" { + #id флипгруппы + #обязательный параметр + #тип - целое число + flipgroup_id = 999 + +} + +output "fg_out" { + value = data.decort_cb_flipgroup.fg +} diff --git a/samples/cloudbroker/flipgroup/data_flipgroup_list/main.tf b/samples/cloudbroker/flipgroup/data_flipgroup_list/main.tf new file mode 100644 index 0000000..fefa060 --- /dev/null +++ b/samples/cloudbroker/flipgroup/data_flipgroup_list/main.tf @@ -0,0 +1,107 @@ +/* +Пример использования +Получение списка flipgroup +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_flipgroup_list" "fg" { + #фильтр по id flipgroup + #опциональный параметр + #тип - целое число + #by_id = 100 + + #фильтр по имени flipgroup + #опциональный параметр + #тип - строка + #name = "test" + + #фильтр по id vins + #опциональный параметр + #тип - целое число + #vins_id = 100 + + #фильтр по имени vins + #опциональный параметр + #тип - строка + #vins_name = "test" + + #фильтр по id extnet + #опциональный параметр + #тип - целое число + #extnet_id = 100 + + #фильтр по IP + #опциональный параметр + #тип - строка + #by_ip = "1.1.1.1.1" + + #фильтр по id ресурсной группы + #опциональный параметр + #тип - целое число + #rg_id = 11111 + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + + #номер страницы для отображения + #опциональный параметр + #если не задан - выводятся все доступные данные + #тип - целое число + #page = 2 + + #размер страницы + #опциональный параметр + #если не задан - выводятся все доступные данные + #тип - целое число + #size = 3 + + #фильтр по id аккаунта + #опциональный параметр + #тип - целое число + #account_id = 100 + + #фильтр по id conn + #опциональный параметр + #тип - целое число + #conn_id = 100 + + #фильтр по id клиентов + #опциональный параметр + #тип - массив целых чисел + #client_ids = [10,11] + + #фильтр по статусу + #опциональный параметр + #тип - строка + #status = "CREATED" + +} + +output "fg_out" { + value = data.decort_cb_flipgroup_list.fg +} diff --git a/samples/cloudbroker/flipgroup/resource_flipgroup/main.tf b/samples/cloudbroker/flipgroup/resource_flipgroup/main.tf new file mode 100644 index 0000000..e10b631 --- /dev/null +++ b/samples/cloudbroker/flipgroup/resource_flipgroup/main.tf @@ -0,0 +1,78 @@ +/* +Пример использования +Работа с ресурсом flipgroup (группа с плавающим ip-адресом) +Ресурс позволяет: +1. Создавать flipgroup +2. Редактировать flipgroup +3. Удалять flipgroup +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + oauth2_url = "https://sso-alpha.dev.decs.online" + controller_url = "https://alpha.dev.decs.online" + app_id = "" + app_secret = "" +} + +resource "decort_cb_flipgroup" "fg" { + #id аккаунта + #обязательный параметр + #тип - целое число + account_id = 999 + + #наименование Flipgroup + #обязательный параметр + #тип - строка + name = "flipgroup_name" + + #тип сети + #обязательный параметр + #возможные значенния - "EXTNET", "VINS" + #тип - строка + net_type = "EXTNET" + + #id сети + #обязательный параметр + #тип - целое число + net_id = 13 + + #тип клиентов + #обязательный параметр + #тип - строка + #в данный момент поддерживается только тип 'compute' + client_type = "compute" + + #ip-адрес + #опциональный параметр + #тип - строка + #ip = "127.0.0.1" + + #cписок клиентов, прикрепленных к флипгруппе + #опциональный параметр + #тип - массив целых чисел + #client_ids = [11269] + + #описание флипгруппы + #опциональный параметр + #тип - строка + #desc = "CHANGED" +} + +output "fg_out" { + value = decort_cb_flipgroup.fg +} diff --git a/samples/cloudbroker/data_grid/main.tf b/samples/cloudbroker/grid/data_grid/main.tf similarity index 96% rename from samples/cloudbroker/data_grid/main.tf rename to samples/cloudbroker/grid/data_grid/main.tf index 75b36e1..a836c1b 100644 --- a/samples/cloudbroker/data_grid/main.tf +++ b/samples/cloudbroker/grid/data_grid/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,8 +29,9 @@ provider "decort" { data "decort_cb_grid" "grid" { #id grid для получения информации #обязательный параметр - #тип - число + #тип - целое число grid_id = 215 + } output "test" { diff --git a/samples/cloudbroker/data_grid_get_consumption/main.tf b/samples/cloudbroker/grid/data_grid_get_consumption/main.tf similarity index 96% rename from samples/cloudbroker/data_grid_get_consumption/main.tf rename to samples/cloudbroker/grid/data_grid_get_consumption/main.tf index a6c3294..5b163e9 100644 --- a/samples/cloudbroker/data_grid_get_consumption/main.tf +++ b/samples/cloudbroker/grid/data_grid_get_consumption/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,8 +29,9 @@ provider "decort" { data "decort_cb_grid_get_consumption" "cons" { #id grid для получения информации #обязательный параметр - #тип - число + #тип - целое число grid_id = 215 + } output "test" { diff --git a/samples/cloudbroker/data_grid_get_post_status/main.tf b/samples/cloudbroker/grid/data_grid_get_post_status/main.tf similarity index 100% rename from samples/cloudbroker/data_grid_get_post_status/main.tf rename to samples/cloudbroker/grid/data_grid_get_post_status/main.tf index 6c4cdd4..1d0ce80 100644 --- a/samples/cloudbroker/data_grid_get_post_status/main.tf +++ b/samples/cloudbroker/grid/data_grid_get_post_status/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } diff --git a/samples/cloudbroker/data_grid_list/main.tf b/samples/cloudbroker/grid/data_grid_list/main.tf similarity index 74% rename from samples/cloudbroker/data_grid_list/main.tf rename to samples/cloudbroker/grid/data_grid_list/main.tf index 43260ba..ce595e1 100644 --- a/samples/cloudbroker/data_grid_list/main.tf +++ b/samples/cloudbroker/grid/data_grid_list/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_grid_list" "gl" { #фильтр по id grid #опциональный параметр - #тип - число + #тип - целое число #by_id = 1 #название grid @@ -37,15 +37,24 @@ data "decort_cb_grid_list" "gl" { #тип - строка #name = "grid name" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения - #опциональный параметр, тип - число + #опциональный параметр #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы - #опциональный параметр, тип - число + #опциональный параметр #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/data_grid_list_consumption/main.tf b/samples/cloudbroker/grid/data_grid_list_consumption/main.tf similarity index 100% rename from samples/cloudbroker/data_grid_list_consumption/main.tf rename to samples/cloudbroker/grid/data_grid_list_consumption/main.tf index 8076c5f..dc22a09 100644 --- a/samples/cloudbroker/data_grid_list_consumption/main.tf +++ b/samples/cloudbroker/grid/data_grid_list_consumption/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } diff --git a/samples/cloudbroker/data_grid_list_emails/main.tf b/samples/cloudbroker/grid/data_grid_list_emails/main.tf similarity index 88% rename from samples/cloudbroker/data_grid_list_emails/main.tf rename to samples/cloudbroker/grid/data_grid_list_emails/main.tf index ab12204..6209cf5 100644 --- a/samples/cloudbroker/data_grid_list_emails/main.tf +++ b/samples/cloudbroker/grid/data_grid_list_emails/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,14 +28,17 @@ provider "decort" { data "decort_cb_grid_list_emails" "gle" { #номер страницы для отображения - #опциональный параметр, тип - число + #опциональный параметр #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы - #опциональный параметр, тип - число + #опциональный параметр #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/data_image/main.tf b/samples/cloudbroker/image/data_image/main.tf similarity index 96% rename from samples/cloudbroker/data_image/main.tf rename to samples/cloudbroker/image/data_image/main.tf index 09bd3b6..a5defe9 100644 --- a/samples/cloudbroker/data_image/main.tf +++ b/samples/cloudbroker/image/data_image/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,8 +29,9 @@ provider "decort" { data "decort_cb_image" "image" { #id образа #обязательный параметр - #тип - число + #тип - целое число image_id = 5912 + } output "test" { diff --git a/samples/cloudbroker/data_image_list/main.tf b/samples/cloudbroker/image/data_image_list/main.tf similarity index 83% rename from samples/cloudbroker/data_image_list/main.tf rename to samples/cloudbroker/image/data_image_list/main.tf index 9f081b2..3315586 100644 --- a/samples/cloudbroker/data_image_list/main.tf +++ b/samples/cloudbroker/image/data_image_list/main.tf @@ -3,7 +3,6 @@ Получение списка образов */ - #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -11,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,12 +29,12 @@ provider "decort" { data "decort_cb_image_list" "il" { #фильтр по id sep #опциональный параметр - #тип - число + #тип - целое число #sep_id = 1 - + #фильтр по id образа #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени образа @@ -52,7 +51,7 @@ data "decort_cb_image_list" "il" { #опциональный параметр #тип - строка #architecture = "x86_64" - + #фильтр по типу образа #опциональный параметр #тип - строка @@ -60,7 +59,7 @@ data "decort_cb_image_list" "il" { #фильтр по размеру образа #опциональный параметр - #тип - число + #тип - целое число #image_size = 100 #фильтр по имени SEP @@ -75,30 +74,37 @@ data "decort_cb_image_list" "il" { #фильтр по доступу #опциональный параметр - #тип - булевый тип + #тип - булев #public = "true" #фильтр по hot_resize #опциональный параметр - #тип - булевый тип + #тип - булев #hot_resize = "true" #фильтр по bootable #опциональный параметр - #тип - булевый тип + #тип - булев #bootable = "true" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/data_image_list_stacks/main.tf b/samples/cloudbroker/image/data_image_list_stacks/main.tf similarity index 83% rename from samples/cloudbroker/data_image_list_stacks/main.tf rename to samples/cloudbroker/image/data_image_list_stacks/main.tf index cd95536..95f74dc 100644 --- a/samples/cloudbroker/data_image_list_stacks/main.tf +++ b/samples/cloudbroker/image/data_image_list_stacks/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка stack по id образа */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_image_list_stacks" "im" { #id образа #обязательный параметр - #тип - число + #тип - целое число image_id = 6040 #фильтр по имени образа @@ -46,17 +47,24 @@ data "decort_cb_image_list_stacks" "im" { #тип - строка #type_image = "cdrom" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения информации #опциональный параметр - #тип - число #если не задан - отображается вся доступная информация + #тип - целое число #page = 2 #количество отображаемых объектов на странице #опциональный параметр - #тип - число #если не задан - отображается вся доступная информация + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/resource_delete_images/main.tf b/samples/cloudbroker/image/resource_delete_images/main.tf similarity index 96% rename from samples/cloudbroker/resource_delete_images/main.tf rename to samples/cloudbroker/image/resource_delete_images/main.tf index be9b61d..4656d67 100644 --- a/samples/cloudbroker/resource_delete_images/main.tf +++ b/samples/cloudbroker/image/resource_delete_images/main.tf @@ -12,8 +12,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -31,13 +31,13 @@ provider "decort" { resource "decort_delete_images" "my_images" { #массив, содержащий набор id образов для удаления #обязательный параметр - #тип - массив чисел + #тип - массив целых чисел image_ids = [6125] #параметр удаления #опциональный тип #по-умолчанию - false - #тип - булев тип + #тип - булев permanently = true #причина удаления diff --git a/samples/cloudbroker/resource_image/main.tf b/samples/cloudbroker/image/resource_image/main.tf similarity index 77% rename from samples/cloudbroker/resource_image/main.tf rename to samples/cloudbroker/image/resource_image/main.tf index 594522d..c553a54 100644 --- a/samples/cloudbroker/resource_image/main.tf +++ b/samples/cloudbroker/image/resource_image/main.tf @@ -5,7 +5,6 @@ 1. Создавать образ 2. Редактировать образ 3. Удалять образ - */ #Расскомментируйте этот код, @@ -15,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -39,13 +38,20 @@ resource "decort_cb_image" "my_image" { name = "test_image_rename" #адрес образа - #обязательный параметр + #опциональный параметр + #внимание, для создания ресурса обязательно должен быть указан или url, или image_file #тип - строка url = "https://colba.decs.online/index.php/s/G3H7AREngzeKGw2/download" + #путь к образу для загрузки + #опциональный параметр + #внимание, для создания ресурса обязательно должен быть указан или url, или image_file + #тип - строка + file_path = "img.iso" + #grid id образа #обязательный параметр - #тип - число + #тип - целое число gid = 212 #тип загрузки образа @@ -68,14 +74,14 @@ resource "decort_cb_image" "my_image" { #поддержка hot resize #опциональный параметр - #тип - булев тип + #тип - булев #hot_resize = true #id аккаунта владельца образа #опциональный параметр #может быть использован как при создании, #так и при редактировании образа - #тип данных - число + #тип данных - целое число #account_id = 57252 #имя пользователя и пароль @@ -94,9 +100,9 @@ resource "decort_cb_image" "my_image" { #username_dl = "Valera1" #password_dl = "1231" - #id storage endpoint + #sep id #опциональный параметр, используется при создании - #тип - число + #тип - целое число #sep_id = 1206 #пул для создания образа @@ -105,53 +111,64 @@ resource "decort_cb_image" "my_image" { #pool_name = "vmstor" #архитектура системы образа - #опциаональный параметр, используется при создании + #опциональный параметр, используется при создании #тип - строка #доступные значения: "X86_64" #architecture = "X86_64" #доступность образа #опциональный параметр, используется на уже созданном ресурсе - #тип - булево значение + #тип - булев #enabled = true #является ли образ загрузочным #опциональный параметр, используется на уже созданном ресурсе - #тип - булево значение + #тип - булев #bootable = true #позволяет создавать образ в синхронном режиме #опциональный параметр - #тип - булево значение + #тип - булев #sync_mode = true #настройка доступа образа аккаунтам #опциональный параметр, используется на уже созданном ресурсе - #тип - массив чисел + #тип - массив целых чисел #пустой массив - удаление всех доступов, если они были #shared_with = [28096, 57121] #установка computeci #опциональный параметр, используется на уже созданном ресурсе - #тип - число + #тип - целое число #чтобы сбросить, необходимо передать 0 #computeci_id = 1 #доступные стаки #опциональный параметр, используется на уже созданном ресурсе - #тип - массив строк + #тип - массив целых чисел #для удаления всех доступных стаков, необходимо передать пустой массив #enabled_stacks = [9] + #аккаунты, которым предоставляется доступ к образу + #опциональный параметр + #тип - массив целых чисел + #для удаления всех доступных аккаунтов, необходимо передать пустой массив + #accounts = [9, 5] + #мгновенное удаление #опциональный параметр, можно использовать перед удалением - #тип - булев тип + #тип - булев #permanently = true #причина удаления #опциональный параметр, можно использовать перед удалением #тип - строка #reason = "test" + + #наименование сетевого интерфейса для вашего компьютера с Linux, eth - встроенный, ens - pci слот + #опциональный параметр + #тип - строка + #network_interface_naming = "ens" } output "test" { diff --git a/samples/cloudbroker/resource_image_cdrom/main.tf b/samples/cloudbroker/image/resource_image_cdrom/main.tf similarity index 92% rename from samples/cloudbroker/resource_image_cdrom/main.tf rename to samples/cloudbroker/image/resource_image_cdrom/main.tf index 47e3607..de8015a 100644 --- a/samples/cloudbroker/resource_image_cdrom/main.tf +++ b/samples/cloudbroker/image/resource_image_cdrom/main.tf @@ -5,8 +5,8 @@ 1. Создавать образ 2. Редактировать образ 3. Удалять образ - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -44,7 +44,7 @@ resource "decort_cb_cdrom_image" "my_image" { #grid id образа #обязательный параметр - #тип - число + #тип - целое число gid = 212 #драйвера @@ -55,14 +55,14 @@ resource "decort_cb_cdrom_image" "my_image" { #поддержка hot resize #опциональный параметр - #тип - булев тип + #тип - булев #hot_resize = true #id аккаунта владельца образа #опциональный параметр #может быть использован как при создании, #так и при редактировании образа - #тип данных - число + #тип данных - целое число #account_id = 57252 #имя пользователя и пароль для загрузки бинарных данных @@ -73,9 +73,9 @@ resource "decort_cb_cdrom_image" "my_image" { #username_dl = "Valera1" #password_dl = "1231" - #id storage endpoint + #sep id #опциональный параметр, используется при создании - #тип - число + #тип - целое число #sep_id = 1206 #пул для создания образа @@ -91,37 +91,36 @@ resource "decort_cb_cdrom_image" "my_image" { #доступность образа #опциональный параметр, используется на уже созданном ресурсе - #тип - булево значение + #тип - булев #enabled = true #настройка доступа образа аккаунтам #опциональный параметр, используется на уже созданном ресурсе - #тип - массив чисел + #тип - массив целых чисел #пустой маасив - удаление всех доступов, если они были #shared_with = [28096, 57121] #установка computeci #опциональный параметр, используется на уже созданном ресурсе - #тип - число + #тип - целое число #чтобы сбросить, необходимо передать 0 #computeci_id = 1 #доступные стаки #опциональный параметр, используется на уже созданном ресурсе - #тип - массив чисел + #тип - массив целых чисел #для удаления всех доступных стаков, необходимо передать пустой массив #enabled_stacks = [9] #является ли образ загрузочным #опциональный параметр, используется на уже созданном ресурсе - #тип - булево значение + #тип - булев #bootable = true #мгновенное удаление #опциональный параметр, можно использовать перед удалением - #тип - булев тип + #тип - булев #permanently = true - } output "test" { diff --git a/samples/cloudbroker/image/resource_image_from_blank_compute/main.tf b/samples/cloudbroker/image/resource_image_from_blank_compute/main.tf new file mode 100644 index 0000000..e806755 --- /dev/null +++ b/samples/cloudbroker/image/resource_image_from_blank_compute/main.tf @@ -0,0 +1,155 @@ +/* +Ресурс образа из компьюта, созданного как blank позволяет: +1. Создавать +2. Редактировать +3. Удалять ресурс +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_image_from_blank_compute" "my_image" { + #ID виртуальной машины, созданной как blank + #используется для создания образа + #обязательный параметр + #тип - целое число + compute_id = 1234 + + #имя образа + #используется для обновления и создания образа + #обязательный параметр + #тип - строка + #при изменении - изменяет название созданного образа + name = "test_image_rename" + + #тип загрузки образа + #используется для создания образа + #обязательный параметр + #тип - строка + #возможные варианты: "bios" или "uefi" + boot_type = "bios" + + #тип образа + #используется для создания образа + #обязательный параметр + #тип - строка + #возможные варианты - "linux", "windows" + image_type = "linux" + + #имя пользователя для образа + #используется для обновления и создания образа + #опциональный параметр + #тип - строка + #username = "userx" + + #пароль для образа + #используется для обновления и создания образа + #опциональный параметр + #тип - строка + #password = "passx" + + #ID аккаунта + #используется для обновления и создания образа + #опциональный параметр + #тип - целое число + #account_id = 138 + + #sep id + #используется для создания образа + #опциональный параметр + #тип - целое число + #sep_id = 1 + + #название pool + #используется для создания образа + #опциональный параметр + #тип - строка + #pool_name = "pool" + + #поддержка hot resize + #используется для обновления и создания образа + #опциональный параметр + #тип - булев + #hot_resize = true + + #флаг для создания образа в асинхронном режиме + #опциональный параметр + #по умолчанию - false + #тип - булев + #async_mode = true + + #доступность образа + #опциональный параметр, используется на уже созданном ресурсе + #тип - булев + #enabled = true + + #является ли образ загрузочным + #опциональный параметр, используется на уже созданном ресурсе + #тип - булев + #bootable = true + + #настройка доступа образа аккаунтам + #опциональный параметр, используется на уже созданном ресурсе + #тип - массив целых чисел + #пустой массив - удаление всех доступов, если они были + #shared_with = [28096, 57121] + + #установка computeci + #опциональный параметр, используется на уже созданном ресурсе + #тип - целое число + #чтобы сбросить, необходимо передать 0 + #computeci_id = 1 + + #доступные стаки + #опциональный параметр, используется на уже созданном ресурсе + #тип - массив целых чисел + #для удаления всех доступных стаков, необходимо передать пустой массив + #enabled_stacks = [9] + + #аккаунты, которым предоставляется доступ к образу + #Используется для обновления и создания образа + #опциональный параметр + #тип - массив целых чисел + #для удаления всех доступных аккаунтов, необходимо передать пустой массив + #accounts = [9, 5] + + #мгновенное удаление + #опциональный параметр, можно использовать перед удалением + #тип - булев + #permanently = true + + #причина удаления + #опциональный параметр, можно использовать перед удалением + #тип - строка + #reason = "test" + + #наименование сетевого интерфейса для вашего компьютера с Linux, eth - встроенный, ens - pci слот + #используется для обновления образа + #опциональный параметр + #тип - строка + #network_interface_naming = "ens" +} + +output "test" { + value = decort_cb_image_from_blank_compute.my_image +} diff --git a/samples/cloudbroker/image/resource_image_from_platform_disk/main.tf b/samples/cloudbroker/image/resource_image_from_platform_disk/main.tf new file mode 100644 index 0000000..14789de --- /dev/null +++ b/samples/cloudbroker/image/resource_image_from_platform_disk/main.tf @@ -0,0 +1,168 @@ +/* +Ресурс образа из платформенного диска: +1. Создавать +2. Редактировать +3. Удалять ресурс +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_image_from_platform_disk" "my_image" { + #ID платформенного диска + #используется для создания образа + #обязательный параметр + #тип - целое число + disk_id = 1234 + + #имя образа + #используется для обновления и создания образа + #обязательный параметр + #тип - строка + #при изменении - изменяет название созданного образа + name = "test_image_rename" + + #тип загрузки образа + #используется для создания образа + #обязательный параметр + #тип - строка + #возможные варианты: "bios" или "uefi" + boot_type = "bios" + + #тип образа + #используется для создания образа + #обязательный параметр + #тип - строка + #возможные варианты - "linux", "windows" + image_type = "linux" + + #архитектура образа + #используется для создания образа + #обязательный параметр + #возможные значения - X86_64 or PPC64_LE + #тип - строка + architecture = "X86_64" + + #имя пользователя для образа + #используется для обновления и создания образа + #опциональный параметр + #тип - строка + #username = "userx" + + #пароль для образа + #используется для обновления и создания образа + #опциональный параметр + #тип - строка + #password = "passx" + + #ID аккаунта + #используется для обновления и создания образа + #опциональный параметр + #тип - целое число + #account_id = 138 + + #sep id + #используется для создания образа + #опциональный параметр + #тип - целое число + #sep_id = 1 + + #название pool + #используется для создания образа + #опциональный параметр + #тип - строка + #pool_name = "pool" + + #драйверы компьютов, подходящие для данного образа + #используется для создания образа + #опциональный параметр + #тип - массив строк + #drivers = ["KVM_X86"] + + #поддержка hot resize + #используется для обновления и создания образа + #опциональный параметр + #тип - булев + #hot_resize = true + + #является ли образ загрузочным + #опциональный параметр, используется на уже созданном ресурсе или при создании ресурса + #тип - булев + #bootable = true + + #флаг для создания образа в асинхронном режиме + #опциональный параметр + #по умолчанию - false + #тип - булев + #async_mode = true + + #доступность образа + #опциональный параметр, используется на уже созданном ресурсе + #тип - булев + #enabled = true + + #настройка доступа образа аккаунтам + #опциональный параметр, используется на уже созданном ресурсе + #тип - массив целых чисел + #пустой массив - удаление всех доступов, если они были + #shared_with = [28096, 57121] + + #установка computeci + #опциональный параметр, используется на уже созданном ресурсе + #тип - целое число + #чтобы сбросить, необходимо передать 0 + #computeci_id = 1 + + #доступные стаки + #опциональный параметр, используется на уже созданном ресурсе + #тип - массив целых чисел + #для удаления всех доступных стаков, необходимо передать пустой массив + #enabled_stacks = [9] + + #аккаунты, которым предоставляется доступ к образу + #Используется для обновления и создания образа + #опциональный параметр + #тип - массив целых чисел + #для удаления всех доступных аккаунтов, необходимо передать пустой массив + #accounts = [9, 5] + + #мгновенное удаление + #опциональный параметр, можно использовать перед удалением + #тип - булев + #permanently = true + + #причина удаления + #опциональный параметр, можно использовать перед удалением + #тип - строка + #reason = "test" + + #наименование сетевого интерфейса для вашего компьютера с Linux, eth - встроенный, ens - pci слот + #используется для обновления образа + #опциональный параметр + #тип - строка + #network_interface_naming = "ens" +} + +output "test" { + value = decort_cb_image_from_platform_disk.my_image +} diff --git a/samples/cloudbroker/resource_virtual_image/main.tf b/samples/cloudbroker/image/resource_virtual_image/main.tf similarity index 69% rename from samples/cloudbroker/resource_virtual_image/main.tf rename to samples/cloudbroker/image/resource_virtual_image/main.tf index 13e4bc6..e996d53 100644 --- a/samples/cloudbroker/resource_virtual_image/main.tf +++ b/samples/cloudbroker/image/resource_virtual_image/main.tf @@ -5,8 +5,8 @@ 1. Создавать образ 2. Редактировать образ 3. Удалять образ - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -39,64 +39,75 @@ resource "decort_cb_virtual_image" "my_image" { #id образа, на основе котрого будет создан виртуальный #обязательный параметр #может быть также использован при редактировании - #тип - число + #тип - целое число link_to = 6125 #id аккаунта владельца образа #опциональный параметр #может быть использован при редактировании образа - #тип данных - число + #тип данных - целое число #account_id = 57252 #является ли образ загрузочным - #опциональный параметр, используется на уже созданном ресурсе - #тип - булево значение + #опциональный параметр + #используется на уже созданном ресурсе + #тип - булев #bootable = true #поддержка hot resize #опциональный параметр - #тип - булев тип + #тип - булев #hot_resize = true - #имя пользователя и пароль - #опциональные параметры, - #могут быть использованы при редактировании образа + #имя пользователя + #опциональный параметр + #может быть использован при редактировании образа #тип - строка #username = "Valera" + + #пароль пользователя + #опциональный параметр + #может быть использован при редактировании образа + #тип - строка #password = "123" #доступность образа - #опциональный параметр, используется на уже созданном ресурсе - #тип - булево значение + #опциональный параметр + #используется на уже созданном ресурсе + #тип - булев #enabled = false #настройка доступа образа аккаунтам - #опциональный параметр, используется на уже созданном ресурсе - #тип - массив чисел + #опциональный параметр + #используется на уже созданном ресурсе #пустой маасив - удаление всех доступов, если они были + #тип - массив целых чисел #shared_with = [28096, 57121] #установка computeci #опциональный параметр, используется на уже созданном ресурсе - #тип - число #чтобы сбросить, необходимо передать 0 + #тип - целое число #computeci_id = 1 #доступные стаки #опциональный параметр, используется на уже созданном ресурсе - #тип - массив строк #для удаления всех доступных стаков, необходимо передать пустой массив + #тип - массив целых чисел #enabled_stacks = [9] #мгновенное удаление - #опциональный параметр, можно использовать перед удалением - #тип - булев тип + #опциональный параметр + #можно использовать перед удалением + #тип - булев #permanently = true #причина удаления - #опциональный параметр, можно использовать перед удалением + #опциональный параметр + #можно использовать перед удалением #тип - строка #reason = "test" + } output "test" { diff --git a/samples/cloudbroker/data_k8ci/main.tf b/samples/cloudbroker/k8s/data_k8ci/main.tf similarity index 96% rename from samples/cloudbroker/data_k8ci/main.tf rename to samples/cloudbroker/k8s/data_k8ci/main.tf index dad04d8..691d74d 100644 --- a/samples/cloudbroker/data_k8ci/main.tf +++ b/samples/cloudbroker/k8s/data_k8ci/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации о k8ci - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,11 +26,10 @@ provider "decort" { allow_unverified_ssl = true } - data "decort_cb_k8ci" "k8ci" { #id k8ci #обязательный параметр - #тип - число + #тип - целое число k8ci_id = 111 } diff --git a/samples/cloudbroker/data_k8ci_list/main.tf b/samples/cloudbroker/k8s/data_k8ci_list/main.tf similarity index 83% rename from samples/cloudbroker/data_k8ci_list/main.tf rename to samples/cloudbroker/k8s/data_k8ci_list/main.tf index 193443e..d9e7c32 100644 --- a/samples/cloudbroker/data_k8ci_list/main.tf +++ b/samples/cloudbroker/k8s/data_k8ci_list/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка k8ci - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,11 +26,10 @@ provider "decort" { allow_unverified_ssl = true } - data "decort_cb_k8ci_list" "k8cil" { #фильтр по id k8ci #опциональный параметр - #тип - число + #тип - целое число #by_id = 111 #фильтр по имени k8ci @@ -61,17 +59,23 @@ data "decort_cb_k8ci_list" "k8cil" { #исключить из результата недоступные k8ci #опциональный параметр - #тип - булево значение + #тип - булев #include_disabled = "true" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #size = 3 } diff --git a/samples/cloudbroker/data_k8ci_list_deleted/main.tf b/samples/cloudbroker/k8s/data_k8ci_list_deleted/main.tf similarity index 82% rename from samples/cloudbroker/data_k8ci_list_deleted/main.tf rename to samples/cloudbroker/k8s/data_k8ci_list_deleted/main.tf index b566e01..fc3c74b 100644 --- a/samples/cloudbroker/data_k8ci_list_deleted/main.tf +++ b/samples/cloudbroker/k8s/data_k8ci_list_deleted/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка удаленных k8ci - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,11 +26,10 @@ provider "decort" { allow_unverified_ssl = true } - data "decort_cb_k8ci_list_deleted" "k8cild" { #фильтр по id k8ci #опциональный параметр - #тип - число + #тип - целое число #by_id = 111 #фильтр по имени k8ci @@ -54,14 +52,20 @@ data "decort_cb_k8ci_list_deleted" "k8cild" { #тип - строка #network_plugin = "flannel" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #size = 3 } diff --git a/samples/cloudbroker/data_k8s/main.tf b/samples/cloudbroker/k8s/data_k8s/main.tf similarity index 96% rename from samples/cloudbroker/data_k8s/main.tf rename to samples/cloudbroker/k8s/data_k8s/main.tf index df2df33..d7aae23 100644 --- a/samples/cloudbroker/data_k8s/main.tf +++ b/samples/cloudbroker/k8s/data_k8s/main.tf @@ -2,19 +2,20 @@ Пример использования Получение информации о k8s кластере */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_k8s" "k8s" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 49304 } diff --git a/samples/cloudbroker/data_k8s_computes/main.tf b/samples/cloudbroker/k8s/data_k8s_computes/main.tf similarity index 76% rename from samples/cloudbroker/data_k8s_computes/main.tf rename to samples/cloudbroker/k8s/data_k8s_computes/main.tf index 402c16f..545dab0 100644 --- a/samples/cloudbroker/data_k8s_computes/main.tf +++ b/samples/cloudbroker/k8s/data_k8s_computes/main.tf @@ -1,6 +1,12 @@ +/* +Пример использования +Получение информации о компьютах k8s кластера +*/ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + /* terraform { required_providers { @@ -21,8 +27,9 @@ provider "decort" { } data "decort_cb_k8s_computes" "computes" { - # ID кластера - # Обязательный параметр + #id кластера + #обязательный параметр + #тип - целое число k8s_id = 999 } diff --git a/samples/cloudbroker/data_k8s_list/main.tf b/samples/cloudbroker/k8s/data_k8s_list/main.tf similarity index 81% rename from samples/cloudbroker/data_k8s_list/main.tf rename to samples/cloudbroker/k8s/data_k8s_list/main.tf index 2f6d419..5688118 100644 --- a/samples/cloudbroker/data_k8s_list/main.tf +++ b/samples/cloudbroker/k8s/data_k8s_list/main.tf @@ -2,19 +2,20 @@ Пример использования Получение списка доступных кластеров */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_k8s_list" "k8s_list" { #фильтр по id кластера #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени кластера @@ -43,17 +44,17 @@ data "decort_cb_k8s_list" "k8s_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #lb_id = 100 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #bservice_id = 100 #фильтр по статусу @@ -68,21 +69,27 @@ data "decort_cb_k8s_list" "k8s_list" { #включение удаленных k8s в результат #опциональный параметр - #тип - булев тип + #тип - булев #если не задан - выводятся все неудаленные данные - # include_deleted = true + #include_deleted = true + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные - # page = 1 + #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные - # size = 1 + #size = 1 } output "output_k8s_list" { diff --git a/samples/cloudbroker/data_k8s_list_deleted/main.tf b/samples/cloudbroker/k8s/data_k8s_list_deleted/main.tf similarity index 82% rename from samples/cloudbroker/data_k8s_list_deleted/main.tf rename to samples/cloudbroker/k8s/data_k8s_list_deleted/main.tf index 0f020bf..df7336a 100644 --- a/samples/cloudbroker/data_k8s_list_deleted/main.tf +++ b/samples/cloudbroker/k8s/data_k8s_list_deleted/main.tf @@ -2,19 +2,20 @@ Пример использования Получение списка удаленных кластеров */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_k8s_list_deleted" "k8s_list_deleted" { #фильтр по id кластера #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени кластера @@ -43,17 +44,17 @@ data "decort_cb_k8s_list_deleted" "k8s_list_deleted" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #lb_id = 100 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #bservice_id = 100 #фильтр по техническому статусу @@ -61,15 +62,21 @@ data "decort_cb_k8s_list_deleted" "k8s_list_deleted" { #тип - строка #tech_status = "STOPPED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudbroker/data_k8s_wg/main.tf b/samples/cloudbroker/k8s/data_k8s_wg/main.tf similarity index 93% rename from samples/cloudbroker/data_k8s_wg/main.tf rename to samples/cloudbroker/k8s/data_k8s_wg/main.tf index e9039b1..396a7cd 100644 --- a/samples/cloudbroker/data_k8s_wg/main.tf +++ b/samples/cloudbroker/k8s/data_k8s_wg/main.tf @@ -2,19 +2,20 @@ Пример использования Получение информации о k8s кластере */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,12 +29,12 @@ provider "decort" { data "decort_cb_k8s_wg" "k8s_wg" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 49304 #id группы воркеров #обязательный параметр - #тип - число + #тип - целое число wg_id = 43329 } diff --git a/samples/cloudbroker/data_k8s_wg_cloud_init/main.tf b/samples/cloudbroker/k8s/data_k8s_wg_cloud_init/main.tf similarity index 94% rename from samples/cloudbroker/data_k8s_wg_cloud_init/main.tf rename to samples/cloudbroker/k8s/data_k8s_wg_cloud_init/main.tf index e9583e5..aeeaf83 100644 --- a/samples/cloudbroker/data_k8s_wg_cloud_init/main.tf +++ b/samples/cloudbroker/k8s/data_k8s_wg_cloud_init/main.tf @@ -2,19 +2,20 @@ Пример использования Получение информации о мета данных рабочей группы k8s кластера */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,12 +29,12 @@ provider "decort" { data "decort_cb_k8s_wg_cloud_init" "wg_cloud_init" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 977 #id группы воркеров #обязательный параметр - #тип - число + #тип - целое число wg_id = 2110 } diff --git a/samples/cloudbroker/data_k8s_wg_list/main.tf b/samples/cloudbroker/k8s/data_k8s_wg_list/main.tf similarity index 87% rename from samples/cloudbroker/data_k8s_wg_list/main.tf rename to samples/cloudbroker/k8s/data_k8s_wg_list/main.tf index 364ea52..f54e273 100644 --- a/samples/cloudbroker/data_k8s_wg_list/main.tf +++ b/samples/cloudbroker/k8s/data_k8s_wg_list/main.tf @@ -1,20 +1,21 @@ /* Пример использования -Получение списка доступных групп воркеров в кластере +Получение списка доступных рабочих групп в кластере */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - +/* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } - +*/ provider "decort" { authenticator = "decs3o" @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_k8s_wg_list" "k8s_wg_list" { #id кластера #обязательный параметр - #тип - число + #тип - целое число k8s_id = 49304 } diff --git a/samples/cloudbroker/resource_k8ci/main.tf b/samples/cloudbroker/k8s/resource_k8ci/main.tf similarity index 86% rename from samples/cloudbroker/resource_k8ci/main.tf rename to samples/cloudbroker/k8s/resource_k8ci/main.tf index 472c299..00c483a 100644 --- a/samples/cloudbroker/resource_k8ci/main.tf +++ b/samples/cloudbroker/k8s/resource_k8ci/main.tf @@ -5,8 +5,8 @@ 1. Создавать k8ci 2. Редактировать k8ci 3. Удалять k8ci - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,14 +14,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -35,56 +34,56 @@ resource "decort_cb_k8ci" "k8ci" { #имя k8ci #обязательный параметр #тип - строка - name = "test" + name = "test" #тег версии #обязательный параметр #тип - строка - version = "1.1.1" + version = "1.1.1" #тип master driver #обязательный параметр #тип - строка - master_driver = "KVM_X86" + master_driver = "KVM_X86" #тип worker driver #обязательный параметр #тип - строка - worker_driver = "KVM_X86" - + worker_driver = "KVM_X86" + #максимальное число master компутов #обязательный параметр - #тип - число + #тип - целое число max_master_count = 1 #максимальное число worker компутов #обязательный параметр - #тип - число + #тип - целое число max_worker_count = 1 #id образа для master #обязательный параметр - #тип - число + #тип - целое число master_image_id = 4 #id образа для worker #обязательный параметр - #тип - число + #тип - целое число worker_image_id = 4 #network plugins #обязательный параметр - #тип - список строк + #тип - массив строк network_plugins = ["flannel"] #доступность k8ci #опциональный параметр - #тип - булево значение + #тип - булев #enabled = false #флаг для моментального удаления k8ci #опциональный параметр - #тип - булевый + #тип - булев #permanently = true #описание @@ -94,8 +93,9 @@ resource "decort_cb_k8ci" "k8ci" { #доступность k8ci другим аккаунтам #опциональный параметр - #тип - список чисел + #тип - массив целых чисел #shared_with = [1111] + } output "test" { diff --git a/samples/cloudbroker/k8s/resource_k8s_cp/main.tf b/samples/cloudbroker/k8s/resource_k8s_cp/main.tf new file mode 100644 index 0000000..15264a6 --- /dev/null +++ b/samples/cloudbroker/k8s/resource_k8s_cp/main.tf @@ -0,0 +1,186 @@ +/* +Пример использования +Ресурса k8s +Ресурс позволяет: +1. Создавать кластер +2. Редактировать кластер +3. Удалять кластер +4. Настроить мастер-узел +5. Изменить кол-во ВМ в мастер-узле +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + oauth2_url = "https://sso.digitalenergy.online" + controller_url = "https://mr4.digitalenergy.online" + app_id = "" + app_secret = "" +} + +resource "decort_cb_k8s_cp" "cp" { + #название кластера + #обязательный параметр + #тип - строка + name = "k8s-cp" + + #k8sCI ID + #обязательный параметр + #тип - целое число + k8sci_id = 55 + + #плагин сети + #обязательный параметр + #возможные значения - "flannel", "weavenet", "calico" + #тип - строка + network_plugin = "flannel" + + #id ресурсной группы + #обязательный параметр + #тип - целое число + rg_id = 1387 + + #кол-во ядер мастер-узла + #опциональный параметр + #тип - целое число + cpu = 2 + + #объем RAM мастер-узла + #опциональный параметр + #тип - целое число + ram = 2048 + + #кол-во ВМ мастер-узла (1, 3 или 5) + #опциональный параметр + #тип - целое число + num = 1 + + #размер диска мастер-узла + #опциональный параметр + #тип - целое число + disk = 10 + + #описание кластера + #опциональный параметр + #тип - строка + desc = "" + + #id extnet + #опциональный параметр + #тип - целое число + extnet_id = 0 + + #id vins + #опциональный параметр + #тип - целое число + vins_id = 1234 + + #sep ip + #опциональный параметр + #тип - целое число + sep_id = 0 + + #название пула + #опциональный параметр + #тип - строка + sep_pool = "pool" + + #старт/стоп кластера + #опциональный параметр + #тип - булев + start = true + + #включить/отключить кластер + #опциональный параметр + #тип - булев + enabled = true + + #удалить кластер безвозвратно + #опциональный параметр + #тип - булев + permanently = true + + #восстановить кластер из корзины + #опциональный параметр + #тип - булев + restore = true + + #создать кластер с/без балансировщика нагрузки + #опциональный параметр + #тип - булев + with_lb = true + + #позволяет создать схему отказоустройчивой LB + #опциональный параметр + #тип - булев + ha_mode = true + + #дополнительные SAN (Subject Alternative Names) для использования в процессе автоматического выписывания сертификата Кластера Kubernetes; + #возможность взаимодействовать с кластером по FQDN + #параметр получает список строк – IP-адреса и/или DNS (по формату RFC 1123 c поддержкой wildcard) + #опциональный параметр + #тип - массив строк + additional_sans = ["192.168.201.0","192.168.201.1"] + + #используется для определения настроек и действий, которые должны быть выполнены перед запуском любого другого компонента в кластере + #это позволяет вам настраивать такие вещи, как регистрация node, настройка network и другие задачи инициализации + #опциональный параметр + #тип - строка + init_config = "{JSON string}" + + #используется для определения глобальных настроек и конфигураций для всего кластера + #он включает в себя такие параметры, как имя кластера, настройки DNS, методы аутентификации и другие конфигурации в масштабах кластера + #опциональный параметр + #тип - строка + cluster_config = "{JSON string}" + + #используется для настройки поведения и параметров Kubelet, который является агентом primary node, запускаемым на каждом node кластера + #он включает в себя такие параметры, как IP-адрес node, распределение ресурсов, политики удаления модулей и другие конфигурации, специфичные для Kubelet + #опциональный параметр + #тип - строка + kubelet_config = "{JSON string}" + + #используется для настройки поведения и параметров присоединения node к кластеру + #он включает в себя такие параметры, как режим прокси-сервера, диапазоны IP-адресов кластера и другие конфигурации, специфичные для Kube-proxy + #опциональный параметр + #тип - строка + kube_proxy_config = "{JSON string}" + + #используется для настройки поведения и параметров присоединения node к кластеру + #он включает в себя такие параметры, как cluster's control plane endpoint, токен и ключ сертификата + #опциональный параметр + #тип - строка + join_config = "{JSON string}" + + #при создании кластере использовать подключение только к сети ExtNet + #опциональный параметр + #тип - булев + extnet_only = true + + #добавить ssl-сертификат в формате x509 pem + #опциональный параметр + #тип - файл с форматом в виде .crt + oidc_cert = file("ca.crt") + + #пользовательские значения sysctl для LB + #опциональный параметр + #тип - массив мап + lb_sysctl_params = [{text = "1", text = "some"}] +} + +output "cp_out" { + value = decort_cb_k8s_cp.cp +} diff --git a/samples/cloudapi/resource_k8s_wg/initconfig.tftpl b/samples/cloudbroker/k8s/resource_k8s_wg/initconfig.tftpl similarity index 100% rename from samples/cloudapi/resource_k8s_wg/initconfig.tftpl rename to samples/cloudbroker/k8s/resource_k8s_wg/initconfig.tftpl diff --git a/samples/cloudbroker/resource_k8s_wg/main.tf b/samples/cloudbroker/k8s/resource_k8s_wg/main.tf similarity index 71% rename from samples/cloudbroker/resource_k8s_wg/main.tf rename to samples/cloudbroker/k8s/resource_k8s_wg/main.tf index 5a04ebd..5a3ec46 100644 --- a/samples/cloudbroker/resource_k8s_wg/main.tf +++ b/samples/cloudbroker/k8s/resource_k8s_wg/main.tf @@ -1,3 +1,7 @@ +/* +Пример использования +Получение информации о группе воркеров кластера Kubernetes(k8s) +*/ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, @@ -19,17 +23,15 @@ provider "decort" { controller_url = "https://ds1.digitalenergy.online" #oauth2_url = oauth2_url = "https://sso.digitalenergy.online" - #app_id = - #app_secret = allow_unverified_ssl = true } - resource "decort_cb_k8s_wg" "wg" { #id экземпляра k8s #обязательный параметр - #тип - число - k8s_id = 1234 //это значение должно быть и результат вызова decort_cb_k8s.cluster.k8s_id + #это значение должно быть и результат вызова decort_cb_k8s.cluster.k8s_id + #тип - целое число + k8s_id = 1234 #имя worker group #обязательный параметр @@ -38,27 +40,27 @@ resource "decort_cb_k8s_wg" "wg" { #количество worker node для создания #опциональный параметр - #тип - число - #по - умолчанию - 1 + #тип - целое число + #по умолчанию - 1 num = 2 #количество cpu для 1 worker node #опциональный параметр - #тип - число - #по - умолчанию - 1 + #тип - целое число + #по умолчанию - 1 cpu = 1 #количество RAM для одной worker node в Мбайтах #опциональный параметр - #тип - число - #по-умолчанию - 1024 + #тип - целое число + #по умолчанию - 1024 ram = 1024 #размер загрузочного диска для worker node, в Гбайтах #опциональный параметр - #тип - число - #по - умолчанию - 0 + #по умолчанию - 0 #если установлен параметр 0, то размер диска будет равен размеру образа + #тип - целое число disk = 10 #список строк с labels для worker группы, в формате: ["label1=value1", "label2=value2"] @@ -66,33 +68,33 @@ resource "decort_cb_k8s_wg" "wg" { #тип - массив строк labels = ["label1=value1", "label2=value2"] - #Список строк с annotations для worker группы, в формате: ["key1=value1", "key2=value2"] + #список строк с annotations для worker группы, в формате: ["key1=value1", "key2=value2"] #опциональный параметр #тип - массив строк annotations = ["key1=value1", "key2=value2"] - #Список строк с taints для worker группы, в формате: ["key1=value1:NoSchedule", "key2=value2:NoExecute"] + #список строк с taints для worker группы, в формате: ["key1=value1:NoSchedule", "key2=value2:NoExecute"] #опциональный параметр #тип - массив строк taints = ["key1=value1", "key2=value2"] - #ID СХД для создания загрузочных дисков для Worker-групп по умолчанию. Использует sepId образа, если не указан. + #id СХД для создания загрузочных дисков для Worker-групп по умолчанию. Использует sepId образа, если не указан. #опциональный параметр - #тип - число + #тип - целое число worker_sep_id = 1 - #Пул для хранения Workers. Если не заполнить, будет выбран системой + #пул для хранения Workers. Если не заполнить, будет выбран системой #опциональный параметр - #тип - число + #тип - целое число worker_sep_pool = "worker_pool" - #Перечень аргументов для cloud-init для виртуальных машин worker групп + #перечень аргументов для cloud-init для виртуальных машин worker групп #опциональный параметр - #тип - файл + #тип - файл в формате YAML #используется при создании и обновлении ресурса cloud_init = file("initconfig.tftpl") -} +} output "test_wg" { value = decort_cb_k8s_wg.wg diff --git a/samples/cloudbroker/data_kvmvm/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm/main.tf similarity index 82% rename from samples/cloudbroker/data_kvmvm/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm/main.tf index ff768b3..a57a4b2 100644 --- a/samples/cloudbroker/data_kvmvm/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных о compute (виртуальной машине). */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,16 +28,16 @@ provider "decort" { data "decort_cb_kvmvm" "comp" { #получение информации по идентификатору машины - compute_id - - # id виртуальной машины - # обязательный параметр - # тип - число + #id виртуальной машины + #обязательный параметр + #тип - целое число compute_id = 11346 - # прична запроса - # опциональный параметр - # тип - строка + #прична запроса + #опциональный параметр + #тип - строка reason = "test" + } output "test" { diff --git a/samples/cloudbroker/data_kvmvm_affinity_relations/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_affinity_relations/main.tf similarity index 97% rename from samples/cloudbroker/data_kvmvm_affinity_relations/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_affinity_relations/main.tf index c8ce004..735309a 100644 --- a/samples/cloudbroker/data_kvmvm_affinity_relations/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_affinity_relations/main.tf @@ -7,12 +7,11 @@ #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,8 +29,9 @@ provider "decort" { data "decort_cb_kvmvm_affinity_relations" "aff_rel" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 48 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_audits/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_audits/main.tf similarity index 96% rename from samples/cloudbroker/data_kvmvm_audits/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_audits/main.tf index ddca0a2..f2336ad 100644 --- a/samples/cloudbroker/data_kvmvm_audits/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_audits/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,8 +29,9 @@ provider "decort" { data "decort_cb_kvmvm_audits" "kvmvm_audits" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_boot_order_get/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_boot_order_get/main.tf similarity index 96% rename from samples/cloudbroker/data_kvmvm_boot_order_get/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_boot_order_get/main.tf index aa1017e..7f8ff2e 100644 --- a/samples/cloudbroker/data_kvmvm_boot_order_get/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_boot_order_get/main.tf @@ -7,12 +7,11 @@ #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,8 +29,9 @@ provider "decort" { data "decort_cb_kvmvm_boot_order_get" "boot_order" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое вчисло compute_id = 48 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_get_audits/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_get_audits/main.tf similarity index 94% rename from samples/cloudbroker/data_kvmvm_get_audits/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_get_audits/main.tf index f55b58d..cdbbcc2 100644 --- a/samples/cloudbroker/data_kvmvm_get_audits/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_get_audits/main.tf @@ -1,18 +1,17 @@ /* Пример использования -Получение данных об аудитах compute (виртулаьной машине) +Получение данных об аудитах compute (виртулаьной машины) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,13 +29,14 @@ provider "decort" { data "decort_cb_kvmvm_get_audits" "kvmvm_get_audits" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 #причина запроса #опциональный параметр #тип - строка #reason = "test" + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_get_console_url/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_get_console_url/main.tf similarity index 91% rename from samples/cloudbroker/data_kvmvm_get_console_url/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_get_console_url/main.tf index 9c95022..7529366 100644 --- a/samples/cloudbroker/data_kvmvm_get_console_url/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_get_console_url/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение url compute (виртулаьной машины) +Получение url compute (виртуальной машины) */ #Расскомментируйте этот код, @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,8 +29,9 @@ provider "decort" { data "decort_cb_kvmvm_get_console_url" "kvmvm_get_console_url" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_get_log/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_get_log/main.tf similarity index 96% rename from samples/cloudbroker/data_kvmvm_get_log/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_get_log/main.tf index a889e61..543008c 100644 --- a/samples/cloudbroker/data_kvmvm_get_log/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_get_log/main.tf @@ -6,17 +6,17 @@ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -29,13 +29,14 @@ provider "decort" { data "decort_cb_kvmvm_get_log" "kvmvm_get_log" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 #путь до log файла #обязательный параметр #тип - строка path = "/var/log/file.log" + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_list/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_list/main.tf similarity index 84% rename from samples/cloudbroker/data_kvmvm_list/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_list/main.tf index 5c94a7e..fa10f0e 100644 --- a/samples/cloudbroker/data_kvmvm_list/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_list/main.tf @@ -1,6 +1,6 @@ /* Пример использования -Получение данных об списке compute (виртуальных машин) +Получение данных о списке compute (виртуальных машин) */ #Расскомментируйте этот код, @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +28,7 @@ provider "decort" { data "decort_cb_kvmvm_list" "compute_list" { #фильтр по id ВМ #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени ВМ @@ -38,7 +38,7 @@ data "decort_cb_kvmvm_list" "compute_list" { #id аккаунта для получения списка ВМ #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по имени ресурсной группы @@ -48,7 +48,7 @@ data "decort_cb_kvmvm_list" "compute_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -73,32 +73,34 @@ data "decort_cb_kvmvm_list" "compute_list" { #фильтр по id extnet #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 #флаг влючения в результат удаленных балансироващиков нагрузки #опциональный параметр - #тип - булев тип - #значение по-умолчанию - false #если не задан - выводятся все доступные неудаленные балансировщики + #значение по-умолчанию - false + #тип - булев #includedeleted = true + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 1 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 1 - #Включить в список вывода ВМ, принадлежащие k8s кластерам (при значении параметра true) - #опциональный параметр - #bool (default = false) - #ignore_k8s = true } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_list_deleted/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_list_deleted/main.tf similarity index 85% rename from samples/cloudbroker/data_kvmvm_list_deleted/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_list_deleted/main.tf index 0c38124..3992b73 100644 --- a/samples/cloudbroker/data_kvmvm_list_deleted/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_list_deleted/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_kvmvm_list_deleted" "compute_list" { #фильтр по id виртуальной машины #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени виртуальной машины @@ -39,7 +39,7 @@ data "decort_cb_kvmvm_list_deleted" "compute_list" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #account_id = 100 #фильтр по имени ресурсной группы @@ -49,7 +49,7 @@ data "decort_cb_kvmvm_list_deleted" "compute_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -69,25 +69,27 @@ data "decort_cb_kvmvm_list_deleted" "compute_list" { #фильтр по id extNet #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 - #Включить в список вывода ВМ, принадлежащие k8s кластерам (при значении параметра true) - #опциональный параметр - #bool (default = false) - #ignore_k8s = true } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_migrate_storage_info/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_migrate_storage_info/main.tf similarity index 96% rename from samples/cloudbroker/data_kvmvm_migrate_storage_info/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_migrate_storage_info/main.tf index 44dad89..6961c23 100644 --- a/samples/cloudbroker/data_kvmvm_migrate_storage_info/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_migrate_storage_info/main.tf @@ -1,18 +1,17 @@ /* Пример использования Получение информации о последней (включая текущую) миграции хранилища. -*/ +*/ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,8 +29,9 @@ provider "decort" { data "decort_cb_kvmvm_migrate_storage_info" "info" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 48 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_pci_device_list/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_pci_device_list/main.tf similarity index 75% rename from samples/cloudbroker/data_kvmvm_pci_device_list/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_pci_device_list/main.tf index 0bdba2f..c337bae 100644 --- a/samples/cloudbroker/data_kvmvm_pci_device_list/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_pci_device_list/main.tf @@ -6,13 +6,12 @@ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,35 +29,47 @@ provider "decort" { data "decort_cb_kvmvm_pci_device_list" "pci_device_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 100 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по id устройства #опциональный параметр - #тип - число + #тип - целое число #device_id = 100 + #фильтр по имени устройства + #опциональный параметр + #тип - строка + #name = "test" + #фильтр по статусу #опциональный параметр #тип - строка #status = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 1 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 1 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_pfw_list/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_pfw_list/main.tf similarity index 97% rename from samples/cloudbroker/data_kvmvm_pfw_list/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_pfw_list/main.tf index f9d1622..fef83c6 100644 --- a/samples/cloudbroker/data_kvmvm_pfw_list/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_pfw_list/main.tf @@ -7,12 +7,11 @@ #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,13 +29,14 @@ provider "decort" { data "decort_cb_kvmvm_pfw_list" "kvmvm_pfw_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 48 #причина запроса #опциональный параметр #тип - строка reason = "test" + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_snapshot_list/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_snapshot_list/main.tf similarity index 97% rename from samples/cloudbroker/data_kvmvm_snapshot_list/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_snapshot_list/main.tf index f090001..2fecc38 100644 --- a/samples/cloudbroker/data_kvmvm_snapshot_list/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_snapshot_list/main.tf @@ -7,12 +7,11 @@ #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,8 +29,9 @@ provider "decort" { data "decort_cb_kvmvm_snapshot_list" "kvmvm_snapshot_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 48 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_snapshot_usage/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_snapshot_usage/main.tf similarity index 86% rename from samples/cloudbroker/data_kvmvm_snapshot_usage/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_snapshot_usage/main.tf index 8348ff1..7273313 100644 --- a/samples/cloudbroker/data_kvmvm_snapshot_usage/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_snapshot_usage/main.tf @@ -1,18 +1,17 @@ /* Пример использования -Получение настояего размера снимка ВМ (виртуальной машины) в хранилище. +Получение настоящего размера снимка ВМ (виртуальной машины) в хранилище. */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,13 +29,14 @@ provider "decort" { data "decort_cb_kvmvm_snapshot_usage" "snp_usage" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 48 #label снимка #опциональный параметр #тип - строка label = "test" + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_user_list/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_user_list/main.tf similarity index 94% rename from samples/cloudbroker/data_kvmvm_user_list/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_user_list/main.tf index c72565f..06cb064 100644 --- a/samples/cloudbroker/data_kvmvm_user_list/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_user_list/main.tf @@ -1,18 +1,17 @@ /* Пример использования -Получение данных об юзерах compute (виртулаьной машины) +Получение данных об юзерах compute (виртуальной машины) */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,8 +29,9 @@ provider "decort" { data "decort_cb_kvmvm_user_list" "kvmvm_user_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 10154 + } output "output" { diff --git a/samples/cloudbroker/data_kvmvm_vgpu_list/main.tf b/samples/cloudbroker/kvmvm/data_kvmvm_vgpu_list/main.tf similarity index 81% rename from samples/cloudbroker/data_kvmvm_vgpu_list/main.tf rename to samples/cloudbroker/kvmvm/data_kvmvm_vgpu_list/main.tf index 0ee676a..659fcb3 100644 --- a/samples/cloudbroker/data_kvmvm_vgpu_list/main.tf +++ b/samples/cloudbroker/kvmvm/data_kvmvm_vgpu_list/main.tf @@ -7,12 +7,11 @@ #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером /* - terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,12 +28,12 @@ provider "decort" { data "decort_cb_kvmvm_vgpu_list" "vgpu_list" { #id виртуальной машины #обязательный параметр - #тип - число + #тип - целое число compute_id = 100 #фильтр по id графического процессора #опциональный параметр - #тип - число + #тип - целое число #gpu_id = 100 #фильтр по типу графического процессора @@ -49,20 +48,27 @@ data "decort_cb_kvmvm_vgpu_list" "vgpu_list" { #фильтр "включая удаленные графические процессоры" #опциональный параметр - #тип - булев тип - #includedeleted = "false" + #тип - булев + #includedeleted = false + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" #номер страницы для отображения #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #page = 1 #размер страницы #опциональный параметр - #тип - число #если не задан - выводятся все доступные данные + #тип - целое число #size = 1 + } output "output" { diff --git a/samples/cloudbroker/resource_kvmvm/initconfig.tftpl b/samples/cloudbroker/kvmvm/resource_kvmvm/initconfig.tftpl similarity index 100% rename from samples/cloudbroker/resource_kvmvm/initconfig.tftpl rename to samples/cloudbroker/kvmvm/resource_kvmvm/initconfig.tftpl diff --git a/samples/cloudbroker/kvmvm/resource_kvmvm/main.tf b/samples/cloudbroker/kvmvm/resource_kvmvm/main.tf new file mode 100644 index 0000000..a3c228c --- /dev/null +++ b/samples/cloudbroker/kvmvm/resource_kvmvm/main.tf @@ -0,0 +1,463 @@ +/* +Пример использования +Работа с ресурсом kvmvm (compute) +Ресурс позволяет: +1. Создавать compute +2. Редактировать compute +3. Удалять compute +*/ +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + version = "" + source = "basis/decort/decort" + } + } +} +*/ + + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_kvmvm" "comp" { + #имя compute + #обязательный параметр + #мб изменен + #тип - строка + name = "test-tf-compute-update-new" + + #id resource group + #обязательный параметр + #тип - целое число + rg_id = 1111 + + #тип драйвера для compute + #обязательный параметр + #тип - строка + driver = "KVM_X86" + + #число cpu + #обязательный параметр + #тип - целое число + cpu = 1 + + #кол-во оперативной памяти, МБ + #обязательный параметр + #тип - целое число + ram = 2048 + + #id образа диска для создания compute + #опциональный параметр + #тип - целое число + #image_id = 111 + + #Если значение равно True, параметры image_id, boot_disk_size, sep_id, pool игнорируются, и компьютер создается без загрузочного диска в остановленном состоянии + #опциональный параметр + #тип - булев + #without_boot_disk = true + + #размер загрузочного диска + #опциональный параметр + #тип - целое число + #boot_disk_size = 20 + + #ID сепа для boot диска + #опциональный параметр + #тип - целое число + #sep_id = 1 + + #Название пула + #опциональный параметр + #тип - строка + #pool = "data02" + + #конфигурация cloud init + #опциональный параметр + #тип - файл в формате JSON/YAML + #cloud_init = file("initconfig.tftpl") + + #описание compute + #опциональный параметр + #тип - строка + #description = "test update description in tf words update" + + #stack id + #опциональный параметр + #тип - целое число + #stack_id = 1 + + #id образа CD-ROM для загрузки + #используется при изменении ресурса, при повторном старте вм + #опциональный параметр + #тип - целое число + #alt_boot_id = 1 + + #необходимость выравнивать ВМ по NUMA + #опциональный параметр + #тип - строка + #возможные значения - "none, "strict", "loose" + #значение по умолчанию - "none" + #numa_affinity = "loose" + + #необходимость запускать ВМ на выделенных CPU ядрах + #опциональный параметр + #тип - булев + #значение по умолчанию - false + #cpu_pin = true + + #необходимость использовать для выделения RAM виртуальной машины Huge Pages + #опциональный параметр + #тип - булев + #значение по умолчанию - false + #hp_backed = true + + #Создание и добавление диска дял compute + #опциональный параметр + #тип - список дисков + #disks { + #Имя диска + #Обязательный для диска параметр + #Тип - строка + #disk_name = "disk_name" + + #Размер диска + #Обязательный для диска параметр + #тип - целое число + #size = 5 + + #Тип диска + #опциональный параметр + #тип - строка + #disk_type = "D" + + #опциональный параметр + #тип - целое число + #sep_id = 1 + + #Название пула + #опциональный параметр + #тип - строка + #pool = "data01" + + #список node + #опциональный параметр + #тип - массив целых чисел + #node_ids = [10,11] + + #Описание диска + #опциональный параметр + #тип - строка + #desc = "" + + #Айди образа + #опциональный параметр + #image_id = 378 + + #Флаг для удаления диска + #опциональный параметр + #тип - булев + #permanently = false + #} + + #правила affinity + #опциональный параметр + #может быть один, несколько или ни одного блока + #тип - блок + #affinity_rules { + #тип правила + #возможные значения - compute или node + #обязательный параметр + #тип - строка + #topology = "compute" + + #строгость правила + #возможные значения - RECOMMENDED и REQUIRED + #обязательный параметр + #тип - строка + #policy = "RECOMMENDED" + + #режим проверки + #возможные значения - ANY, EQ, NE + #обязательный параметр + #тип - строка + #mode = "ANY" + + #ключ правила + #обязательный параметр + #тип - строка + #key = "testkey" + + #ключ правила + #необязательный параметр + #тип - строка + #value = "testvalue" + #} + + #правила anti-affinity + #опциональный параметр + #может быть один, несколько или ни одного блока + #тип - блок + #anti_affinity_rules { + #тип правила + #возможные значения - compute или node + #обязательный параметр + #тип - строка + #topology = "compute" + + #строгость правила + #возможные значения - RECOMMENDED и REQUIRED + #обязательный параметр + #тип - строка + #policy = "RECOMMENDED" + + #режим проверки + #возможные значения - ANY, EQ, NE + #обязательный параметр + #тип - строка + #mode = "ANY" + + #ключ правила + #обязательный параметр + #тип - строка + #key = "testkey" + + #ключ правила + #необязательный параметр + #тип - строка + #value = "testvalue" + #} + + #установка метки для вм + #опциональный параметр + #тип - строка + #affinity_label = "test4" + + + #наименование системы + #опциональный параметр + #используется при создании вм + #по умолчанию - не задан + #тип - строка + #is="" + + #назначение вм + #опциональный параметр + #используется при создании вм + #по умолчанию - не задан + #тип - строка + #ipa_type = "" + + #Id экстра дисков + #опциональный параметр + #тип - список чисел + #extra_disks = [1234, 4322, 1344] + + #Управление XML виртуальной машины + #опциональный параметр + #тип - строка (json-encoded) + #custom_fields = "{`key`:`value`}" + + #Описание необходимости выполнения действия + #опциональный параметр + #тип - строка + #reason = "need" + + #Присоеденения сетей и удаление сетей в компьюте + #опциональный параметр + #тип - блок + #network { + #Тип сети VINS/EXTNET (для любого драйвера) и VFNIC (для KVM_X86) + #Обязательный параметр + #тип - строка + #net_type = "VINS" + + #ID сети + #Обязательный параметр + #тип - целое число + #net_id = 1234 + + #IP адрес входящий в сеть + #опциональный параметр + #тип - строка + #ip_address = "127.0.0.1" + #} + + #добавление и удаление тэгов + #опциональный параметр + #тип - блок + #tags { + #Ключ для тэга + #Обязательный параметр + #тип - строка + #key = "key" + + #Значения тэга + #Обязательный параметр + #тип - строка + #value = "value" + #} + + #добавление и удаление port forwarding + #опциональный параметр + #тип - блок + #port_forwarding { + #номер внешнего начального порта для правила + #Обязательный параметр + #тип - целое число + #public_port_start = 2023 + + #номер внешнего последнего порта для правила + #опциональный параметр + #тип - целое число + #по умолчанию - -1 + #public_port_end = 2023 + + #номер внутреннего базового порта + #Обязательный параметр + #тип - целое число + #local_port = 80 + + #сетевой протокол + #Обязательный параметр + #тип - строка + #proto = "tcp" + #} + + #предоставить/забрать пользователю доступ к компьюту + #опциональный параметр + #тип - блок + #user_access { + #Имя юзера, которому предоставляем доступ + #Обязательный параметр + #тип - строка + #username = "some@decs3o" + + #Права: 'R' - только на чтение, 'RCX' - чтение/запись, 'ARCXDU' - админ + #Обязательный параметр + #тип - строка + #access_type = "ARCXDU" + #} + + #Создать/удалить снапшот компьюта + #опциональный параметр + #тип - блок + #snapshot { + #Лейбл снапшота + #Обязательный параметр + #тип - строка + #label = "label1" + #} + + #Rollback на нужный снапшот + #опциональный параметр + #Не имеет смысла при отсутсвии снапшотов + #тип - блок + #rollback { + #Лейбл снапшота + #Обязательный параметр + #тип - строка + #label = "label1" + #} + + #Вставить/удалить СD rom + #опциональный параметр + #Максимальное кол-во - 1 + #тип - блок + #cd { + #ID образа диска CD rom + #Обязательный параметр + #тип - целое число + #cdrom_id = 344 + #} + + #Добавить компьют на стэк + #опциональный параметр + #тип - булев + #pin_to_stack = true + + #id stack для добавления компьюта на этот стэк + #опциональный параметр + #тип - целое число + #target_stack_id = 1 + + #Флаг для принужительного добавления компьюта на стэк + #опциональный параметр + #тип - булев + #force_pin = true + + #Флаг доступности компьюта для проведения с ним операций + #опциональный параметр + #тип - булев + #enabled = true + + #pause/resume компьюта + #опциональный параметр + #тип - булев + #pause = true + + #сделать компьют заново + #опциональный параметр + #тип - булев + #reset = true + + #восстановить удаленный компьют из корзины + #опциональный параметр + #тип - булев + #restore = true + + #флаг для редеплоя компьюта + #опциональный параметр + #тип - булев + #auto_start = true + + #флаг для редеплоя компьюта + #опциональный параметр + #тип - булев + #force_stop = true + + #флаг для предоставления дисков из node + #опциональный параметр + #тип - булев + #по умолчанию - true + #depresent = true + + #флаг для ресайза компьюта + #опциональный параметр + #тип - булев + #force_resize = true + + #поле для редеплоя компьюта + #опциональный параметр + #тип - строка + #data_disks = "KEEP" + + #запуск/стоп компьюта + #опциональный параметр + #тип - булев + #started = true + + #detach диска при удалении компьюта + #опциональный параметр + #тип - булев + #detach_disks = true + + #Флаг для удаления компьюта + #опциональный параметр + #тип - булев + #permanently = false +} + +output "test" { + value = decort_cb_kvmvm.comp +} diff --git a/samples/cloudbroker/data_lb/main.tf b/samples/cloudbroker/lb/data_lb/main.tf similarity index 96% rename from samples/cloudbroker/data_lb/main.tf rename to samples/cloudbroker/lb/data_lb/main.tf index a1c1c33..5b25fcb 100644 --- a/samples/cloudbroker/data_lb/main.tf +++ b/samples/cloudbroker/lb/data_lb/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о load balancer (балансировщик нагрузок) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_lb" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 238 } diff --git a/samples/cloudbroker/data_lb_list/main.tf b/samples/cloudbroker/lb/data_lb_list/main.tf similarity index 80% rename from samples/cloudbroker/data_lb_list/main.tf rename to samples/cloudbroker/lb/data_lb_list/main.tf index c9cfa0b..8bf5bbf 100644 --- a/samples/cloudbroker/data_lb_list/main.tf +++ b/samples/cloudbroker/lb/data_lb_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка load balancer (балансировщиков нагрузки) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_lb_list" "lbl" { #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени балансировщика нагрузки @@ -38,12 +39,12 @@ data "decort_cb_lb_list" "lbl" { #id аккаунта для получения списка балансировщиков нагрузки #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -66,22 +67,28 @@ data "decort_cb_lb_list" "lbl" { #тип - строка #back_ip = "ENABLED" - #флаг влючения в результат удаленных балансироващиков нагрузки + #флаг включения в результат удаленных балансировщиков нагрузки #опциональный параметр - #тип - булев тип - #значение по-умолчанию - false + #тип - булев + #по-умолчанию - false #если не задан - выводятся все доступные неудаленные балансировщики #includedeleted = true + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudbroker/data_lb_list_deleted/main.tf b/samples/cloudbroker/lb/data_lb_list_deleted/main.tf similarity index 84% rename from samples/cloudbroker/data_lb_list_deleted/main.tf rename to samples/cloudbroker/lb/data_lb_list_deleted/main.tf index 925f972..fe3e4ce 100644 --- a/samples/cloudbroker/data_lb_list_deleted/main.tf +++ b/samples/cloudbroker/lb/data_lb_list_deleted/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение списка удаленных load balancer (балансировщиков нагрузок) - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_lb_list_deleted" "lbld" { #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени балансировщика нагрузки @@ -39,12 +39,12 @@ data "decort_cb_lb_list_deleted" "lbld" { #id аккаунта для получения списка балансировщиков нагрузки #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по техническому статусу @@ -62,15 +62,21 @@ data "decort_cb_lb_list_deleted" "lbld" { #тип - строка #back_ip = "ENABLED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudapi/resource_lb/main.tf b/samples/cloudbroker/lb/resource_lb/main.tf similarity index 70% rename from samples/cloudapi/resource_lb/main.tf rename to samples/cloudbroker/lb/resource_lb/main.tf index f1e4b99..3a02308 100644 --- a/samples/cloudapi/resource_lb/main.tf +++ b/samples/cloudbroker/lb/resource_lb/main.tf @@ -1,113 +1,119 @@ -/* -Пример использования -Ресурса load balancer -Ресурс позволяет: -1. Создавать load balancer -2. Редактировать load balancer -3. Удалять load balancer - -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - version = "" - source = "basis/decort/decort" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_lb" "lb" { - #id ресурсной группы для со - #обязательный параметр - #тип - число - rg_id = 1111 - - #наименование load balancer - #обязательный параметр - #тип - строка - name = "tf-test-lb" - - #id внешней сети и id виртуальной сети не могут быть одновременно = 0 - - #id внешней сети - #опциональный параметр - #тип - число - extnet_id = 6 - - #id виртуальной сети - #опциональный параметр - #тип - число - vins_id = 758 - - #флаг запуска load balancer - #обязательный параметр - #тип - булев тип - #по умолчанию - true - #если load balancer был в статусе "stopped" (start = false), - #то для успешного старта, он должен быть доступен (enable = true) - start = true - - # позволяет создать схему отказоустройчивой LB - # опциональный параметр - # тип - булев тип - ha_mode = true - - #описание - #опциональный параметр - #тип - строка - #desc = "temp super lb for testing tf provider" - - #флаг доступности load balancer - #необязательный параметр - #тип - булев тип - #enable = true - - #флаг перезапуска load balancer - #необязательный параметр - #тип - булев тип - #перезагрузка срабатывает только при изменении флага с false на true - #restart = false - - #флаг сброса конфигурации load balancer - #необязательный параметр - #тип - булев тип - #сброс срабатывает только при изменении флага с false на true - #config_reset = false - - #флаг моментального удаления load balancer - #необязательный параметр - #тип - булев тип - #по умолчанию - false - #применяется при выполнении команды terraform destroy - #permanently = false - - #флаг восстановления load balancer - #необязательный параметр - #тип - булев тип - #восстановить можно load balancer, удаленным с флагом permanently = false - #restore = true - - #флаг используемый при рестарте load balancer - #необязательный параметр - #тип - булев тип - #значение по умолчанию - true, при данном значении рестарт производится на обоих нодах в HA mode - #safe = true -} - -output "test" { - value = decort_lb.lb -} +/* +Пример использования +Ресурса load balancer +Ресурс позволяет: +1. Создавать load balancer +2. Редактировать load balancer +3. Удалять load balancer +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_lb" "lb" { + #id ресурсной группы для создания балансировщика + #обязательный параметр + #тип - целое число + rg_id = 1111 + + #наименование load balancer + #обязательный параметр + #тип - строка + name = "tf-test-lb" + + #id внешней сети + #опциональный параметр + #id внешней сети и id виртуальной сети не могут быть одновременно = 0 + #тип - целое число + extnet_id = 6 + + #id виртуальной сети + #опциональный параметр + #id внешней сети и id виртуальной сети не могут быть одновременно = 0 + #тип - целое число + vins_id = 758 + + #флаг запуска load balancer + #обязательный параметр + #если load balancer был в статусе "stopped" (start = false), + #то для успешного старта, он должен быть доступен (enable = true) + #по умолчанию - true + #тип - булев + start = true + + #позволяет создать схему отказоустройчивой LB + #опциональный параметр + #тип - булев + #ha_mode = true + + #описание + #опциональный параметр + #тип - строка + #descс= "temp super lb for testing tf provider" + + #флаг доступности load balancer + #опциональный параметр + #тип - булев + #enable = true + + #флаг перезапуска load balancer + #опциональный параметр + #перезагрузка срабатывает только при изменении флага с false на true + #тип - булев + #restart = false + + #флаг сброса конфигурации load balancer + #опциональный параметр + #сброс срабатывает только при изменении флага с false на true + #тип - булев + #config_reset = false + + #флаг моментального удаления load balancer + #опциональный параметр + #применяется при выполнении команды terraform destroy + #по умолчанию - false + #тип - булев + #permanently = false + + #флаг восстановления load balancer + #опциональный параметр + #восстановить можно load balancer, удаленным с флагом permanently = false + #тип - булев + #restore = true + + #флаг используемый при рестарте load balancer + #опциональный параметр + #значение по умолчанию - true, при данном значении рестарт производится на обоих нодах в HA mode + #тип - булев + #safe = true + + #пользовательские значения sysctl для LB + #опциональный параметр + #тип - список мап + #sysctl_params = [{text = "1", text = "some"}] + +} + +output "test" { + value = decort_cb_lb.lb +} diff --git a/samples/cloudbroker/resource_lb_backend/main.tf b/samples/cloudbroker/lb/resource_lb_backend/main.tf similarity index 81% rename from samples/cloudbroker/resource_lb_backend/main.tf rename to samples/cloudbroker/lb/resource_lb_backend/main.tf index 898b3e2..fd5e87f 100644 --- a/samples/cloudbroker/resource_lb_backend/main.tf +++ b/samples/cloudbroker/lb/resource_lb_backend/main.tf @@ -5,8 +5,8 @@ 1. Создавать backend 2. Редактировать backend 3. Удалять backend - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,7 +33,7 @@ provider "decort" { resource "decort_cb_lb_backend" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя бекенда для создания сервера @@ -42,10 +42,10 @@ resource "decort_cb_lb_backend" "lb" { name = "testBackend" #алгоритм балансировки - #опицональный параметр - #тип - строка - #по умолчанию - "roundrobin" + #опциональный параметр #доступные значения - "roundrobin", "static-rr", "leastconn" + #по умолчанию - "roundrobin" + #тип - строка #algorithm = "roundrobin" #------------------- @@ -53,54 +53,55 @@ resource "decort_cb_lb_backend" "lb" { #------------------- #интервал между проверками, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 5000 + #тип - целое число #inter = 5000 #интервал между проверками доступности сервера после восстановления, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 10000 + #тип - целое число #downinter = 1000 #кол-во проверок, которые сервер должен успешно пройти - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #по умолчанию - 2 #rise = 2 #кол-во проверок, которые сервер может не пройти и после этого получить статус "unavailable" - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 2 + #тип - целое число #fall = 2 #кол-во миллисекунд - время между получением сервера статуса "available" и открытием соединений - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 60000 + #тип - целое число #slowstart = 60000 #максимальное кол-во соединений сервера, при достижении этого кол-ва, сервер выходит из схемы балансирования - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 250 + #тип - целое число #maxconn = 250 #максимальное кол-во соединений в очереди серевера, при достижении этого кол-ва, соединения будут перенаправлены на другой сервер - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 256 + #тип - целое число #maxqueue = 256 #вес сервера для балансировки - #опицональный параметр - #тип - число + #опциональный параметр #мин - 0 #макс - 255 #по умолчанию - 100 + #тип - целое число #weight = 100 + } output "test" { diff --git a/samples/cloudbroker/resource_lb_backend_server/main.tf b/samples/cloudbroker/lb/resource_lb_backend_server/main.tf similarity index 82% rename from samples/cloudbroker/resource_lb_backend_server/main.tf rename to samples/cloudbroker/lb/resource_lb_backend_server/main.tf index 26218c5..037613e 100644 --- a/samples/cloudbroker/resource_lb_backend_server/main.tf +++ b/samples/cloudbroker/lb/resource_lb_backend_server/main.tf @@ -5,8 +5,8 @@ 1. Создавать server 2. Редактировать server 3. Удалять server - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,7 +33,7 @@ provider "decort" { resource "decort_cb_lb_backend_server" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя бекенда для создания сервера @@ -53,65 +53,66 @@ resource "decort_cb_lb_backend_server" "lb" { #порт сервера #обязательный параметр - #тип - число + #тип - целое число port = 6553 #проверка доступности сервера - #опицональный параметр - #тип - строка - #по умолчанию - "enabled" + #опциональный параметр #доступные значения - "disabled", "enabled" + #по умолчанию - "enabled" + #тип - строка #check = "enabled" #интервал между проверками, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 5000 + #тип - целое число #inter = 5000 #интервал между проверками доступности сервера после восстановления, в миллисекундах - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 10000 + #тип - целое число #downinter = 1000 #кол-во проверок, которые сервер должен успешно пройти - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 2 + #тип - целое число #rise = 2 #кол-во проверок, которые сервер может не пройти и после этого получить статус "unavailable" - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 2 + #тип - целое число #fall = 2 #кол-во миллисекунд - время между получением сервера статуса "available" и открытием соединений - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 60000 + #тип - целое число #slowstart = 60000 #максимальное кол-во соединений сервера, при достижении этого кол-ва, сервер выходит из схемы балансирования - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 250 + #тип - целое число #maxconn = 250 #максимальное кол-во соединений в очереди серевера, при достижении этого кол-ва, соединения будут перенаправлены на другой сервер - #опицональный параметр - #тип - число + #опциональный параметр #по умолчанию - 256 + #тип - целое число #maxqueue = 256 #вес сервера для балансировки - #опицональный параметр - #тип - число + #опциональный параметр #мин - 0 #макс - 255 #по умолчанию - 100 + #тип - целое число #weight = 100 + } output "test" { diff --git a/samples/cloudbroker/resource_lb_frontend/main.tf b/samples/cloudbroker/lb/resource_lb_frontend/main.tf similarity index 97% rename from samples/cloudbroker/resource_lb_frontend/main.tf rename to samples/cloudbroker/lb/resource_lb_frontend/main.tf index fb11c5a..1c43d27 100644 --- a/samples/cloudbroker/resource_lb_frontend/main.tf +++ b/samples/cloudbroker/lb/resource_lb_frontend/main.tf @@ -4,8 +4,8 @@ Ресурс позволяет: 1. Создавать frontend 2. Удалять frontend - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -13,8 +13,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -32,7 +32,7 @@ provider "decort" { resource "decort_cb_lb_frontend" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя бекенда для создания фронтенда @@ -44,6 +44,7 @@ resource "decort_cb_lb_frontend" "lb" { #обязательный параметр #тип - строка name = "testFrontend" + } output "test" { diff --git a/samples/cloudbroker/resource_lb_frontend_bind/main.tf b/samples/cloudbroker/lb/resource_lb_frontend_bind/main.tf similarity index 96% rename from samples/cloudbroker/resource_lb_frontend_bind/main.tf rename to samples/cloudbroker/lb/resource_lb_frontend_bind/main.tf index b65fd17..8f3e013 100644 --- a/samples/cloudbroker/resource_lb_frontend_bind/main.tf +++ b/samples/cloudbroker/lb/resource_lb_frontend_bind/main.tf @@ -5,8 +5,8 @@ 1. Создавать привязку 2. Редактировать привязку 3. Удалять привязку - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -33,7 +33,7 @@ provider "decort" { resource "decort_cb_lb_frontend_bind" "lb" { #id балансировщика нагрузок #обязательный параметр - #тип - число + #тип - целое число lb_id = 668 #имя фронтенда для создания привязки @@ -53,8 +53,9 @@ resource "decort_cb_lb_frontend_bind" "lb" { #порт для привязки фронтенда #обязательный параметр - #тип - число + #тип - целое число port = 1111 + } output "test" { diff --git a/samples/cloudbroker/node/data_node/main.tf b/samples/cloudbroker/node/data_node/main.tf new file mode 100644 index 0000000..08fbffa --- /dev/null +++ b/samples/cloudbroker/node/data_node/main.tf @@ -0,0 +1,38 @@ +/* +Пример использования +Получение информации о ноде платформы +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_node" "node" { + #id ноды + #обязательный параметр + #тип - целое число + node_id = 12 +} + +output "test" { + value = data.decort_cb_node.node +} diff --git a/samples/cloudbroker/node/data_node_list/main.tf b/samples/cloudbroker/node/data_node_list/main.tf new file mode 100644 index 0000000..564925b --- /dev/null +++ b/samples/cloudbroker/node/data_node_list/main.tf @@ -0,0 +1,84 @@ +/* +Пример использования +Получение списка нод платформы +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_node_list" "nodes" { + #фильтр по id ноды + #опциональный параметр + #тип - целое число + #by_id = 1234 + + #фильтр по имени ноды + #опциональный параметр + #тип - строка + #name = "node1" + + #фильтр по версии ноды + #опциональный параметр + #тип - строка + #version = "version1" + + #фильтр по релизу ноды + #опциональный параметр + #тип - строка + #release = "release1" + + #фильтр по sep id + #опциональный параметр + #тип - целое число + #sep_id = 12 + + #фильтр по ролям ноды + #опциональный параметр + #тип - строка + #role = "service" + + #фильтр по статусу ноды + #опциональный параметр + #тип - строка + #status = "disabled" + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + + #номер страницы для отображения + #опциональный параметр + #тип - целое число + #page = 2 + + #размер страницы + #опциональный параметр + #тип - целое число + #size = 3 +} + +output "test" { + value = data.decort_cb_node_list.nodes +} diff --git a/samples/cloudbroker/data_pcidevice/main.tf b/samples/cloudbroker/pcidevice/data_pcidevice/main.tf similarity index 96% rename from samples/cloudbroker/data_pcidevice/main.tf rename to samples/cloudbroker/pcidevice/data_pcidevice/main.tf index 4c2db39..764735f 100644 --- a/samples/cloudbroker/data_pcidevice/main.tf +++ b/samples/cloudbroker/pcidevice/data_pcidevice/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение информации об устройстве - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,14 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -31,8 +30,9 @@ provider "decort" { data "decort_cb_pcidevice" "pd" { #id устройства #обязательный параметр - #тип - число + #тип - целое число device_id = 85 + } output "test" { diff --git a/samples/cloudbroker/data_pcidevice_list/main.tf b/samples/cloudbroker/pcidevice/data_pcidevice_list/main.tf similarity index 91% rename from samples/cloudbroker/data_pcidevice_list/main.tf rename to samples/cloudbroker/pcidevice/data_pcidevice_list/main.tf index 2e5ee60..ecc8e9f 100644 --- a/samples/cloudbroker/data_pcidevice_list/main.tf +++ b/samples/cloudbroker/pcidevice/data_pcidevice_list/main.tf @@ -1,18 +1,17 @@ /* Пример использования Получение информации обо всех доступных устройствах - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -30,12 +29,12 @@ provider "decort" { data "decort_cb_pcidevice_list" "pdl" { #фильтр по id устройства #опциональный параметр - #тип - число + #тип - целое число #by_id = 111 #фильтр по id Compute #опциональный параметр - #тип - число + #тип - целое число #compute_id = 123 #фильтр по имени устройства @@ -45,7 +44,7 @@ data "decort_cb_pcidevice_list" "pdl" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 111 #фильтр по статусу устройства @@ -55,13 +54,14 @@ data "decort_cb_pcidevice_list" "pdl" { #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudbroker/resource_pcidevice/main.tf b/samples/cloudbroker/pcidevice/resource_pcidevice/main.tf similarity index 91% rename from samples/cloudbroker/resource_pcidevice/main.tf rename to samples/cloudbroker/pcidevice/resource_pcidevice/main.tf index 96171e1..24c7de2 100644 --- a/samples/cloudbroker/resource_pcidevice/main.tf +++ b/samples/cloudbroker/pcidevice/resource_pcidevice/main.tf @@ -5,8 +5,8 @@ 1. Создавать устройство 2. Редактировать устройство 3. Удалять устройство - */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -14,14 +14,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -45,40 +44,40 @@ resource "decort_cb_pcidevice" "pd" { #описание устройства #необязательный параметр #тип - строка - description = "test desc" + #description = "test desc" #id ресурсной группы устройства #обязательный параметр - #тип - число + #тип - целое число rg_id = 1111 #id стака устройства #обязательный параметр - #тип - число + #тип - целое число stack_id = 11 #доступность устройства #опциональный параметр #может использоваться на созданном ресурсе - #тип - булево значение + #тип - булев #enable = false #принудительное отключение устройства #опциональный параметр #может использоваться на созданном ресурсе - #тип - булево значение + #тип - булев #force_disable = true #принудительное удаление устройства #опциональный параметр #используется при удалении ресурса - #тип - булево значение + #тип - булев #force_delete = true #id устройства #опциональный параметр #позволяет "восстановить" состояние ресурса терраформа на локальной машине - #тип - число + #тип - целое число #device_id = 86 } diff --git a/samples/cloudbroker/resource_extnet/main.tf b/samples/cloudbroker/resource_extnet/main.tf deleted file mode 100644 index fc6cc82..0000000 --- a/samples/cloudbroker/resource_extnet/main.tf +++ /dev/null @@ -1,172 +0,0 @@ -/* -Пример использования -Получение списка доступных образов -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером - -# terraform { -# required_providers { -# decort = { -# version = "" -# source = "basis/decort/decort" -# } -# } -# } - - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - allow_unverified_ssl = true -} - -resource "decort_cb_extnet" "new_extnet" { - # Наименование внешней сети - # Обязательный параметр - # Тип - строка - name = "test_extnet" - - # ID платформы - # Обязательный параметр - # Тип - число - gid = 500 - - # CIDR - # Обязательный параметр - # Тип - строка - ipcidr = "192.168.0.0/24" - - # ID виртуальной локальной сети - # Обязательный параметр - # Тип - число - vlan_id = 111 - - # IP-адрес шлюза внешней сети - # Опциональный параметр - # Тип - строка - gateway = "test desc" - - # Список DNS адресов - # Опциональный параметр - # Тип - массив строк - dns = ["8.8.8.8", "9.9.9.9"] - - # Список NTP адресов - # Опциональный параметр - # Тип - массив строк - ntp = ["ntp0.ntp-servers.net", "ntp1.ntp-servers.net"] - - # IP-адреса для проверки доступности сети - # Опциональный параметр - # Тип - массив строк - check_ips = ["191.255.0.0,", "191.255.0.0,"] - - # Если true - DHCP-сервер создан не будет - # Опциональный параметр - # Тип - булевое - virtual = true - - # Описание - # Опциональный параметр - # Тип - строка - desc = "test desc" - - # Начало диапазона IP-адресов - # Опциональный параметр - # Тип - строка - start_ip = "191.255.0.0" - - # Окончание диапазона IP-адресов - # Опциональный параметр - # Тип - строка - end_ip = "191.255.0.40" - - # IP с которым будет создан vnfdev - # Опциональный параметр - # Тип - строка - vnfdev_ip = "191.255.0.20" - - # Количество предварительно созданных бронирований - # Опциональный параметр - # Тип - число - # По-умолчанию значение 128 - pre_reservations_num = 128 - - # Имя bridge Openvswitch для подключения к внешней сети - # Опциональный параметр - # Тип - строка - ovs_bridge = "some" - - # Включение/Выключение внешней сети - # Опциональный параметр - # Тип - булев - enable = true - - # Сделать сеть сетью по умолчанию - # Опциональный параметр - # Тип - булев - set_default = true - - # Список исключенных IP адресов - # Опциональный параметр - # Тип - массив строк - excluded_ips = ["192.168.0.4", "192.168.0.5"] - - # Диапазон исключенных IP адресов - # Опциональный параметр - excluded_ips_range { - # Начало диапазона - # Обязательный параметр - # Тип - строка - ip_start = "192.168.0.4" - - # Окончание диапазона - # Обязательный параметр - # Тип - строка - ip_end = "192.168.0.50" - } - - # Список id аккаунтов, которым предоставлен доступ к extnet - # Опциональный параметр - # Тип - массив чисел - shared_with = [112, 123] - - # Изменение настроек ограничения трафика сети - # Значение по умолчанию 0, то есть без ограничений - # Опциональный параметр - default_qos { - # Ограничение внутреннего трафика в кбит - # Опциональный параметр - # Тип - число - in_rate = 0 - - # Ограничение внутреннего burst трафика в кбит - # Опциональный параметр - # Тип - число - in_burst = 0 - - # Ограничение внешнего трафика в кбит - # Опциональный параметр - # Тип - число - e_rate = 0 - } - - # ID stack на который происходит миграция - # Опциональный параметр - # Тип - число - migrate = 1 - - # Перезапустить сеть - # Опциональный параметр - # Тип - булев - restart = true -} - -output "extnet" { - value = decort_cb_extnet.new_extnet -} \ No newline at end of file diff --git a/samples/cloudbroker/resource_flipgroup/main.tf b/samples/cloudbroker/resource_flipgroup/main.tf deleted file mode 100644 index 5c34c80..0000000 --- a/samples/cloudbroker/resource_flipgroup/main.tf +++ /dev/null @@ -1,72 +0,0 @@ -/* -Пример использования -ресурса флипгруппы -*/ - -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - oauth2_url = "https://sso-alpha.dev.decs.online" - controller_url = "https://alpha.dev.decs.online" - app_id = "" - app_secret = "" -} - -resource "decort_cb_flipgroup" "fg" { - # ID аккаунта - # Обязательный параметр - # int - account_id = 999 - - # Наименование Flipgroup - # Обязательный параметр - # string - name = "flipgroup_name" - - # Тип сети (EXTNET, VINS) - # Обязательный параметр - # string - net_type = "EXTNET" - - # ID сети - # Обязательный параметр - # int - net_id = 13 - - # Тип клиентов (в данный момент поддерживается только тип 'compute') - # Обязательный параметр - # string - client_type = "compute" - - # IP-адрес - # Опциональный параметр - # string - #ip = "127.0.0.1" - - # Список клиентов, прикрепленных к флипгруппе - # Опциональный параметр - # []int - #client_ids = [11269] - - # Описание флипгруппы - # Опциональный параметр - # string - #desc = "CHANGED" -} - -output "fg_out" { - value = decort_cb_flipgroup.fg -} diff --git a/samples/cloudbroker/resource_k8s_cp/main.tf b/samples/cloudbroker/resource_k8s_cp/main.tf deleted file mode 100644 index 45dff03..0000000 --- a/samples/cloudbroker/resource_k8s_cp/main.tf +++ /dev/null @@ -1,173 +0,0 @@ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - #app_id = - #app_secret = - allow_unverified_ssl = true - -} - -resource "decort_cb_k8s_cp" "cp" { - # Название кластера - # Обязательный параметр - # string - name = "k8s-cp" - - # K8sCI ID - # Обязательный параметр - # int - k8sci_id = 55 - - # Плагин сети (flannel, weavenet или calico) - # Обязательный параметр - # string - network_plugin = "flannel" - - # ID ресурсной группы - # Обязательный параметр - # int - rg_id = 1387 - - # Кол-во ядер мастер-узла - # Опциональный параметр - # int - cpu = 2 - - # Объем RAM мастер-узла - # Опциональный параметр - # int - ram = 2048 - - # Кол-во ВМ мастер-узла (1 или 3) - # Опциональный параметр - # int - num = 1 - - # Размер диска мастер-узла - # Опциональный параметр - # int - disk = 10 - - # Описание кластера - # Опциональный параметр - # string - desc = "" - - # id extnet - #опциональный параметр - #тип - число - extnet_id = 0 - - # id vins - # опциональный параметр - # тип - число - vins_id = 1234 - - # Storage Endpoint ID - # Опциональный параметр - # id - sep_id = 0 - - # SEP Pool - # Опциональный параметр - # string - sep_pool = "pool" - - # Старт/Стоп кластера - # Опциональный параметр - # bool - start = true - - # Включить/отключить кластер - # Опциональный параметр - # bool - enabled = true - - # Удалить кластер безвозвратно - # Опциональный параметр - # bool - permanently = true - - # Восстановить кластер из корзины - # Опциональный параметр - # bool - restore = true - - # Создать кластер с/без балансировщика нагрузки - # Опциональный параметр - # bool - with_lb = true - - # позволяет создать схему отказоустройчивой LB - # опциональный параметр - # тип - булев тип - ha_mode = true - - # дополнительные SAN (Subject Alternative Names) для использования в процессе автоматического выписывания сертификата Кластера Kubernetes; - # возможность взаимодействовать с кластером по FQDN - # параметр получает список строк – IP-адреса и/или DNS (по формату RFC 1123 c поддержкой wildcard) - # опциональный параметр - # тип - массив строк - additional_sans = ["192.168.201.0","192.168.201.1"] - - # используется для определения настроек и действий, которые должны быть выполнены перед запуском любого другого компонента в кластере - # это позволяет вам настраивать такие вещи, как регистрация node, настройка network и другие задачи инициализации - # опциональный параметр - # тип - строка - init_config = "{JSON string}" - - # используется для определения глобальных настроек и конфигураций для всего кластера - # он включает в себя такие параметры, как имя кластера, настройки DNS, методы аутентификации и другие конфигурации в масштабах кластера - # опциональный параметр - # тип - строка - cluster_config = "{JSON string}" - - # используется для настройки поведения и параметров Kubelet, который является агентом primary node, запускаемым на каждом node кластера - # он включает в себя такие параметры, как IP-адрес node, распределение ресурсов, политики удаления модулей и другие конфигурации, специфичные для Kubelet - # опциональный параметр - # тип - строка - kubelet_config = "{JSON string}" - - # используется для настройки поведения и параметров присоединения node к кластеру - # он включает в себя такие параметры, как режим прокси-сервера, диапазоны IP-адресов кластера и другие конфигурации, специфичные для Kube-proxy - # опциональный параметр - # тип - строка - kube_proxy_config = "{JSON string}" - - # используется для настройки поведения и параметров присоединения node к кластеру - # он включает в себя такие параметры, как cluster's control plane endpoint, токен и ключ сертификата - # опциональный параметр - # тип - строка - join_config = "{JSON string}" - - # при создании кластре использовать подключение только к сети ExtNet - # опциональный параметр - # тип - булев тип - extnet_only = true - - # добавить ssl-сертификат в формате x509 pem - # необязательный параметр - # тип - файл - oidc_cert = file("ca.crt") -} - -output "cp_out" { - value = decort_cb_k8s_cp.cp -} diff --git a/samples/cloudbroker/resource_k8s_wg/initconfig.tftpl b/samples/cloudbroker/resource_k8s_wg/initconfig.tftpl deleted file mode 100644 index 06df7c0..0000000 --- a/samples/cloudbroker/resource_k8s_wg/initconfig.tftpl +++ /dev/null @@ -1,9 +0,0 @@ ---- -users: -- groups: users, wheel - name: user - plain_text_passwd: examplePassword - primary_group: user - ssh_authorized_keys: - - ssh-rsa EXAMPLE%id_rsa.pub - sudo: ALL=(ALL) NOPASSWD:ALL diff --git a/samples/cloudbroker/resource_kvmvm/main.tf b/samples/cloudbroker/resource_kvmvm/main.tf deleted file mode 100644 index 3301b9a..0000000 --- a/samples/cloudbroker/resource_kvmvm/main.tf +++ /dev/null @@ -1,429 +0,0 @@ -/* -Пример использования -Работа с ресурсом kvmvm (compute) -Ресурс позволяет: -1. Создавать compute -2. Редактировать compute -3. Удалять compute -*/ -#Расскомментируйте этот код, -#и внесите необходимые правки в версию и путь, -#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* -terraform { - required_providers { - decort = { - source = "basis/decort/decort" - version = "" - } - } -} -*/ - -provider "decort" { - authenticator = "decs3o" - #controller_url = - controller_url = "https://ds1.digitalenergy.online" - #oauth2_url = - oauth2_url = "https://sso.digitalenergy.online" - #app_id = - #app_secret = - allow_unverified_ssl = true -} - -resource "decort_cb_kvmvm" "comp" { - #имя compute - #обязательный параметр - #мб изменен - #тип - строка - name = "test-tf-compute-update-new" - - #id resource group - #обязательный параметр - #тип - число - rg_id = 1111 - - #тип драйвера для compute - #обязательный параметр - #тип - строка - driver = "KVM_X86" - - #число cpu - #обязательный параметр - #тип - число - cpu = 1 - - #кол-во оперативной памяти, МБ - #обязательный параметр - #тип - число - ram = 2048 - - #id образа диска для создания compute - #обязательный параметр - #тип - число - image_id = 111 - - #размер загрузочного диска - #опциональный параметр - #тип - число - boot_disk_size = 20 - - #ID сепа для boot диска - #опциональный параметр - #тип - число - sep_id = 1 - - #Название пула - #опциональный параметр - #тип - строка - pool = "data02" - - #конфигурация cloud init - #опциональный параметр - #тип - файл в формате JSON/YAML - cloud_init = file("initconfig.tftpl") - - #описание compute - #опциональный параметр - #тип - строка - description = "test update description in tf words update" - - #stack id - #опциональный параметр - #тип - число - stack_id = 1 - - #id образа CD-ROM для загрузки - #используется при изменении ресурса, при повторном старте вм - #опциональный параметр - #тип - число - alt_boot_id = 1 - - #Создание и добавление диска дял compute - #опциональный параметр - #тип - список дисков - disks { - #Имя диска - #Обязательный для диска параметр - #Тип - строка - disk_name = "disk_name" - - #Размер диска - #Обязательный для диска параметр - #Тип - число - size = 5 - - #Тип диска - #опциональный параметр - #тип - строка - disk_type = "D" - - #опциональный параметр - #тип - число - sep_id = 1 - - #Название пула - #опциональный параметр - #тип - строка - pool = "data01" - - #Описание диска - #опциональный параметр - #тип - строка - desc = "" - - #Айди образа - #опциональный параметр - image_id = 378 - - #Флаг для удаления диска - #опциональный параметр - #тип - bool - permanently = false - } - - #правила affinity - #опциональный параметр - #может быть один, несколько или ни одного блока - #тип - блок - affinity_rules { - #тип правила - #возможные значения - compute или node - #обязательный параметр - #тип - строка - topology = "compute" - - #строгость правила - #возможные значения - RECOMMENDED и REQUIRED - #обязательный параметр - #тип - строка - policy = "RECOMMENDED" - - #режим проверки - #возможные значения - ANY, EQ, NE - #обязательный параметр - #тип - строка - mode = "ANY" - - #ключ правила - #обязательный параметр - #тип строка - key = "testkey" - - #ключ правила - #необязательный параметр - #тип строка - value = "testvalue" - } - - #правила anti-affinity - #опциональный параметр - #может быть один, несколько или ни одного блока - #тип - блок - anti_affinity_rules { - #тип правила - #возможные значения - compute или node - #обязательный параметр - #тип - строка - topology = "compute" - - #строгость правила - #возможные значения - RECOMMENDED и REQUIRED - #обязательный параметр - #тип - строка - policy = "RECOMMENDED" - - #режим проверки - #возможные значения - ANY, EQ, NE - #обязательный параметр - #тип - строка - mode = "ANY" - - #ключ правила - #обязательный параметр - #тип строка - key = "testkey" - - #ключ правила - #необязательный параметр - #тип строка - value = "testvalue" - } - - #установка метки для вм - #опциональный параметр - #тип - строка - affinity_label = "test4" - - - #наименование системы - #опциональный параметр - #используется при создании вм - #по умолчанию - не задан - #тип - строка - is="" - - #назначение вм - #опциональный параметр - #используется при создании вм - #по умолчанию - не задан - #тип - строка - ipa_type = "" - - #Id экстра дисков - #опциональный параметр - #тип - список чисел - extra_disks = [1234, 4322, 1344] - - #Управление XML виртуальной машины - #опциональный параметр - #тип - строка (json-encoded) - custom_fields = "{`key`:`value`}" - - #Описание необходимости выполнения действия - #опциональный параметр - #тип - строка - reason = "need" - - #Присоеденения сетей и удаление сетей в компьюте - #опциональный параметр - #тип - блок - network { - #Тип сети VINS/EXTNET - #Обязательный параметр - #тип - строка - net_type = "VINS" - - #ID сети - #Обязательный параметр - #тип - число - net_id = 1234 - - #IP адрес входящий в сеть - #опциональный параметр - #тип - строка - ip_address = "127.0.0.1" - } - - #добавление и удаление тэгов - #опциональный параметр - #тип - блок - tags { - #Ключ для тэга - #Обязательный параметр - #тип - строка - key = "key" - - #Значения тэга - #Обязательный параметр - #тип - строка - value = "value" - } - - #добавление и удаление port forwarding - #опциональный параметр - #тип - блок - port_forwarding { - #номер внешнего начального порта для правила - #Обязательный параметр - #тип - число - public_port_start = 2023 - - #номер внешнего последнего порта для правила - #опциональный параметр - #тип - число - #по умолчанию - -1 - public_port_end = 2023 - - #номер внутреннего базового порта - #Обязательный параметр - #тип - число - local_port = 80 - - #сетевой протокол - #Обязательный параметр - #тип - строка - proto = "tcp" - } - - #предоставить/забрать пользователю доступ к компьюту - #опциональный параметр - #тип - блок - user_access { - #Имя юзера, которому предоставляем доступ - #Обязательный параметр - #тип - строка - username = "some@decs3o" - - #Права: 'R' - только на чтение, 'RCX' - чтение/запись, 'ARCXDU' - админ - #Обязательный параметр - #тип - строка - access_type = "ARCXDU" - } - - #Создать/удалить снапшот компьюта - #опциональный параметр - #тип - блок - snapshot { - #Лейбл снапшота - #Обязательный параметр - #тип - строка - label = "label1" - } - - #Rollback на нужный снапшот - #опциональный параметр - #Не имеет смысла при отсутсвии снапшотов - #тип - блок - rollback { - #Лейбл снапшота - #Обязательный параметр - #тип - строка - label = "label1" - } - - #Вставить/удалить СD rom - #опциональный параметр - #Максимальное кол-во - 1 - #тип - блок - cd { - #ID образа диска CD rom - #Обязательный параметр - #тип - число - cdrom_id = 344 - } - - #Добавить компьют на стэк - #опциональный параметр - #тип - булев - pin_to_stack = true - - #id stack для добавления компьюта на этот стэк - #опциональный параметр - #тип - число - target_stack_id = 1 - - #Флаг для принужительного добавления компьюта на стэк - #опциональный параметр - #тип - булев - force_pin = true - - #Флаг доступности компьюта для проведения с ним операций - #опциональный параметр - #тип - булев - enabled = true - - #pause/resume компьюта - #опциональный параметр - #тип - булев - pause = true - - #сделать компьют заново - #опциональный параметр - #тип - булев - reset = true - - #восстановить удаленный компьют из корзины - #опциональный параметр - #тип - булев - restore = true - - #флаг для редеплоя компьюта - #опциональный параметр - #тип - булев - auto_start = true - - #флаг для редеплоя компьюта - #опциональный параметр - #тип - булев - force_stop = true - - #флаг для ресайза компьюта - #опциональный параметр - #тип - булев - force_resize = true - - #поле для редеплоя компьюта - #опциональный параметр - #тип - строка - data_disks = "KEEP" - - #запуск/стоп компьюта - #опциональный параметр - #тип - булев - started = true - - #detach диска при удалении компьюта - #опциональный параметр - #тип - булев - detach_disks = true - - #Флаг для удаления компьюта - #опциональный параметр - #тип - bool - permanently = false -} - -output "test" { - value = decort_cb_kvmvm.comp -} diff --git a/samples/cloudbroker/data_rg/main.tf b/samples/cloudbroker/rg/data_rg/main.tf similarity index 90% rename from samples/cloudbroker/data_rg/main.tf rename to samples/cloudbroker/rg/data_rg/main.tf index 79e2d95..7ef2386 100644 --- a/samples/cloudbroker/data_rg/main.tf +++ b/samples/cloudbroker/rg/data_rg/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение информации о ресурсной группе RG +Получение информации о ресурсной группе (RG) */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +11,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,10 +30,10 @@ provider "decort" { data "decort_cb_rg" "rg" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 1022 - #причина для выполняния действия + #причина для выполнения действия #необязятельный параметр #тип - строка reason = "TEST" diff --git a/samples/cloudbroker/data_rg_affinity_group_computes/main.tf b/samples/cloudbroker/rg/data_rg_affinity_group_computes/main.tf similarity index 97% rename from samples/cloudbroker/data_rg_affinity_group_computes/main.tf rename to samples/cloudbroker/rg/data_rg_affinity_group_computes/main.tf index 4c0ce7a..56feab8 100644 --- a/samples/cloudbroker/data_rg_affinity_group_computes/main.tf +++ b/samples/cloudbroker/rg/data_rg_affinity_group_computes/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о специальной группе компьютов */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ @@ -27,7 +28,7 @@ provider "decort" { data "decort_cb_rg_affinity_group_computes" "lc" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #название специальной группы компьютов diff --git a/samples/cloudbroker/data_rg_affinity_groups_get/main.tf b/samples/cloudbroker/rg/data_rg_affinity_groups_get/main.tf similarity index 97% rename from samples/cloudbroker/data_rg_affinity_groups_get/main.tf rename to samples/cloudbroker/rg/data_rg_affinity_groups_get/main.tf index 1a2fc90..6633529 100644 --- a/samples/cloudbroker/data_rg_affinity_groups_get/main.tf +++ b/samples/cloudbroker/rg/data_rg_affinity_groups_get/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о списке компьютов из определенной группы */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,13 +10,12 @@ /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ - provider "decort" { authenticator = "decs3o" #controller_url = @@ -28,7 +28,7 @@ provider "decort" { data "decort_cb_rg_affinity_groups_get" "get_groups" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #название специальной группы компьютов diff --git a/samples/cloudbroker/data_rg_affinity_groups_list/main.tf b/samples/cloudbroker/rg/data_rg_affinity_groups_list/main.tf similarity index 93% rename from samples/cloudbroker/data_rg_affinity_groups_list/main.tf rename to samples/cloudbroker/rg/data_rg_affinity_groups_list/main.tf index 647c4d3..e541ac7 100644 --- a/samples/cloudbroker/data_rg_affinity_groups_list/main.tf +++ b/samples/cloudbroker/rg/data_rg_affinity_groups_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о списке специальных групп компьютов */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ @@ -27,18 +28,18 @@ provider "decort" { data "decort_cb_rg_affinity_groups_list" "list_groups" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudbroker/data_rg_audits/main.tf b/samples/cloudbroker/rg/data_rg_audits/main.tf similarity index 96% rename from samples/cloudbroker/data_rg_audits/main.tf rename to samples/cloudbroker/rg/data_rg_audits/main.tf index bdfe145..c72c8cd 100644 --- a/samples/cloudbroker/data_rg_audits/main.tf +++ b/samples/cloudbroker/rg/data_rg_audits/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о списке аудитов ресурсной группы */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ @@ -27,7 +28,7 @@ provider "decort" { data "decort_cb_rg_audits" "rg_audits" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 1022 } diff --git a/samples/cloudbroker/data_rg_get_resource_consumption/main.tf b/samples/cloudbroker/rg/data_rg_get_resource_consumption/main.tf similarity index 93% rename from samples/cloudbroker/data_rg_get_resource_consumption/main.tf rename to samples/cloudbroker/rg/data_rg_get_resource_consumption/main.tf index 078fd9e..a15b413 100644 --- a/samples/cloudbroker/data_rg_get_resource_consumption/main.tf +++ b/samples/cloudbroker/rg/data_rg_get_resource_consumption/main.tf @@ -1,4 +1,5 @@ /* +Пример использования Получение списка текущего потребления ресурсов ресурсной группы */ @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -27,7 +28,7 @@ provider "decort" { data "decort_cb_rg_resource_consumption_get" "rc_get" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 111 } diff --git a/samples/cloudbroker/data_rg_list/main.tf b/samples/cloudbroker/rg/data_rg_list/main.tf similarity index 79% rename from samples/cloudbroker/data_rg_list/main.tf rename to samples/cloudbroker/rg/data_rg_list/main.tf index 142d2d8..1476a24 100644 --- a/samples/cloudbroker/data_rg_list/main.tf +++ b/samples/cloudbroker/rg/data_rg_list/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение информации о списке всех ресурсных группах к которым есть доступ +Получение информации о списке всех ресурсных групп к которым есть доступ */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ @@ -27,7 +28,7 @@ provider "decort" { data "decort_cb_rg_list" "rg_list" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени ресурсной группы @@ -37,7 +38,7 @@ data "decort_cb_rg_list" "rg_list" { #id аккаунта для получения списка ресурсных групп #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по имени аккаунта @@ -47,12 +48,12 @@ data "decort_cb_rg_list" "rg_list" { #фильтр по времени создания (после указанного времени) #опциональный параметр - #тип - число + #тип - целое число #created_after = 123 #фильтр по времени создания (перед указанным временем) #опциональный параметр - #тип - число + #тип - целое число #created_before = 123 #фильтр по статусу @@ -62,18 +63,24 @@ data "decort_cb_rg_list" "rg_list" { #отображать удаленные ресурсные группы или нет #необязательный параметр - #тип - булевый - #значение по умолчанию - false + #тип - булев + #по умолчанию - false #includedeleted = false + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" #номер страницы #необязательный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #необязательный параметр - #тип - число + #тип - целое число #size = 2 } diff --git a/samples/cloudbroker/data_rg_list_computes/main.tf b/samples/cloudbroker/rg/data_rg_list_computes/main.tf similarity index 83% rename from samples/cloudbroker/data_rg_list_computes/main.tf rename to samples/cloudbroker/rg/data_rg_list_computes/main.tf index 5946694..7aae74a 100644 --- a/samples/cloudbroker/data_rg_list_computes/main.tf +++ b/samples/cloudbroker/rg/data_rg_list_computes/main.tf @@ -2,6 +2,7 @@ Пример использования Получение информации о списке компьютов в ресурсной группе */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,11 +10,12 @@ /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,12 +29,12 @@ provider "decort" { data "decort_cb_rg_list_computes" "list_computes" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #фильтр по id compute #опциональный параметр - #тип - число + #тип - целое число #compute_id = 100 #фильтр по имени compute @@ -42,7 +44,7 @@ data "decort_cb_rg_list_computes" "list_computes" { #фильтр по id аккаунта #опциональный параметр - #тип - число + #тип - целое число #account_id = 100 #фильтр по техническому статусу @@ -67,18 +69,24 @@ data "decort_cb_rg_list_computes" "list_computes" { #фильтр по id внешней сети #опциональный параметр - #тип - число + #тип - целое число #extnet_id = 100 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudbroker/data_rg_list_deleted/main.tf b/samples/cloudbroker/rg/data_rg_list_deleted/main.tf similarity index 81% rename from samples/cloudbroker/data_rg_list_deleted/main.tf rename to samples/cloudbroker/rg/data_rg_list_deleted/main.tf index e6a2c09..357ba43 100644 --- a/samples/cloudbroker/data_rg_list_deleted/main.tf +++ b/samples/cloudbroker/rg/data_rg_list_deleted/main.tf @@ -2,18 +2,21 @@ Пример использования Получение информации о списке удаленных ресурсных групп */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* terraform { +/* +terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,7 +30,7 @@ provider "decort" { data "decort_cb_rg_list_deleted" "list_deleted" { #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени ресурсной группы @@ -37,7 +40,7 @@ data "decort_cb_rg_list_deleted" "list_deleted" { #id аккаунта для получения списка ресурсных групп #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по имени аккаунта @@ -47,12 +50,12 @@ data "decort_cb_rg_list_deleted" "list_deleted" { #фильтр по времени создания (после указанного времени) #опциональный параметр - #тип - число + #тип - целое число #created_after = 123 #фильтр по времени создания (перед указанным временем) #опциональный параметр - #тип - число + #тип - целое число #created_before = 123 #фильтр по lock status @@ -60,14 +63,20 @@ data "decort_cb_rg_list_deleted" "list_deleted" { #тип - строка #lock_status = "UNLOCKED" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы #необязательный параметр - #тип - число + #тип - целое число #page = 1 #размер страницы #необязательный параметр - #тип - число + #тип - целое число #size = 2 } diff --git a/samples/cloudbroker/data_rg_list_lb/main.tf b/samples/cloudbroker/rg/data_rg_list_lb/main.tf similarity index 84% rename from samples/cloudbroker/data_rg_list_lb/main.tf rename to samples/cloudbroker/rg/data_rg_list_lb/main.tf index 2a9318e..77d4f0f 100644 --- a/samples/cloudbroker/data_rg_list_lb/main.tf +++ b/samples/cloudbroker/rg/data_rg_list_lb/main.tf @@ -2,18 +2,21 @@ Пример использования Получение информации о списке балансировщиков в ресурсной группе */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* terraform { +/* +terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,12 +30,12 @@ provider "decort" { data "decort_cb_rg_list_lb" "list_lb" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #фильтр по id балансировщика нагрузки #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени балансировщика нагрузки @@ -40,11 +43,6 @@ data "decort_cb_rg_list_lb" "list_lb" { #тип - строка #name = "test" - #id аккаунта для получения списка балансировщиков нагрузки - #опциональный параметр - #тип - число - #account_id = 11111 - #фильтр по техническому статусу #опциональный параметр #тип - строка @@ -65,15 +63,21 @@ data "decort_cb_rg_list_lb" "list_lb" { #тип - строка #back_ip = "1.1.1.1" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudbroker/data_rg_list_pfw/main.tf b/samples/cloudbroker/rg/data_rg_list_pfw/main.tf similarity index 95% rename from samples/cloudbroker/data_rg_list_pfw/main.tf rename to samples/cloudbroker/rg/data_rg_list_pfw/main.tf index 7bd8aff..13f9292 100644 --- a/samples/cloudbroker/data_rg_list_pfw/main.tf +++ b/samples/cloudbroker/rg/data_rg_list_pfw/main.tf @@ -2,18 +2,21 @@ Пример использования Получение информации о списке правил переадресации портов для ресурсной группы. */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* terraform { +/* +terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,7 +30,7 @@ provider "decort" { data "decort_cb_rg_list_pfw" "list_pfw" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 } diff --git a/samples/cloudbroker/rg/data_rg_list_vins/main.tf b/samples/cloudbroker/rg/data_rg_list_vins/main.tf new file mode 100644 index 0000000..742b45f --- /dev/null +++ b/samples/cloudbroker/rg/data_rg_list_vins/main.tf @@ -0,0 +1,77 @@ +/* +Пример использования +Получение информации о списке винсов в ресурсной группе +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_rg_list_vins" "list_vins" { + #id ресурсной группы + #обязательный параметр + #тип - целое число + rg_id = 123 + + #фильтр по id vins + #опциональный параметр + #тип - целое число + #vins_id = 100 + + #фильтр по имени vins + #опциональный параметр + #тип - строка + #name = "test" + + #id аккаунта для получения списка балансировщиков нагрузки + #опциональный параметр + #тип - целое число + #account_id = 11111 + + #фильтр по IP внешней сети + #опциональный параметр + #тип - строка + #ext_ip = "test" + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + + #номер страницы для отображения + #опциональный параметр + #тип - целое число + #если не задан - выводятся все доступные данные + #page = 2 + + #размер страницы + #опциональный параметр + #тип - целое число + #если не задан - выводятся все доступные данные + #size = 3 +} + +output "output" { + value = data.decort_cb_rg_list_vins.list_vins +} diff --git a/samples/cloudbroker/data_rg_resource_consumption_list/main.tf b/samples/cloudbroker/rg/data_rg_resource_consumption_list/main.tf similarity index 95% rename from samples/cloudbroker/data_rg_resource_consumption_list/main.tf rename to samples/cloudbroker/rg/data_rg_resource_consumption_list/main.tf index 591af4a..8ad0518 100644 --- a/samples/cloudbroker/data_rg_resource_consumption_list/main.tf +++ b/samples/cloudbroker/rg/data_rg_resource_consumption_list/main.tf @@ -1,20 +1,23 @@ /* +Пример использования Получение списка текущего потребления ресурсов */ #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером + /* terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = diff --git a/samples/cloudbroker/data_rg_usage/main.tf b/samples/cloudbroker/rg/data_rg_usage/main.tf similarity index 90% rename from samples/cloudbroker/data_rg_usage/main.tf rename to samples/cloudbroker/rg/data_rg_usage/main.tf index b99862d..d16b565 100644 --- a/samples/cloudbroker/data_rg_usage/main.tf +++ b/samples/cloudbroker/rg/data_rg_usage/main.tf @@ -1,19 +1,22 @@ /* Пример использования -Получение информации об использовании ресурсов на ресурсной группе +Получение информации об использовании ресурсов в ресурсной группе */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером -/* terraform { +/* +terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } -} */ +} +*/ provider "decort" { authenticator = "decs3o" @@ -27,7 +30,7 @@ provider "decort" { data "decort_cb_rg_usage" "rg_usage" { #id ресурсной группы #обязательный параметр - #тип - число + #тип - целое число rg_id = 123 #причина для действия diff --git a/samples/cloudbroker/resource_rg/main.tf b/samples/cloudbroker/rg/resource_rg/main.tf similarity index 74% rename from samples/cloudbroker/resource_rg/main.tf rename to samples/cloudbroker/rg/resource_rg/main.tf index 195b12b..7d1ae2e 100644 --- a/samples/cloudbroker/resource_rg/main.tf +++ b/samples/cloudbroker/rg/resource_rg/main.tf @@ -2,10 +2,11 @@ Пример использования Ресурсов RG Ресурс позволяет: -1. Создавать -2. Редактировать -3. Удалять +1. Создавать RG +2. Редактировать RG +3. Удалять RG */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -13,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -37,41 +38,41 @@ resource "decort_cb_rg" "rg" { #id аккаунта которому будет принадлежать ресурсная группа #обязательный параметр - #тип - число + #тип - целое число account_id = 123 #id сети #обязательный параметр - #тип - число + #тип - целое число gid = 1234 #лимиты ресурсов #опциональные параметры - #тип - блок + #тип - блок лимитов на ресурсы #resource_limits { - #max number of cpu cores - #опциональный праметр при использовании блока - #тип - число + #максимальное количество ядер cpu + #опциональный праметр + #тип - целое число #cu_c = 12 - #max size of aggregated vdisks in GB - #опциональный праметр при использовании блока - #тип - число + #максимальный размер агрегированных виртуальных дисков в ГБ + #опциональный параметр + #тип - целое число #cu_dm = 12 - #max number of assigned public IPs - #опциональный праметр при использовании блока - #тип - число + #максимальное количество назначенных общедоступных IP-адресов + #опциональный праметр + #тип - целое число #cu_i = 12 - #max size of memory in MB - #опциональный праметр при использовании блока - #тип - число + #максимальный объем памяти в МБ + #опциональный праметр + #тип - целое число #cu_m = 12 - #max sent/received network transfer peering - #опциональный праметр при использовании блока - #тип - число + #максимальный пиринг отправленных/принятых сетевых передач + #опциональный праметр + #тип - целое число #cu_np = 12 #} @@ -99,7 +100,7 @@ resource "decort_cb_rg" "rg" { #id внешней сети #необязательный параметр - #тип - число + #тип - целое число #ext_net_id = 123 #ip внешней сети @@ -124,7 +125,7 @@ resource "decort_cb_rg" "rg" { #блок для предоставления прав на ресурсную группу #необязательный параметр - #тип - блок + #тип - блок прав пользователя access { #имя юзера предоставляемому права #обязательный праметр при использовании блока @@ -143,9 +144,9 @@ resource "decort_cb_rg" "rg" { reason = "test" } - #Установить сеть по умолчанию + #установить сеть по умолчанию #необязательный параметр - #тип - блок + #тип - блок конфигурации сети #при добавлении блока, удалять его нельзя def_net { #тип сети @@ -159,7 +160,7 @@ resource "decort_cb_rg" "rg" { #имеет значение PRIVATE и net_id=0, будет выбран первый vins, определенный для этой ресурсной группы. #В противном случае net_id идентифицирует либо существующий сегмент внешней сети, либо vins. #необязательный параметр - #тип - число + #тип - целое число net_id = 1234 #причина выполнения @@ -177,31 +178,39 @@ resource "decort_cb_rg" "rg" { #CPU allocation ratio #необязательный параметр #one pCPU = ratio*vCPU (zero or positive value) - #тип - число + #тип - целое число cpu_allocation_ratio = 1 #флаг доступности ресурсной группы #необязательный параметр - #тип - булевый + #тип - булев enable = true #флаг для восстановления удаленной ресурсной группы #необязательный параметр - #тип - булевый + #тип - булев #restore = false #флаг для принудительного удаления ресурсной группы #необязательный параметр - #тип - булевый + #тип - булев #перед удалением следует перевести ресурсную группу в статус disabled, выставив enable = false force = true #флаг для моментального удаления ресурсной группы #необязательный параметр - #тип - булевый + #тип - булев permanently = true -} + #доступ к дополнительным функциям управления ВМ + #необязательный параметр + #возможные значенния - "hugepages", "numa", "cpupin", "vfnic" + #тип - массив строк + #внимание - требуется указывать итоговое желаемое состояние для ресурсной группы (рг), так как поле compute_features не будет автоматически + #наследоваться от аккаунта, в котором создается рг. + compute_features = ["hugepages", "numa", "cpupin", "vfnic"] + +} output "output" { value = decort_cb_rg.rg diff --git a/samples/cloudbroker/data_sep/main.tf b/samples/cloudbroker/sep/data_sep/main.tf similarity index 96% rename from samples/cloudbroker/data_sep/main.tf rename to samples/cloudbroker/sep/data_sep/main.tf index 5cc4f4c..2267ea5 100644 --- a/samples/cloudbroker/data_sep/main.tf +++ b/samples/cloudbroker/sep/data_sep/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных sep */ + #Расскомментируйте код ниже, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,9 +29,8 @@ provider "decort" { data "decort_cb_sep" "sd" { #id sep #обязательный параметр - #тип - число + #тип - целое число sep_id = 1111 - } output "test" { diff --git a/samples/cloudbroker/data_sep_config/main.tf b/samples/cloudbroker/sep/data_sep_config/main.tf similarity index 96% rename from samples/cloudbroker/data_sep_config/main.tf rename to samples/cloudbroker/sep/data_sep_config/main.tf index da3f737..ff2b9d8 100644 --- a/samples/cloudbroker/data_sep_config/main.tf +++ b/samples/cloudbroker/sep/data_sep_config/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных конфигурации sep */ + #Расскомментируйте код ниже, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_sep_config" "sc" { #id sep #обязательный параметр - #тип - число + #тип - целое число sep_id = 1111 } diff --git a/samples/cloudbroker/data_sep_consumption/main.tf b/samples/cloudbroker/sep/data_sep_consumption/main.tf similarity index 96% rename from samples/cloudbroker/data_sep_consumption/main.tf rename to samples/cloudbroker/sep/data_sep_consumption/main.tf index 1a0e8ca..73e519f 100644 --- a/samples/cloudbroker/data_sep_consumption/main.tf +++ b/samples/cloudbroker/sep/data_sep_consumption/main.tf @@ -2,6 +2,7 @@ Пример использования Получение общих данных об использовании sep */ + #Расскомментируйте код ниже, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_sep_consumption" "scons" { #id sep #обязательный параметр - #тип - число + #тип - целое число sep_id = 1111 } diff --git a/samples/cloudbroker/data_sep_disk_list/main.tf b/samples/cloudbroker/sep/data_sep_disk_list/main.tf similarity index 97% rename from samples/cloudbroker/data_sep_disk_list/main.tf rename to samples/cloudbroker/sep/data_sep_disk_list/main.tf index 5b39586..1710ff9 100644 --- a/samples/cloudbroker/data_sep_disk_list/main.tf +++ b/samples/cloudbroker/sep/data_sep_disk_list/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_sep_disk_list" "sdl" { #id sep #обязательный параметр - #тип - число + #тип - целое число sep_id = 1111 #sep pool name diff --git a/samples/cloudbroker/data_sep_list/main.tf b/samples/cloudbroker/sep/data_sep_list/main.tf similarity index 79% rename from samples/cloudbroker/data_sep_list/main.tf rename to samples/cloudbroker/sep/data_sep_list/main.tf index 287ba5b..8d0300f 100644 --- a/samples/cloudbroker/data_sep_list/main.tf +++ b/samples/cloudbroker/sep/data_sep_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка sep */ + #Расскомментируйте код ниже, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,12 +10,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -27,7 +29,7 @@ provider "decort" { data "decort_cb_sep_list" "sl" { #фильтр по sep id #необязательный параметр - #тип - число + #тип - целое число #by_id = 3 #фильтр по sep name @@ -37,7 +39,7 @@ data "decort_cb_sep_list" "sl" { #фильтр по gid #необязательный параметр - #тип - число + #тип - целое число #gid = 1 #фильтр по sep type @@ -47,7 +49,7 @@ data "decort_cb_sep_list" "sl" { #фильтр по provided physical node id #необязательный параметр - #тип - число + #тип - целое число #provided_by = 1 #фильтр по тех статусу @@ -57,17 +59,23 @@ data "decort_cb_sep_list" "sl" { #фильтр по consumed physical node id #необязательный параметр - #тип - число + #тип - целое число #consumed_by = 1 + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #страница #необязательный параметр - #тип - число + #тип - целое число #page = 3 #размер страницы #необязательный параметр - #тип - число + #тип - целое число #size = 2 } diff --git a/samples/cloudbroker/data_sep_pool/main.tf b/samples/cloudbroker/sep/data_sep_pool/main.tf similarity index 96% rename from samples/cloudbroker/data_sep_pool/main.tf rename to samples/cloudbroker/sep/data_sep_pool/main.tf index dbfdd04..fed987e 100644 --- a/samples/cloudbroker/data_sep_pool/main.tf +++ b/samples/cloudbroker/sep/data_sep_pool/main.tf @@ -1,8 +1,8 @@ /* Пример использования Получение данных sep pool - */ + #Расскомментируйте код ниже, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_sep_pool" "sp" { #id sep #обязательный параметр - #тип - число + #тип - целое число sep_id = 1111 #sep pool name diff --git a/samples/cloudbroker/resource_sep/main.tf b/samples/cloudbroker/sep/resource_sep/main.tf similarity index 52% rename from samples/cloudbroker/resource_sep/main.tf rename to samples/cloudbroker/sep/resource_sep/main.tf index 9a2f191..91b6875 100644 --- a/samples/cloudbroker/resource_sep/main.tf +++ b/samples/cloudbroker/sep/resource_sep/main.tf @@ -6,8 +6,8 @@ 2. Редактировать sep. 3. Удалять sep. 4. Конфигурировать sep. - */ + #Расскомментируйте код ниже, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -15,12 +15,13 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } */ + provider "decort" { authenticator = "decs3o" #controller_url = @@ -33,7 +34,7 @@ provider "decort" { resource "decort_cb_sep" "s" { #grid id #обязательный параметр - #тип - число + #тип - целое число gid = 212 #sep name @@ -43,104 +44,117 @@ resource "decort_cb_sep" "s" { #тип sep #обязательный параметр - #тип - строка #возможные значения - des, dorado, tatlin, hitachi - type = "des" - - #описание sep - #необязательный параметр, используется при создании ресурса #тип - строка - #desc = "rrrrr" + type = "des" #конфигурация sep - #необязательный параметр, мб применен при создании или редактировании sep + #обязательный параметр + #мб применен при создании или редактировании sep #представляет собой json-строку #тип - строка - #config = file("./config.json") + config = file("./config.json") + + #описание sep + #опциональный параметр + #используется при создании ресурса + #тип - строка + #desc = "rrrrr" #изменение поля в конфигурации - #необязательный параметр, может быть применен на уже созданном sep - #тип - объект + #опциональный параметр + #может быть применен на уже созданном sep #внимание, во избежание конфликтов не использовать с полем config - /* - field_edit { + #тип - блок поля + #field_edit { #имя поля #обязательный параметр #тип - строка - field_name = "edgeuser_password" - + #field_name = "edgeuser_password" + #значение поля #обязательный параметр #тип - json строка - field_value = "mosk" + #field_value = "mosk" #тип значения #обязательный параметр - #тип - строка, возможные значения: list,dict,int,bool,str - field_type = "str" - } - */ + #возможные значения: list,dict,int,bool,str + #тип - строка + #field_type = "str" + #} #предоставление/отключение доступа указанных аккаунтов к sep - #необязательный параметр, используется при редактировании и создании ресурса - #тип - массив чисел + #опциональный параметр, используется при редактировании и создании ресурса + #тип - массив целых чисел #account_ids = [12, 245] #предоставление/отключение доступа к пулу на sep - #необязательный параметр, может быть применен на уже созданном sep - #тип - объект - /* - access_to_pool { + #опциональный параметр, может быть применен на уже созданном sep + #тип - блок доступа к пулу + #access_to_pool { #имя pool #обязательный параметр #тип - строка - pool_name = "pool name" + #pool_name = "pool name" #id аккаунта - #необязательный параметр - #тип - число + #опциональный параметр + #тип - целое число #account_id_pool = 123 #id ресурсной группы - #необязательный параметр - #тип - число - #rg_id = 1234 - } - */ + #опциональный параметр + #тип - целое число + #rg_id = 1234 + #} #доступность sep - #необязательный параметр, может быть применен на уже созданном ресурсе - #тип - булево значение - #дефолтное значение false - #enable = false + #опциональный параметр + #может быть применен на уже созданном ресурсе + #по умолчанию - false + #тип - булев + #enable = false #использование нодами - #необязательный параметр, используется при редактировании и создании ресурса - #тип - массив чисел - #consumed_by = [] + #опциональный параметр + #используется при редактировании и создании ресурса + #тип - массив целых чисел + #consumed_by = [] #обновление лимита объема - #необязательный параметр, применяется на уж созданном ресурсе - #тип - булев тип + #опциональный параметр + #применяется на уж созданном ресурсе + #тип - булев #upd_capacity_limit = true #id provided nodes - #необязательный параметр, используется при редактировании и создании ресурса - #тип - массив чисел + #опциональный параметр + #используется при редактировании и создании ресурса + #тип - массив целых чисел #provided_by = [16, 14, 15] #отключение nodes - #необязательный параметр, применяется на уже созданном ресурсе - #тип - булев тип + #опциональный параметр + #применяется на уже созданном ресурсе #используется в связке с clear_physically - #дефолтное значение true - #decommission = true + #по умолчанию - true + #тип - булев + #decommission = true #физическое очищение nodes - #необязательный параметр, используется при удалении ресурса - #тип - булев тип + #опциональный параметр + #используется при удалении ресурса #внимание, во избежание конфликтов использовать только в связке с полем decommission = true + #тип - булев #clear_physically = false + + #добавление/удаление pools к/из sep + #опциональный параметр + #используется при редактировании и создании ресурса, состоит из имен pool + #тип - массив строк + #pools = ["data01", "data02"] + } output "test" { diff --git a/samples/cloudbroker/resource_sep_config/main.tf b/samples/cloudbroker/sep/resource_sep_config/main.tf similarity index 78% rename from samples/cloudbroker/resource_sep_config/main.tf rename to samples/cloudbroker/sep/resource_sep_config/main.tf index c1d1a1e..532fb3d 100644 --- a/samples/cloudbroker/resource_sep_config/main.tf +++ b/samples/cloudbroker/sep/resource_sep_config/main.tf @@ -6,6 +6,7 @@ 2. Изменять конфигурацию 3. Изменять отдельные поля конфигурации */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -13,8 +14,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -32,36 +33,37 @@ provider "decort" { resource "decort_cb_sep_config" "sc" { #id sep #обязательный параметр - #тип - число + #тип - целое число sep_id = 1111 #конфигурация - #необязательное поле, используется для создания и изменения конфигурации - #тип - json-строка + #опциональный параметр + #используется для создания и изменения конфигурации + #тип - json строка #config = file("./config.json") #редактирование поля - #необязательный параметр, используется при редактировании ресурса - #тип - объект - /* - field_edit { + #опциональный параметр + #используется при редактировании ресурса + #тип - блок полей + #field_edit { #имя поля #обязательный параметр #тип - строка - field_name = "edgeuser_password" + #field_name = "edgeuser_password" #значение поля #обязательный параметр #тип - строка - field_value = "shshs" + #field_value = "shshs" #тип поля #обязательный параметр - #тип - строка #возможные значения - int,bool, str, dict, list - field_type = "str" - } - */ + #тип - строка + #field_type = "str" + #} + } output "sep_config" { diff --git a/samples/cloudbroker/data_stack/main.tf b/samples/cloudbroker/stack/data_stack/main.tf similarity index 96% rename from samples/cloudbroker/data_stack/main.tf rename to samples/cloudbroker/stack/data_stack/main.tf index 4296c32..8ba3aa9 100644 --- a/samples/cloudbroker/data_stack/main.tf +++ b/samples/cloudbroker/stack/data_stack/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,8 +29,9 @@ provider "decort" { data "decort_cb_stack" "stack" { #id стека #обязательный параметр - #тип - число + #тип - целое число stack_id = 1 + } output "test" { diff --git a/samples/cloudbroker/data_stack_list/main.tf b/samples/cloudbroker/stack/data_stack_list/main.tf similarity index 80% rename from samples/cloudbroker/data_stack_list/main.tf rename to samples/cloudbroker/stack/data_stack_list/main.tf index ad8c568..4310c03 100644 --- a/samples/cloudbroker/data_stack_list/main.tf +++ b/samples/cloudbroker/stack/data_stack_list/main.tf @@ -10,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -29,7 +29,7 @@ provider "decort" { data "decort_cb_stack_list" "sl" { #фильтр стеков по id #опциональный параметр - #тип - число + #тип - целое число #by_id = 111 #фильтр по имени стека @@ -47,15 +47,22 @@ data "decort_cb_stack_list" "sl" { #тип - строка #status = "status" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #page = 2 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #size = 3 + } output "test" { diff --git a/samples/cloudapi/data_vins/main.tf b/samples/cloudbroker/user/data_user/main.tf similarity index 82% rename from samples/cloudapi/data_vins/main.tf rename to samples/cloudbroker/user/data_user/main.tf index 009e6cf..407508f 100644 --- a/samples/cloudapi/data_vins/main.tf +++ b/samples/cloudbroker/user/data_user/main.tf @@ -1,7 +1,8 @@ /* Пример использования -Получение данных о vins +Получение данных user по id */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -25,14 +26,15 @@ provider "decort" { allow_unverified_ssl = true } -data "decort_vins" "vins" { +data "decort_cb_user" "user" { + #id user #обязательный параметр - #id жедаемого vins - #тип - число - vins_id = 10101 - + #тип - строка + user_id = "" + } output "test" { - value = data.decort_vins.vins + value = data.decort_cb_user.user } + diff --git a/samples/cloudbroker/user/data_user_get_audit/main.tf b/samples/cloudbroker/user/data_user_get_audit/main.tf new file mode 100644 index 0000000..35454fb --- /dev/null +++ b/samples/cloudbroker/user/data_user_get_audit/main.tf @@ -0,0 +1,70 @@ +/* +Пример использования +Получение списка аудитов пользователя +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_user_get_audit" "audits" { + #имя пользователя + #опциональный параметр + #если не указано, выводит данные по текущему пользователю + #тип - строка + #username = "test_user" + + #фильтр по вызову api + #опциональный параметр + #тип - строка + #call = "restapi/user/get" + + #фильтр по статус коду ответа + #опциональный параметр + #тип - целое число + #status_code = 200 + + #фильтр по временной метке, после которой были сделаны запросы + #опциональный параметр + #тип - целое число + #timestamp_at = 123456 + + #фильтр по временной метке, до которой были сделаны запросы + #опциональный параметр + #тип - целое число + #timestamp_to = 123456 + + #номер страницы для отображения + #опциональный параметр + #тип - целое число + #page = 2 + + #размер страницы + #опциональный параметр + #тип - целое число + #size = 3 + +} + +output "test" { + value = data.decort_cb_user_get_audit.audits +} diff --git a/samples/cloudbroker/user/data_user_list/main.tf b/samples/cloudbroker/user/data_user_list/main.tf new file mode 100644 index 0000000..21bc91c --- /dev/null +++ b/samples/cloudbroker/user/data_user_list/main.tf @@ -0,0 +1,65 @@ +/* +Пример использования +Получение списка пользователей +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_user_list" "users" { + #фильтр по id пользователя + #опциональный параметр + #тип - строка + #by_id = "test_user" + + #фильтр по активным пользователям + #опциональный параметр + #тип - булев + #active = true + + #фильтр по сервисным аккаунтам + #опциональный параметр + #тип - булев + #service_account = true + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + + #номер страницы для отображения + #опциональный параметр + #тип - целое число + #page = 2 + + #размер страницы + #опциональный параметр + #тип - целое число + #size = 3 + +} + +output "test" { + value = data.decort_cb_user_list.users +} diff --git a/samples/cloudbroker/user/resource_user/main.tf b/samples/cloudbroker/user/resource_user/main.tf new file mode 100644 index 0000000..aaab698 --- /dev/null +++ b/samples/cloudbroker/user/resource_user/main.tf @@ -0,0 +1,64 @@ +/* +Пример использования +Ресурса user +Ресурс позволяет: +1. Создавать пользователя +2. Изменять список apiaccess групп пользователя +3. Удалять пользователя +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://mr4.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_user" "user" { + #id пользователя + #обязательный параметр + #тип - строка + username = "user1" + + #email адрес пользователя + #обязательный параметр + #тип - массив строк + emailaddress = ["user1@example.com"] + + #пароль пользователя + #опциональный параметр + #тип - строка + #password = "user1Password" + + #список групп, к которым принадлежит этот пользователь + #опциональный параметр + #тип - массив строк + #groups = ["user"] + + #список групп доступа к api, к которым принадлежит этот пользователь + #опциональный параметр + #тип - массив целых чисел + #apiaccess = [1,2] + +} + +output "test" { + value = decort_cb_user.user +} + diff --git a/samples/cloudbroker/vfpool/data_vfpool/main.tf b/samples/cloudbroker/vfpool/data_vfpool/main.tf new file mode 100644 index 0000000..31ee783 --- /dev/null +++ b/samples/cloudbroker/vfpool/data_vfpool/main.tf @@ -0,0 +1,40 @@ +/* +Пример использования +Получение информации о vfpool по его id +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_vfpool" "vfpool" { + #идентификатор vfpool + #обязательный параметр + #тип - целое число + vfpool_id = 2 + +} + +output "test" { + value = data.decort_cb_vfpool.vfpool +} + diff --git a/samples/cloudbroker/vfpool/data_vfpool_list/main.tf b/samples/cloudbroker/vfpool/data_vfpool_list/main.tf new file mode 100644 index 0000000..e8398cf --- /dev/null +++ b/samples/cloudbroker/vfpool/data_vfpool_list/main.tf @@ -0,0 +1,88 @@ +/* +Пример использования +Получение списка vfpool +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +data "decort_cb_vfpool_list" "vfpool_list" { + #фильтрация списка для получения информации о конкретном vfpool по его id + #опциональный параметр + #тип - целое число + #by_id = 1 + + #фильтрация списка для получения информации о vfpool, которые принадлежат к определенному GRID + #опциональный параметр + #тип - целое число + #gid = 1 + + #фильтрация списка для получения информации о конкретном vfpool по его имени + #опциональный параметр + #тип - строка + #name = "alpha-cpu-04" + + #фильтрация списка для получения информации о конкретном vfpool по его описанию + #опциональный параметр + #тип - строка + #description = "some" + + #фильтрация списка для получения информации о vfpool, которые имеют соответствующий статус + #опциональный параметр + #тип - строка + #status = "ENABLED" + + #фильтрация списка для получения информации о vfpool, которые доступны конкретному аккаунту + #опциональный параметр + #тип - целое число + #account_access = 1 + + #фильтрация списка для получения информации о vfpool, которые доступны конкретной ресурсной группе + #опциональный параметр + #тип - целое число + #rg_access = 1 + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #формат - "+поле" по возрастанию / "-поле" по убыванию + #тип - строка + #sort_by = "+name" + + #номер страницы для отображения + #опциональный параметр + #если не задан - выводятся все доступные данные + #тип - целое число + #page = 2 + + #размер страницы + #опциональный параметр + #если не задан - выводятся все доступные данные + #тип - целое число + #size = 3 + +} + +output "test" { + value = data.decort_cb_vfpool_list.vfpool_list +} + diff --git a/samples/cloudbroker/vfpool/resource_vfpool/main.tf b/samples/cloudbroker/vfpool/resource_vfpool/main.tf new file mode 100644 index 0000000..478f0b8 --- /dev/null +++ b/samples/cloudbroker/vfpool/resource_vfpool/main.tf @@ -0,0 +1,87 @@ +/* +Пример использования +Ресурс позволяет: +1. Создавать пул виртуальных сетевых функций +2. Изменять список аккаунтов, которым доступен пул +3. Изменять список ресурсных групп, которым доступен пул +4. Изменять статус пула +5. Изменять наименование или описание пула +6. Изменять конфигурацию пула +7. Удалять пул +*/ + +#Расскомментируйте этот код, +#и внесите необходимые правки в версию и путь, +#чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером +/* +terraform { + required_providers { + decort = { + source = "basis/decort/decort" + version = "" + } + } +} +*/ + +provider "decort" { + authenticator = "decs3o" + #controller_url = + controller_url = "https://ds1.digitalenergy.online" + #oauth2_url = + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} + +resource "decort_cb_vfpool" "vfpool" { + #наименование vfpool + #обязательный параметр + #тип - строка + name = "test" + + #описание vfpool + #опциональный параметр + #тип - строка + #применяется при создании и редактировании ресурса + #description = "some" + + #список для предоставления доступа к vfpool перечисленным аккаунтам + #опциональный параметр + #тип - массив целых чисел + #применяется при создании и редактировании ресурса + #account_access = [1,2] + + #список для предоставления доступа к vfpool перечисленным ресурсным группам + #опциональный параметр + #тип - массив целых чисел + #применяется при создании и редактировании ресурса + #rg_access = [1,2] + + #блок для указания списка конфигурации + #опциональный параметр + #тип - блок + #config = { + #идентификатор узла + #обязательный параметр + #тип - целое число + #node_id = 1 + + #имя верхнеуровневого сетевого интерфейса, VF которого входят в пул + #обязательный параметр + #тип - строка + #nic_name = "eth0" + + #список идентификаторов VF для NIC узла + #обязательный параметр + #тип - массив целых чисел + #vf_ids = [1,2] + #} + + #ручное подключение и отключение ресурса + #опциональный параметр + #тип - булев + #enable = true +} + + + diff --git a/samples/cloudbroker/data_vins/main.tf b/samples/cloudbroker/vins/data_vins/main.tf similarity index 92% rename from samples/cloudbroker/data_vins/main.tf rename to samples/cloudbroker/vins/data_vins/main.tf index f796a3b..68a0f8d 100644 --- a/samples/cloudbroker/data_vins/main.tf +++ b/samples/cloudbroker/vins/data_vins/main.tf @@ -2,6 +2,7 @@ Пример использования Получение данных о vins */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,13 +27,13 @@ provider "decort" { } data "decort_cb_vins" "vins" { - #обязательный параметр #id желаемого vins - #тип - число + #обязательный параметр + #тип - целое число vins_id = 10101 - #необязательный параметр #причина запроса + #опциональный параметр #тип - строка #reason = "report" } diff --git a/samples/cloudbroker/data_vins_audits/main.tf b/samples/cloudbroker/vins/data_vins_audits/main.tf similarity index 96% rename from samples/cloudbroker/data_vins_audits/main.tf rename to samples/cloudbroker/vins/data_vins_audits/main.tf index 9a9a426..5bbff8b 100644 --- a/samples/cloudbroker/data_vins_audits/main.tf +++ b/samples/cloudbroker/vins/data_vins_audits/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка vins audits */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -26,9 +27,9 @@ provider "decort" { } data "decort_cb_vins_audits" "vins_audits" { - #обязательный параметр #id желаемого vins - #тип - число + #обязательный параметр + #тип - целое число vins_id = 10101 } diff --git a/samples/cloudbroker/data_vins_ext_net_list/main.tf b/samples/cloudbroker/vins/data_vins_ext_net_list/main.tf similarity index 96% rename from samples/cloudbroker/data_vins_ext_net_list/main.tf rename to samples/cloudbroker/vins/data_vins_ext_net_list/main.tf index 5d443d4..98b140a 100644 --- a/samples/cloudbroker/data_vins_ext_net_list/main.tf +++ b/samples/cloudbroker/vins/data_vins_ext_net_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка vins extnet */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,9 +27,9 @@ provider "decort" { } data "decort_cb_vins_ext_net_list" "vins_ext_net_list" { - #обязательный параметр #id желаемого vins - #тип - число + #обязательный параметр + #тип - целое число vins_id = 10101 } diff --git a/samples/cloudbroker/data_vins_ip_list/main.tf b/samples/cloudbroker/vins/data_vins_ip_list/main.tf similarity index 96% rename from samples/cloudbroker/data_vins_ip_list/main.tf rename to samples/cloudbroker/vins/data_vins_ip_list/main.tf index c8c99cb..5a0f290 100644 --- a/samples/cloudbroker/data_vins_ip_list/main.tf +++ b/samples/cloudbroker/vins/data_vins_ip_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка vins_ip */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,9 +27,9 @@ provider "decort" { } data "decort_cb_vins_ip_list" "vins_ip_list" { - #обязательный параметр #id желаемого vins - #тип - число + #обязательный параметр + #тип - целое число vins_id = 10101 } diff --git a/samples/cloudbroker/data_vins_list/main.tf b/samples/cloudbroker/vins/data_vins_list/main.tf similarity index 77% rename from samples/cloudbroker/data_vins_list/main.tf rename to samples/cloudbroker/vins/data_vins_list/main.tf index 8410c4d..371bac8 100644 --- a/samples/cloudbroker/data_vins_list/main.tf +++ b/samples/cloudbroker/vins/data_vins_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка vins */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_vins_list" "vl" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени vins @@ -38,12 +39,12 @@ data "decort_cb_vins_list" "vl" { #id аккаунта для получения списка vins #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по IP внешней сети @@ -51,21 +52,32 @@ data "decort_cb_vins_list" "vl" { #тип - строка #ext_ip = "test" + #фильтр по id vnfDevices + #опциональный параметр + #тип - целое число + #vnfdev_id = 11111 + #включение удаленных vins в результат #опциональный параметр - #тип - булев тип + #тип - булев #если не задан - выводятся все неудаленные данные #include_deleted = true + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #номер страницы для отображения #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #page = 1 #размер страницы #опциональный параметр - #тип - число + #тип - целое число #если не задан - выводятся все доступные данные #size = 1 } diff --git a/samples/cloudbroker/data_vins_list_deleted/main.tf b/samples/cloudbroker/vins/data_vins_list_deleted/main.tf similarity index 75% rename from samples/cloudbroker/data_vins_list_deleted/main.tf rename to samples/cloudbroker/vins/data_vins_list_deleted/main.tf index 4f16906..9730d25 100644 --- a/samples/cloudbroker/data_vins_list_deleted/main.tf +++ b/samples/cloudbroker/vins/data_vins_list_deleted/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка удаленных vins */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,7 +29,7 @@ provider "decort" { data "decort_cb_vins_list_deleted" "vins_list_deleted" { #фильтр по id vins #опциональный параметр - #тип - число + #тип - целое число #by_id = 100 #фильтр по имени vins @@ -38,12 +39,12 @@ data "decort_cb_vins_list_deleted" "vins_list_deleted" { #id аккаунта для получения списка vins #опциональный параметр - #тип - число + #тип - целое число #account_id = 11111 #фильтр по id ресурсной группы #опциональный параметр - #тип - число + #тип - целое число #rg_id = 100 #фильтр по IP внешней сети @@ -51,14 +52,20 @@ data "decort_cb_vins_list_deleted" "vins_list_deleted" { #тип - строка #ext_ip = "test" + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + #кол-во страниц для вывода - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #page = 1 #размер страницы - #опицональный параметр - #тип - число + #опциональный параметр + #тип - целое число #size = 1 } diff --git a/samples/cloudbroker/data_vins_nat_rule_list/main.tf b/samples/cloudbroker/vins/data_vins_nat_rule_list/main.tf similarity index 93% rename from samples/cloudbroker/data_vins_nat_rule_list/main.tf rename to samples/cloudbroker/vins/data_vins_nat_rule_list/main.tf index 245493a..c99bb20 100644 --- a/samples/cloudbroker/data_vins_nat_rule_list/main.tf +++ b/samples/cloudbroker/vins/data_vins_nat_rule_list/main.tf @@ -2,6 +2,7 @@ Пример использования Получение списка natRule vins */ + #Расскомментируйте этот код, #и внесите необходимые правки в версию и путь, #чтобы работать с установленным вручную (не через hashicorp provider registry) провайдером @@ -9,8 +10,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -26,13 +27,13 @@ provider "decort" { } data "decort_cb_vins_nat_rule_list" "vins_nat_rule_list" { - #обязательный параметр #id желаемого vins - #тип - число + #обязательный параметр + #тип - целое число vins_id = 10101 - #необязательный параметр #причина вызова + #опциональный параметр #тип - строка #reason = "test" } diff --git a/samples/cloudbroker/data_vins_static_route/main.tf b/samples/cloudbroker/vins/data_vins_static_route/main.tf similarity index 93% rename from samples/cloudbroker/data_vins_static_route/main.tf rename to samples/cloudbroker/vins/data_vins_static_route/main.tf index fd55cf8..31365be 100644 --- a/samples/cloudbroker/data_vins_static_route/main.tf +++ b/samples/cloudbroker/vins/data_vins_static_route/main.tf @@ -1,6 +1,5 @@ /* Пример использования -vins static route Получение информации о static route в данном Vins */ @@ -11,8 +10,8 @@ vins static route terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,14 +27,14 @@ provider "decort" { } data "decort_cb_vins_static_route" "route" { - #обязательный параметр #id vins в котором добавлены routes - #тип - число + #обязательный параметр + #тип - целое число vins_id = 1111 + #id route #обязательный параметр - #id route - #тип - число + #тип - целое число route_id = 1 } diff --git a/samples/cloudbroker/data_vins_static_route_list/main.tf b/samples/cloudbroker/vins/data_vins_static_route_list/main.tf similarity index 95% rename from samples/cloudbroker/data_vins_static_route_list/main.tf rename to samples/cloudbroker/vins/data_vins_static_route_list/main.tf index 1583450..04437c0 100644 --- a/samples/cloudbroker/data_vins_static_route_list/main.tf +++ b/samples/cloudbroker/vins/data_vins_static_route_list/main.tf @@ -1,6 +1,5 @@ /* Пример использования -vins static route list Получение информации о всех static routes в данном Vins */ @@ -11,8 +10,8 @@ vins static route list terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -28,9 +27,9 @@ provider "decort" { } data "decort_cb_vins_static_route_list" "route" { - #обязательный параметр #id vins в котором добавлены routes - #тип - число + #обязательный параметр + #тип - целое число vins_id = 111 } diff --git a/samples/cloudbroker/resource_vins/main.tf b/samples/cloudbroker/vins/resource_vins/main.tf similarity index 72% rename from samples/cloudbroker/resource_vins/main.tf rename to samples/cloudbroker/vins/resource_vins/main.tf index 7329c63..7cb082e 100644 --- a/samples/cloudbroker/resource_vins/main.tf +++ b/samples/cloudbroker/vins/resource_vins/main.tf @@ -9,7 +9,6 @@ 5. Резервировать и освобождать ip для vins 6. Добавлять и удалять natrule 7. Перезапускать и редеплоить vnfdev - */ #Расскомментируйте этот код, @@ -19,8 +18,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -36,205 +35,204 @@ provider "decort" { } resource "decort_cb_vins" "vins" { - # Параметры для создания vins - #обязательный параметр #имя создаваемого ресурса #тип - строка name = "Test_name" - #опциональный параметр #id аккаунта для создаения ресурса - #тип - число + #опциональный параметр #внимание, для создания ресурса обязательно должен быть указан или rg_id, или account_id + #тип - целое число account_id = 2023 - #опциональный параметр #id ресурсной группы для создаения ресурса - #тип - число + #опциональный параметр #внимание, для создания ресурса обязательно должен быть указан или rg_id, или account_id + #тип - целое число rg_id = 10101 - #опциональный параметр #id внешней сети для подключения к ней ресурса - #тип - число + #опциональный параметр + #тип - целое число #ext_net_id = 2222 - #опциональный параметр #ip внешней сети для подключения к нему ресурса + #опциональный параметр #тип - строка #ext_ip = "1.1.1.1" + #приватная сеть IP CIDR #опциональный параметр - #private network IP CIDR #тип - строка - #ipcidr = "192.168.0.1" + #ipcidr = "192.168.0.1" - #опциональный параметр #количество зарезервированных адресов на момент создания - #тип - число + #опциональный параметр #значение по умолчанию 32 + #тип - целое число #pre_reservations_num = 2 - #опциональный параметр #grid (platform) ID - #тип - число - #gid = 2002 + #опциональный параметр + #тип - целое число + #gid = 2002 + #описание #опциональный параметр - #Description #тип - строка #description = "Description" + #причина запроса #опциональный параметр - #Причина запроса #тип - строка #reason = "test" - #опциональный параметр #блок для указания списка routes - #тип - блок + #опциональный параметр + #тип - список routes #routes = [{ + #ip целевой сети #опциональный параметр - #destination network #тип - строка - #destination = "DHCP" + #destination = "DHCP" + #сетевая маска в формате 255.255.255.255 #опциональный параметр - #destination network mask in 255.255.255.255 format #тип - строка #netmask = "192.168.5.5" + #шлюз по умолчанию #опциональный параметр - #next hop host, IP address from ViNS ID free IP pool #тип - строка #gateway = "192.168.5.5" #}] - # Default qos - + #default qos #опциональный параметр #блок для указания default_qos - #тип - блок + #тип - список qos #default_qos = { + #внутренний трафик, Кбит #опциональный параметр - #ingress rate - #тип - число + #тип - целое число #in_rate = 1 + #burst внутреннего трафика, Кбит #опциональный параметр - #ingress burst - #тип - число + #тип - целое число #in_burst = 1 + #rate внешнего трафика, Кбит #опциональный параметр - #egress rate - #тип - число + #тип - целое число #e_rate = 1 - #} - - # Enable, delete parameters + #} - #опциональный параметр #ручное подключение и отключение ресурса - #тип - булев тип - #enable = true - #опциональный параметр - #удаление навсегда - #тип - булев тип - #permanently = true + #тип - булев + #enable = true + #удаление навсегда #опциональный параметр - #удаляет за собой все зависимые ресурсы - #тип - булев тип - #force = true - - # IP release, IP reserve parameters + #тип - булев + #permanently = true + #удаляет за собой все зависимые ресурсы #опциональный параметр + #тип - булев + #force = true + #блок для резервирования ip - #тип - блок + #опциональный параметр + #тип - список параметров ip #ip { - #обязательный параметр #тип подключения + #обязательный параметр #тип - строка - # type = "DHCP" + #type = "DHCP" - #опциональный параметр #ip который необходимо зарезервировать + #опциональный параметр #тип - строка #ip_addr = "192.168.5.5" - #опциональный параметр #mac который необходимо зарезервировать + #опциональный параметр #тип - строка #mac = "ff:ff:ff:ff:ff:ff" - #опциональный параметр #compute_id, ассоциируемый с типом DHCP - #тип - число + #опциональный параметр + #тип - целое число #compute_id = 1234 - #опциональный параметр #причина запроса + #опциональный параметр #тип - строка #reason = "one more reason" - #} + #} - # Добавление и удаление NAT Rules - - #опциональный параметр #блок для добавления natRule - #тип - блок + #опциональный параметр + #тип - список параметров natRule #nat_rule { - #обязательный параметр #ip внутренний + #обязательный параметр #тип - строка - # int_ip = "192.168.0.28" + #int_ip = "192.168.0.28" - #обязательный параметр #внутренний порт - #тип - число - # int_port = 80 + #опциональный параметр + #тип - целое число + #int_port = 80 - #обязательный параметр #начало диапазона внешних портов - #тип - число - # ext_port_start = 8001 + #обязательный параметр + #тип - целое число + #ext_port_start = 8001 - #опциональный параметр #конец диапазона внешних портов - #тип - число - #ext_port_end = 8001 - #опциональный параметр + #тип - целое число + #ext_port_end = 8001 + #протокол natRule: разрешенные значения "tcp", "udp" + #опциональный параметр #тип - строка - #proto = "tcp" - #} - - # vnf dev start, stop, restart, reset, redeploy parameters + #proto = "tcp" + #} + #vnf dev start, stop #опциональный параметр #true: старт vnfDev; false: стоп vnfDev - #тип - булев тип + #тип - булев #vnfdev_start = true - #опциональный параметр #перезапуск vnfDev - #тип - булев тип + #опциональный параметр + #тип - булев #vnfdev_restart = true - #опциональный параметр #ресет vnfDev - #тип - булев тип + #опциональный параметр + #тип - булев #vnfdev_reset = true - #опциональный параметр #редеплой vnfDev - #тип - булев тип + #опциональный параметр + #тип - булев #vnfdev_redeploy = true + + #список dns + #опциональный параметр + #применяется при создании и редактировании ресурса + #если при создании указать пустой список, то ресурс создается с полем vnfs.dhcp.config.dns, имеющим значение по умолчанию + #если при обновлении указать пустой список, то ресурс обновит в модели поле vnfs.dhcp.config.dns с текущего значения на пустой список + #тип - список строк + #dns = ["1.1.1.1", "2.2.2.2"] + } output "test" { diff --git a/samples/cloudbroker/resource_vins_static_route/main.tf b/samples/cloudbroker/vins/resource_vins_static_route/main.tf similarity index 88% rename from samples/cloudbroker/resource_vins_static_route/main.tf rename to samples/cloudbroker/vins/resource_vins_static_route/main.tf index ba32d35..8d23d67 100644 --- a/samples/cloudbroker/resource_vins_static_route/main.tf +++ b/samples/cloudbroker/vins/resource_vins_static_route/main.tf @@ -15,8 +15,8 @@ terraform { required_providers { decort = { - version = "" source = "basis/decort/decort" + version = "" } } } @@ -32,30 +32,31 @@ provider "decort" { } resource "decort_cb_vins_static_route" "sr" { - #id Vins + #id vins #обязательный параметр - #тип - число + #тип - целое число vins_id = 385 - #destination network + #ip целевой сети #обязательный параметр #тип - строка destination = "192.168.201.0" - #destination network mask + #сетевая маска #обязательный параметр #тип - строка netmask = "255.255.255.255" - #IP-адрес из пула свободных IP-адресов ViNS ID + #ip-адрес из пула свободных IP-адресов ViNS ID #обязательный параметр #тип - строка gateway = "192.168.201.40" #список виртуальных машин, которым будет предоставлен доступ к роуту #опциональный параметр - #тип - массив чисел + #тип - массив целых чисел #compute_ids = [111,222] + } output "sr" { diff --git a/scripts/install.sh b/scripts/install.sh index 1c47a9f..bb32dd2 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -43,29 +43,29 @@ EOF } install () { - if [[ -d $plugins_dir$provider_path ]] - then - echo "Provider directory already exists, checking for decort provider executable.." - if [[ ! "$(ls -A $plugins_dir$provider_path)" ]]; then - cp bin/terraform-provider-decort_$version\_$os\_$arch $plugins_dir$provider_path/terraform-provider-decort_$version/$os\_$arch - print_info - else - echo "DECORT provider version $version is already installed. Exiting.." - print_info - fi - else - echo "Creating provider directory.." - mkdir -p $plugins_dir/$provider_path - cp bin/terraform-provider-decort_$version\_$os\_$arch $plugins_dir$provider_path/terraform-provider-decort_$version/$os\_$arch - echo "DECORT provider version $version has been successfully installed" - print_info - fi + if [[ -d $plugins_dir$provider_path ]] + then + echo "Provider directory already exists, checking for decort provider executable.." + if [[ ! "$(ls -A $plugins_dir$provider_path)" ]]; then + cp bin/terraform-provider-decort_$version\_$os\_$arch $plugins_dir$provider_path + print_info + else + echo "DECORT provider version $version is already installed. Exiting.." + print_info + fi + else + echo "Creating provider directory.." + mkdir -p $plugins_dir/$provider_path + cp bin/terraform-provider-decort_$version\_$os\_$arch $plugins_dir$provider_path + echo "DECORT provider version $version has been successfully installed" + print_info + fi } case "$OSTYPE" in - linux*) install ;; - darwin*) install ;; - bsd*) install ;; - msys*) echo "Use bat script to install DECORT provider on Windows machine." ;; - cygwin*) echo "Use bat script to install DECORT provider on Windows machine." ;; + linux*) install ;; + darwin*) install ;; + bsd*) install ;; + msys*) echo "Use bat script to install DECORT provider on Windows machine." ;; + cygwin*) echo "Use bat script to install DECORT provider on Windows machine." ;; esac diff --git a/wiki/4.5.2/06.01.08-Data_decort_locations_list.md b/wiki/4.5.2/06.01.08-Data_decort_locations_list.md index a0b367d..8b4927d 100644 --- a/wiki/4.5.2/06.01.08-Data_decort_locations_list.md +++ b/wiki/4.5.2/06.01.08-Data_decort_locations_list.md @@ -12,6 +12,7 @@ _Data source_ функция **decort_locations_list** принимает сле | name | string | :x: | Поиск по имени | | by_id | int | :x: | Поиск по ID | | location_code | string | :x: | Поиск по коду локации | +| sort_by | string | :x: | Фильтр по одному из поддерживаемых полей, формат: +или- название поля | | page | int | :x: | Номер страниц | | size | int | :x: | Размер страницы | @@ -35,10 +36,41 @@ _Data source_ функция **decort_locations_list** принимает сле ```terraform data "decort_locations_list" "ll" { - #name = "mr4" - #by_id = 1 - #page = 2 - #size = 3 + #фильтр по флагу + #опицональный параметр + #тип - строка + #flag = "some" + + #фильтр по id локации + #опциональный параметр + #тип - число + #by_id = 100 + + #фильтр по имени локации + #опциональный параметр + #тип - строка + #name = "test" + + #фильтр по коду локации + #опциональный параметр + #тип - строка + #location_code = "europe" + + #сортировка по одному из поддерживаемых полей + #опциональный параметр + #тип - строка + #формат - "+поле" по возрастанию / "-поле" по убыванию + #sort_by = "+name" + + #кол-во страниц для вывода + #опицональный параметр + #тип - число + #page = 1 + + #размер страницы + #опицональный параметр + #тип - число + #size = 1 } # once the above directive completes, locations (grid) list will be accessible # as data.decort_locations_list.ll.items diff --git a/wiki/4.5.2/07.02.17-Resource_decort_cb_lb b/wiki/4.5.2/07.02.17-Resource_decort_cb_lb.md similarity index 100% rename from wiki/4.5.2/07.02.17-Resource_decort_cb_lb rename to wiki/4.5.2/07.02.17-Resource_decort_cb_lb.md diff --git a/wiki/4.5.3/07.02.17-Resource_decort_cb_lb b/wiki/4.5.3/07.02.17-Resource_decort_cb_lb.md similarity index 100% rename from wiki/4.5.3/07.02.17-Resource_decort_cb_lb rename to wiki/4.5.3/07.02.17-Resource_decort_cb_lb.md diff --git a/wiki/4.6.0/01.-Введение.md b/wiki/4.6.0/01.-Введение.md new file mode 100644 index 0000000..1b51eb3 --- /dev/null +++ b/wiki/4.6.0/01.-Введение.md @@ -0,0 +1,7 @@ +DECORT Terraform Provider позволяет управлять облачными ресурсами на платформе Digital Energy Cloud Orchestration Technology (DECORT) версии 3.7.x и выше посредством Terraform. + +С помощью данного провайдера можно организовать программное управление вычислительными ресурсами (_compute_), ресурсными группами, сетевыми и дисковыми ресурсами, образами дисков, кластером, а также другими параметрами облачной платформы DECORT. + +Если вы хорошо знакомы с инструментом Terraform и хотите максимально быстро начать использовать платформу DECORT в своих Terraform-проектах, то можете сразу перейти к разделу [Пример работы](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/02.-Пример-работы.md), где приведён подробно откомментированный пример работы с основными видами ресурсов платформы. Если у вас всё же возникнут вопросы по облачной платформе DECORT и порядку авторизации в ней, то обратитесь к главе [«Обзор облачной платформы DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/03.-Обзор-облачной-платформы-DECORT.md). Также может оказаться полезной глава [«Инициализация Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/04.02-Инициализация-Terraform-провайдера-DECORT.md). + +Если вы только начинаете использовать инструмент Terraform и облачную платформу DECORT, то рекомендуем вам начать с главы [«Обзор облачной платформы DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/03.-Обзор-облачной-платформы-DECORT.md), после чего изучить главы [«_Data source_ функции Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/06.-Data-source-функции-Terraform-провайдера-DECORT.md) и [«_Resource_ функции Terraform провайдера DECORT»](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/07.-Resource-функции-Terraform-провайдера-DECORT.md). Примеры, приведенные в этих разделах, помогут вам быстро освоить базовые приёмы работы с инструментом Terraform и провайдером DECORT. diff --git a/wiki/4.6.0/02.-Пример-работы.md b/wiki/4.6.0/02.-Пример-работы.md new file mode 100644 index 0000000..46fd4e4 --- /dev/null +++ b/wiki/4.6.0/02.-Пример-работы.md @@ -0,0 +1,92 @@ +Данный раздел предназначен для тех, кто хорошо знаком с инструментом Terraform, а также имеет представление об основных понятиях и способах авторизации в облачной платформе DECORT. + +Ниже приведён подробно откомментированный пример, показывающий, как создать виртуальный сервер (aka _compute_ на базе системы виртуализации KVM x86) в облачной платформе DECORT с помощью соответствующего Terraform провайдера. Сервер будет создан в новой ресурсной группе, к нему будет подключён один предварительно созданный диск, у сервера будет прямое сетевое подключение во внешнюю сеть. + +Идентификатор образа операционной системы, на базе которого должен быть создан виртуальный сервер, считывается из облачной платформы с помощью _data source_ функции `decort_image`. + +Далее мы с помощью _resource_ функции `decort_resgroup` создаём новую ресурсную группу, в которую будет помещён этот виртуальный сервер. В качестве альтернативы, для получения информации об уже имеющейся ресурсной группе можно использовать _data source_ функцию с таким же названием. + +Затем с помощью _resource_ функции `decort_disk` создаётся диск, который будет подключён к виртуальному серверу в качестве дополнительного. Помимо этого дополнительного диска у сервера будет также и загрузочный диск, на который в процессе создания сервера клонируется выбранный образ операционной системы. + +Виртуальный сервер - в данном примере на базе системы виртуализации KVM x86 - создаётся посредством _resource_ функции `decort_kvmvm`. + +Только авторизованные в контроллере облачной платформы пользователи могут управлять облачными ресурсами. Подробнее о способах авторизации см. [Обзор облачной платформы DECORT](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/03.-Обзор-облачной-платформы-DECORT.md). + +```terraform +# 1. Initialize DECORT plugin and connection to DECORT cloud controller +# NOTE: in this example credentials are expected to come from +# DECORT_APP_ID and DECORT_APP_SECRET environmental variables - set them +# in the shell before calling terraform. +# Alternatively you may define plugin parameters app_id and app_secret in +# the TF file, however, this may not be secure if you plan to share this TF +# file with others. + +provider "decort" { + authenticator = "decs3o" + controller_url = "<>" # specify correct DECORT controller URL, e.g. "https://ds1.digitalenergy.online" + oauth2_url = "<>" # specify corresponding DECORT SSO URL, e.g. "https://sso.digitalenergy.online" + app_id = "<>" # application secret to access DECORT cloud API in 'decs3o' and 'bvs' authentication mode, e.g. "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu" + app_secret = "<>" # application ID to access DECORT cloud API in 'decs3o' and 'bvs' authentication mode, e.g. "ewqfrvea7s890avw804389qwguf234h0otfi3w4eiu" + # allow_unverified_ssl = true +} + +# 2. Load account to use - new VM will belong to this account +data "decort_account" "my_account" { + account_id = # Specify account ID +} + +# 3. Load OS image to use for VM deployment +data "decort_image" "os_image" { + image_id = # Specify OS image id, e.g. 1234. You can get accessible image id from data source "decort_image_list" +} + +# 4. Create new Resource Group in the selected account, new VM will be created in this RG +resource "decort_resgroup" "my_rg" { + name = "NewRgByTF" + account_id = data.decort_account.my_account.account_id + gid = # Grid (platform) ID + # if you want to set resource quota on this Resource Group, uncomment + # the following code fragment + # quota { + # cpu = 8 # CPU limit + # ram = 8912 # RAM limit in MB + # disk = 96 # disk volume limit in GB + #} +} + +# 5. Create extra disk, which will be attached to the new VM. +# This step is optional - if you do not want extra disks on your VM, skip it +# and comment out extra_disks parameter when creating VM below. +resource "decort_disk" "extra_disk" { + disk_name = "extra-disk-for-vm" + account_id = data.decort_account.my_account.account_id + gid = # Grid (platform) ID + size_max = 5 # disk size in GB + type = "D" # disk type, always use "D" for extra disks + sep_id = data.decort_image.os_image.sep_id # use the same SEP ID as the OS image + pool = "<>" # consult your DECORT platform admin for configured storage pool names +} + +# 6. Create virtual machine (a compute of type KVM VM x86 in this example) +# Now that we have all necessary components at hand, we may create a virtual machine. +# This VM will be based on the previsouly obtained OS image, located in the specified +# Resource Group, directly connected to an external network, have a boot disk of +# specified size and one extra disk attached. +resource "decort_kvmvm" "my_new_vm" { + name = "tf-managed-vm" + driver = "KVM_X86" # Compute virtualization driver + rg_id = decort_resgroup.my_rg.id + cpu = 1 # CPU count + ram = 1024 # RAM size in MB, must be even number, ideally a power of 2 + boot_disk_size = 10 # Boot disk size in GB + image_id = data.decort_image.os_image.image_id + description = "Test KVM VM Compute managed by Terraform" + extra_disks = [ decort_disk.extra_disk.id ] + + network { + net_type = "EXTNET" + net_id = <> # specify external network ID to use, consult your DECORT platform admin for correct IDs + # ip_address = "<>" # you may optionally request a specific IP address + } +} +``` diff --git a/wiki/4.6.0/03.-Обзор-облачной-платформы-DECORT.md b/wiki/4.6.0/03.-Обзор-облачной-платформы-DECORT.md new file mode 100644 index 0000000..938223a --- /dev/null +++ b/wiki/4.6.0/03.-Обзор-облачной-платформы-DECORT.md @@ -0,0 +1,31 @@ +## Основные понятия +Ниже перечислены основные понятия с указанием соответствующих им аргументов в Terraform провайдере DECORT. +1. **Контроллер облачной платформы DECORT** – управляющее приложение, которое обеспечивает авторизацию пользователей и оркестрацию облачных ресурсов. + - Адрес контроллера задается в обязательном аргументе `controller_url` на стадии инициализации Terraform провайдера DECORT. Например, `controller_url= "https://ds1.digitalenergy.online"` +2. **Авторизационный провайдер** – приложение, работающее по протоколу Oauth2, предназначенное для выпуска и валидации токенов доступа к контроллеру облачной платформы в соответствующих режимах авторизации. Все действия в платформе должны выполняться авторизованными пользователями, и авторизационное приложение позволяет получить токен доступа, действующий некоторое ограниченное время, наличие которого подтверждает успешную авторизацию. + - Адрес авторизационного провайдера задается в аргументе`oauth2_url` на стадии инициализации Terraform провайдера DECORT. Например `oauth2_url= "https://sso.digitalenergy.online"` +3. **Подписчик** (_account_) – сущность, которая используется для группирования облачных ресурсов по принадлежности к определенному клиенту для целей учета потребления и биллинга. + - Имя подписчика задается аргументом `account_name` при вызове _resource_ или _data_ функций провайдера. Альтернативной является задание численного идентификатора подписчика в аргументе `account_id`. +4. **Пользователь** (_user_) – пользователь облачной инфраструктуры, представленный учетной записью. Чтобы получить возможность управлять облачными ресурсами (например, создавать виртуальные серверы или дискт) пользователь должен быть ассоциирован с одним или несколькими подписчиками и иметь соответствующие права, определяемые ролевой моделью, принятой в облачной платформе DECORT. Для доступа к платформе пользователь должен авторизоваться одним из способов, описанных ниже в разделе «Способы авторизации». +5. **Ресурсная группа** (_resource group_) – способ группирования вычислительных ресурсов (например, виртуальных серверов по функциональному признаку или принадлежности к одному и тому же проекту). Ресурсную группу можно рассматривать как небольшой персональный дата-центр, в котором размещаются один или несколько серверов и виртуальных сетевых сегментов. Ресурсная группа идентифицируется по комбинации параметров `account` и `name`. Обратите внимание, что имя имя ресурсной группы уникально только в рамках одного и того же `account`. +6. **Вычислительный ресурс** (_compute_) - универсальная абстракция пользовательского сервера в платформе DECORT. Благодаря использованию такой абстракции можно, например, создать одну виртуальную машину на базе KVM Intel x86, а другую - на базе KVM IBM Power, а потом управлять ими - изменять количество CPU/RAM, подключать/отключать диски и т.п. - одинаковым образом, не задумываясь об их архитектурных различиях. В то же время, так как типизация ресурсов в Terraform не поддерживает наследование, различные типы вычислительных ресурсов, доступных на платформе DECORT и абстрагируемых через понятие унифицированный _compute_, в Terraform представлены разными типами (напр., свой тип для виртуальных серверов на базе KVM и свой тип для перспективных x86-совместимых bare metal серверов). +7. **Ресурс хранения** (_disk_) - универсальная абстракция дискового ресурса в платформе DECORT. Платформа поддерживает различные типы систем хранения данных, но при этом управление созданными на разных системах хранения дисками осуществляется посредством унифицированного набора действий, например, "подключить диск к _compute_", "увеличить размер диска", "сделать мгновенный снимок диска", "настроить параметры быстродействия диска". +8. **Виртуальный сервер** – экземпляр _compute_, в основе технической реализации которого лежит виртуальная машина, работающая в облаке DECORT и доступна по сети. Виртуальный сервер характеризуется количеством выделенных ему CPU (аргумент`cpu`), объемом ОЗУ (`ram`), размером загрузочного диска (`boot_disk size`). При создании виртуального сервера на загрузочный диск устанавливается образ операционной системы, заданный в аргументе `image_id`. Помимо загрузочного диска к виртуальному серверу можно подключить несколько дисков для хранения прикладных данных, список которых задается аргументами `extra_disks`. Виртуальный сервер идентифицируется по комбинации аргументов `name` (имя сервера) и `rgid` (идентификатор ресурсной группы). Обратите внимание, что имя виртуального сервера `name` уникально только в рамках одной и той же ресурсной группы. +9. **Виртуальный сетевой сегмент** (_Virtual Network Segment_ или _ViNS_) - сетевой сегмент и обеспечивающая его функционирование виртуальная инфраструктура, которые пользователь может создавать для своих нужд на уровне ресурсной группы или подписчика (_account_). ViNS можно создать полностью изолированным от внешних сетей (см. ниже _External Network_) или с подключением во внешнюю сеть. Внутри ViNS работает DHCP-сервис, обеспечивающий управление IP адресами экземпляров _compute_, подключённых в этот ViNS. +10. **Внешняя сеть** (_External Network_) - сетевой сегмент, через который платформа DECORT взаимодействует с внешними по отношению к ней сетевыми ресурсами. Например, в случае с публичным облаком на базе DECORT в качестве внешней сети выступает сеть Интернет. В отличие от ViNS платформа не управляет внешней сетью, а лишь пользуется её ресурсами. В платформе может быть настроено несколько внешних сетей с различными диапазонами IP адресов, и существует механизм управления доступом пользователей к внешним сетям. +11. Сетевой доступ к экземпляру _compute_ (виртуальному серверу) реализуется через его подключение к ViNS и/или прямое подключение во внешнюю сеть (External Network). Один и тот же экземпляр _compute_ может одновременно иметь несколько подключений в разные ViNS и/или различные внешние сети. + +## Способы авторизации +Облачная платформа DECORT поддерживает три базовых типа авторизации: +1. С использованием авторизационного провайдера, работающего по протоколу _Oauth2_. Данный способ является предпочтительным, так как обеспечивает бОльшую гибкость и безопасность. Для авторизации в этом режиме при инициализации Terrafrom провайдера DECORT необходимо указать параметры `oauth2_url` и `controller_url`, а также предоставить одно из нижеперечисленного: + - Комбинация Application ID & Application secret, соответствующих пользователю, от имени которого будет осуществляться управление облачными ресурсами в текущей сессии. В процессе проверки предоставленных Application ID & Application secret модуль получает от авторизационного провайдера токен (JSON Web Token, JWT), который затем используется для доступа к указанному контроллеру DECORT. Для авторизации по данному варианту, при инициализации Terraform провайдера DECORT следует установить аргумент `authenticator=decs3o` и задать аргументы `app_id` и `app_secret` (или определить соответствующие переменные окружения `DECORT_APP_ID` и `DECORT_APP_SECRET`). + - JSON Web Token – заранее полученный от авторизационного провайдера токен доступа, ассоциированный с определенным пользователем, от имени которого будет осуществляться управление облачными ресурсами в текущей сессии. Для авторизации по данному варианту, при инициализации Terraform провайдера DECORT следует установить аргумент `authenticator=jwt` и задать аргумент `jwt` (или определить переменную окружения `DECORT_JWT`). +2. С использованием комбинации _имя пользователя : пароль_. Данный режим не использует внешних авторизационных провайдеров и подразумевает, что пользователь с такой комбинацией зарегистрирован непосредственно на указанном в параметре `controller_url` контроллере облачной платформы DECORT. + - Чтобы провайдер авторизовался по данному варианту, при его инициализации следует установить аргумент `authenticator=legacy` и задать аргументы `user` и `password` (или определить соответствующие переменные окружения `DECORT_USER` и `DECORT_PASSWORD`). +3. С использованием авторизационного провайдера, работающего по протоколу _Oauth2_oidc_. Для авторизации в этом режиме при инициализации Terrafrom провайдера DECORT необходимо указать параметры `oauth2_url` и `controller_url`, а также Application ID & Application secret, _имя пользователя и пароль_, соответствующих пользователю, от имени которого будет осуществляться управление облачными ресурсами в текущей сессии, и _имя домена_. В процессе проверки предоставленных Application ID & Application secret и пары _имя пользователя-пароль_ модуль получает от авторизационного провайдера токен (JSON Web Token, JWT), который затем используется для доступа к указанному контроллеру DECORT. Для авторизации по данному варианту, при инициализации Terraform провайдера DECORT следует установить аргумент `authenticator=bvs`, задать аргументы `app_id` и `app_secret` (или определить соответствующие переменные окружения `DECORT_APP_ID` и `DECORT_APP_SECRET`), `bvs_user` и `bvs_password` (или определить соответствующие переменные окружения `DECORT_BVS_USER` и `DECORT_BVS_PASSWORD`), а также указать `domain` (или определить соответствующие переменные окружения `DECORT_DOMAIN`). + +После успешной авторизации пользователь (или приложение-клиент) получает доступ к ресурсам, находящимся под управлением соответствующего DECORT контроллера. Доступ предоставляется в рамках подписчиков (_account_), с которыми ассоциирован данный пользователь (_user_), и в соответствии с присвоенными ему ролями. + +## Пользовательская и административная группы API +Пользовательская группа API - группа API платформы DECORT, которая позволяет выполнять операции с платформой с правами обычного пользователя. Покрывает большую часть задач. +Административная группа API - группа API платформы DECORT, которая позволяет выполнять операции с платформой с расширенными правами. Данные права подразумевают расширенный перечень операций над ресурсами, расширенный перечень ресурсов, расширенную информацию. Требуются права администратора для взаимодействия с этой группой API. diff --git a/wiki/4.6.0/04.-Начало-работы-с-terraform-провайдером-DECORT.md b/wiki/4.6.0/04.-Начало-работы-с-terraform-провайдером-DECORT.md new file mode 100644 index 0000000..edaa664 --- /dev/null +++ b/wiki/4.6.0/04.-Начало-работы-с-terraform-провайдером-DECORT.md @@ -0,0 +1,6 @@ +Данный раздел описывает: +- Системные требования +- Установку провайдера +- Инициализацию провайдера +- Переключение режима работы между разными группами API +- Получение gid/grid_id площадки diff --git a/wiki/4.6.0/04.01-Установка-Terraform-провайдера-DECORT.md b/wiki/4.6.0/04.01-Установка-Terraform-провайдера-DECORT.md new file mode 100644 index 0000000..f642d2d --- /dev/null +++ b/wiki/4.6.0/04.01-Установка-Terraform-провайдера-DECORT.md @@ -0,0 +1,150 @@ +## Системные требования + +Для запуска провайдера вам потребуется машина, на которой установлен Terraform. + +Кроме того, в связи с тем, что начиная с версии 0.12 Terraform изменил алгоритм поиска и инициализации локальных провайдеров, настройка данного провайдера для работы с Terraform 0.12 или более новыми версиями потребует выполнения ряда дополнительных действий. Подробнее см. [8.3 Настройка локального провайдера для работы с новыми версиями Terraform](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/08.-Полезные-советы#user-content-8-3-настройка-локального-провайдера-для-работы-с-новыми-версиями-terraform.md). + +## Установка +Начиная с версии провайдера `4.3.0` в релизном архиве находятся скрипты-инсталляторы. +Чтобы выполнить установку, необходимо: +1. Перейти по адресу: https://repository.basistech.ru/BASIS/terraform-provider-decort/releases +2. Выбрать необходимую версию провайдера подходящую под операционную систему. +3. Скачать архив. +4. Распаковать архив. +5. Выполнить скрипт установщика, `install.sh` или `install.bat` для Windows.
+*Для запуска `install.sh` не забудьте изменить права доступа к файлу* +```bash +chmod u+x install.sh +``` +6. Дождаться сообщения об успешной установке. Установщик выведет актуальный блок конфигурации провайдера, скопируйте его +```bash +DECORT provider version 4.3.0 has been successfully installed + +Copy this provider configuration to main.tf file: +terraform { + required_providers { + decort = { + version = "4.3.0" + source = "basis/decort/decort" + } + } +} +``` +7. После этого, создайте файл `main.tf` в рабочей директории, которая может находится в любом удобном для пользователя месте. +В данном примере, рабочая директория с файлом main.tf находится по пути: +```bash +~/work/tfdir/main.tf +``` +8. Вставьте в `main.tf` блок конфигурации провайдера, который был выведен на экран установщиком: +```terraform +terraform { + required_providers { + decort = { + version = "4.3.0" + source = "basis/decort/decort" + } + } +} +``` +9. Добавьте в файл блок с инициализацией провайдера. +```terraform +provider "decort" { + authenticator = "decs3o" + controller_url = "https://mr4.digitalenergy.online" + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} +``` + +10. В консоли выполните команду +```bash +terraform init +``` + +11. В случае успешной установки, Terraform инициализирует провайдер и будет готов к дальнейшей работе. + +## Установка из релизов +Terraform провайдер DECORT имеет скомпилированные релизные версии, которые расположены по адресу: [Релизы](https://repository.basistech.ru/BASIS/terraform-provider-decort/releases). +Чтобы выполнить установку из релиза, необходимо: +1. Перейти по адресу: https://repository.basistech.ru/BASIS/terraform-provider-decort/releases +2. Выбрать необходимую версию провайдера подходящую под операционную систему. +3. Скачать архив. +4. Распаковать архив. +5. Полученный файл (в директории `bin/`) необходимо поместить: +Linux: +```bash +~/.terraform.d/plugins/${host_name}/${namespace}/${type}/${version}/${target} +``` +Windows: +```powershell +%APPDATA%\terraform.d\plugins\${host_name}\${namespace}\${type}\${version}\${target} +``` +Где: +- host_name - имя хоста, держателя провайдера, например, basis +- namespace - пространство имен хоста, например decort +- type - тип провайдера, может совпадать с пространством имен, например, decort +- version - версия провайдера, например 4.3.0 +- target - архитектура операционной системы, например windows_amd64 + +В примере ниже используется путь до провайдера на машине с ОС Linux: + +```bash +~/.terraform.d/plugins/basis/decort/decort/4.3.0/linux_amd64/tf-provider + ^ ^ ^ ^ ^ ^ + host_name | | | | | | + | | | | | + namespace | | | | | + | | | | + type | | | | + | | | + version | | | + | | + target | | + | + исполняемый файл | +``` + +6. После этого, создайте файл `main.tf` в рабочей директории, которая может находится в любом удобном для пользователя месте. +В данном примере, рабочая директория с файлом main.tf находится по пути: +```bash +~/work/tfdir/main.tf +``` +7. Добавьте в `main.tf` следующий блок +```terraform +terraform { + required_providers { + decort = { + version = "4.3.0" + source = "basis/decort/decort" + } + } +} +``` +В поле `version` указывается версия провайдера. +
+**ВНИМАНИЕ: Версии в блоке и в пути к исполняемому файлу провайдера должны совпадать!** + +В поле `source` помещается путь до репозитория с версией вида: + +```bash +${host_name}/${namespace}/${type} +``` + +**ВНИМАНИЕ: Версии в блоке и в пути к исполняемому файлу провайдера должны совпадать!** + +8. Добавьте в файл блок с инициализацией провайдера. +```terraform +provider "decort" { + authenticator = "decs3o" + controller_url = "https://mr4.digitalenergy.online" + oauth2_url = "https://sso.digitalenergy.online" + allow_unverified_ssl = true +} +``` + +9. В консоли выполните команду +```bash +terraform init +``` + +10. В случае успешной установки, Terraform инициализирует провайдер и будет готов к дальнейшей работе. diff --git a/wiki/4.6.0/04.02-Инициализация-Terraform-провайдера-DECORT.md b/wiki/4.6.0/04.02-Инициализация-Terraform-провайдера-DECORT.md new file mode 100644 index 0000000..c48b179 --- /dev/null +++ b/wiki/4.6.0/04.02-Инициализация-Terraform-провайдера-DECORT.md @@ -0,0 +1,64 @@ +## Список аргументов для инициализации +Перед началом использования любой Terraform провайдер должен быть инициализирован. + +В процессе инициализации Terraform провайдера DECORT проверяется корректность переданных аргументов и выполняется авторизация в указанном контроллере облачной инфраструктуры. Подробнее о способах авторизации в платформе DECORT смотри соответствующий [раздел](https://repository.basistech.ru/BASIS/terraform-provider-decort/src/branch/main/wiki/4.6.0/03.-Обзор-облачной-платформы-DECORT#user-content-способы-авторизации.md). + +При инициализации Terraform провайдера DECORT используются следующие аргументы: + +| Аргумент | Переменная окружения | Описание | +| --- | --- | --- | +| allow_unverified_ssl | - | Если данный аргумент явно установлен в `true`, то провайдер **не будет** проверять SSL сертификаты при взаимодействии с авторизационным сервисом OAuth2 и контроллером облачной платформы.
Отключение проверок может быть полезным при работе в доверенной среде, использующей самоподписанные SSL сертификаты. Однако, так как отключение проверок несёт потенциальные риски безопасности, данную настройку следует использовать с осторожностью.
Разрешённые значения: `false` (значение по умолчанию) и `true`. | +| app_id | DECORT_APP_ID | Идентификатор приложения (клиента) для авторизации в контроллере облачной платформы в режиме `decs3o` или `bvs`.
Аргументы `app_id` и `app_secret` являются обязательными для режимов авторизации `authenticator=decs3o` и `authenticator=bvs`.
Если `app_id` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_APP_ID`. | +| app_secret | DECORT_APP_SECRET | Секретный код приложения (клиента) для авторизации в контроллере облачной платформы в режиме `decs3o` или `bvs`.
Аргументы `app_id` и `app_secret` являются обязательными для режимов авторизации `authenticator=decs3o` и `authenticator=bvs`.
Если `app_secret` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_APP_SECRET`. | +| authenticator | - | Режим авторизации при подключении к контроллеру облачной платформы.
Доступные режимы: `decs3o`, `legacy`, `jwt` или `bvs`.
Данный аргумент является обязательным. | +| bvs_user | DECORT_BVS_USER | Имя пользователя для авторизации в контроллере облачной платформы в режиме `bvs`.
Аргументы `bvs_password` и `bvs_user` являются обязательными для режима авторизации `authenticator=bvs`.
Если `bvs_user` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_BVS_USER`. | +| bvs_password | DECORT_BVS_PASSWORD | Пароль пользователя для авторизации в контроллере облачной платформы в режиме `bvs`.
Аргументы `bvs_user` и `bvs_password` являются обязательными для режима авторизации `authenticator=bvs`.
Если `bvs_password` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_BVS_PASSWORD`. | +| domain | DECORT_DOMAIN | Имя домена в контроллере облачной платформы в режиме `bvs`.
Данный аргумент является обязательным.
Если `domain` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_DOMAIN`. | +| controller_url | - | URL контроллера облачной платформы, через который будет осуществляться управление облачными ресурсами.
Данный аргумент является обязательным. | +| jwt | DECORT_JWT | JSON Web Token (JWT), который используется для авторизации в контроллере облачной платформы в режиме `jwt`.
Данный аргумент является обязательным для режима авторизации `authenticator=jwt`.
Если `jwt` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_JWT` | +| oauth2_url | DECORT_OAUTH2_URL | URL авторизационного сервиса OAuth2, который используется для управления доступом пользователей (или программных клиентов) к контроллеру облачной платформы.
Данный аргумент является обязательным для режимов авторизации `authenticator=decs3o`, `authenticator=bvs` и `authenticator=jwt`.
Если `oauth2_url` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_OAUTH2_URL` | +| password | DECORT_PASSWORD | Пароль для авторизации в контроллере облачной платформы в режиме `legacy`.
Аргументы `password` и `user` являются обязательными для режима авторизации `authenticator=legacy`.
Если `password` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_PASSWORD`. | +| user | DECORT_USER | Имя пользователя для авторизации в контроллере облачной платформы в режиме `legacy`.
Аргументы `user` и `password` являются обязательными для режима авторизации `authenticator=legacy`.
Если `user` не задан в tf-файле, то провайдер будет использовать значение из переменной окружения `DECORT_USER`. | + +## Пример инициализации в режиме авторизации `decs3o` +Пример инициализации Terraform провайдера DECORT: +```terraform +provider "decort" { + authenticator = "decs3o" + controller_url = "https://ctrl.decort.online" + oauth2_url = "https://oauth2.decort.online:7777" +} +``` + +В данном примере используется режим авторизации `decs3o`. + +Как отмечено выше, в данном режиме требуется указать аргументы `app_id` и `app_secret`, идентифицирующие пользователя (или приложение-клиент), от лица которого будут выполняться дальнейшие действия. Однако, так как данная информация является конфиденциальной (по сути, она эквивалентна паре _имя пользователя : пароль_), то в общем случае заносить такого рода данные в tf-файл не следует. Рекомендуется определять в среде запуска Terraform переменные окружения `DECORT_APP_ID` и `DECORT_APP_SECRET`, из которых провайдер извлечёт нужные данные. Приведенный пример подразумевает, что нужная информация будет получена из этих переменных окружения. + +Пользователь, от лица которого Terrafrom будет выполнять действия в облачной платформе, должен заранее создать пару _Application ID_ и _Application Secret_ в авторизационном приложении OAuth2. Именно эти значения, а также URL авторизационного приложения Oauth2, должны присваиваться аргументам `app_id`, `app_secret` и `oauth2_url` соответственно для успешной инициализации провайдера. + +Также обратите внимание на формат задания аргументов `controller_url` и `oauth2_url`. В общем случае они должны содержать идентификатор протокола (_https://_) и сетевой порт, если он отличается от порта по умолчанию (в примере для авторизационного сервиса OAuth2 указан порт _7777_). Эту информацию вы можете узнать у администратора вашей облачной инфраструктуры DECORT. + +## Пример инициализации в режиме авторизации `bvs` +Пример инициализации Terraform провайдера DECORT: +```terraform +provider "decort" { + authenticator = "bvs" + controller_url = "https://delta.qa.loc" + oauth2_url = "https://bvs-delta.qa.loc:8443" + app_id = "delta" + app_secret = "" + bvs_password = "" + bvs_user = "" + domain = "dynamix" +} +``` + +В данном примере используется режим авторизации `bvs`. + +Как отмечено выше, в данном режиме требуется указать аргументы `app_id` - идентификатор площадки - delta, alpha, poc, etc. Можно найти на странице администратора по следующему пути: вкладка безопасность - клиентские сервисы - наименование площадки. `app_secret` - пароль площадки. Можно найти на странице администратора по следующему пути: вкладка безопасность - клиентские сервисы - наименование площадки (символ i) - поле "Пароль". Однако, так как данная информация является конфиденциальной, то в общем случае заносить такого рода данные в tf-файл не следует. Рекомендуется определять в среде запуска Terraform переменные окружения `DECORT_APP_ID` и `DECORT_APP_SECRET`, из которых провайдер извлечёт нужные данные. Приведенный пример подразумевает, что нужная информация будет получена из этих переменных окружения. +Также обязательными аргументами являются: `bvs_user` - имя пользователя, `bvs_password` - пароль пользователя. Рекомендуется не заносить их в tf-файл, а определять в среде запуска Terraform переменные окружения `DECORT_BVS_USER` и `DECORT_BVS_PASSWORD`, из которых провайдер извлечёт нужные данные. Приведенный пример подразумевает, что нужная информация будет получена из этих переменных окружения. +Домен для подключения `domain` - указывается наименование площадки. Данный аргумент является обязательным. Рекомендуется не заносить его в tf-файл, а определять в среде запуска Terraform переменную окружения `DECORT_DOMAIN`, из которой провайдер извлечёт нужные данные. Приведенный пример подразумевает, что нужная информация будет получена из этих переменных окружения. + +Пользователь, от лица которого Terrafrom будет выполнять действия в облачной платформе, должен заранее получить от администратора _Application ID_ и _Application Secret_, _bvs user_ и _bvs password_, а также _domain_. А также осуществить первичный вход на платформу посредством браузера. + +Также обратите внимание на формат задания аргументов `controller_url` и `oauth2_url`. В общем случае они должны содержать идентификатор протокола (_https://_) и сетевой порт, если он отличается от порта по умолчанию (в примере для авторизационного сервиса OAuth2 указан порт _8443_). Эту информацию вы можете узнать у администратора вашей облачной инфраструктуры DECORT. diff --git a/wiki/4.6.0/04.03-Переключение-между-группами-API.md b/wiki/4.6.0/04.03-Переключение-между-группами-API.md new file mode 100644 index 0000000..fb722ac --- /dev/null +++ b/wiki/4.6.0/04.03-Переключение-между-группами-API.md @@ -0,0 +1,38 @@ +Так как платформа DECORT предоставляет для работы две группы API, то terraform провайдер позволяет свободно переключать режимы работы между этими группами. +По умолчанию стоит пользовательская группа API. Ее можно сменить на административную группу. +Если прав у пользователя будет достаточно, то запрос будет выполнен, если нет, то будет ошибка: +```bash +Permission denied +``` +Которая говорит о том, что прав недостаточно. Тогда для выполнения операции обратитесь к администратору платформы. +Установка режима взаимодействия с группами API осуществляется через установку переменной окружения _DECORT_ADMIN_MODE_. +Для более подробного описания возможностей каждой группы API см. соответствующий раздел. + +## Переключение режима работы в Windows +Используйте сл. команду: +```Powershell +$Env:DECORT_ADMIN_MODE=1 +``` +Для отключения: +```Powershell +$Env:DECORT_ADMIN_MODE=0 +``` +## Переключение режима работы в Linux +Используйте сл. команду: +```bash +DECORT_ADMIN_MODE=1 +``` +или +```bash +export DECORT_ADMIN_MODE=1 +``` +Для отключения: +```bash +DECORT_ADMIN_MODE=0 +``` +или +```bash +export DECORT_ADMIN_MODE=0 +``` +**ОБРАТИТЕ ВНИМАНИЕ** +Переменные окружения создаются для терминальной сессии. В сл. раз их придется задавать еще раз, если требуется режим, отличный от пользовательского. diff --git a/wiki/4.6.0/04.04-Получение-gid-или-grid_id.md b/wiki/4.6.0/04.04-Получение-gid-или-grid_id.md new file mode 100644 index 0000000..4b316ac --- /dev/null +++ b/wiki/4.6.0/04.04-Получение-gid-или-grid_id.md @@ -0,0 +1,31 @@ +Платформа может располагаться на нескольких площадках(grid). +Такие площадки имеют свой id. +Для создания некоторых ресурсов требуется ввести grid_id или gid площадки. +Получение gid различается для пользовательского и административного API. + +## Получение gid для пользовательского API +Для получения gid с помощью пользовательского API, необходимо получить информацию из _data_source_ функции _decort_locations_list_, как указано ниже: +```terraform +data "decort_locations_list" "ll" { + +} + +output "test" { + value = data.decort_locations_list.ll +} +``` +В файл состояния будет сохранен результат, где можно посмотреть доступные для работы площадки. + +## Получение gid для административного API +Для получения gid с помощью административного API, необходимо получить информацию из _data_source_ функции _decort_grid_list_, как указано ниже: +```terraform +data "decort_grid_list" "gl" { + +} + +output "test" { + value = data.decort_grid_list.gl +} + +``` +В файл состояния будет сохранен результат, где можно посмотреть доступные для работы площадки. diff --git a/wiki/4.6.0/04.05-Сборка-terraform-провайдера-в-образ.md b/wiki/4.6.0/04.05-Сборка-terraform-провайдера-в-образ.md new file mode 100644 index 0000000..02bc8b7 --- /dev/null +++ b/wiki/4.6.0/04.05-Сборка-terraform-провайдера-в-образ.md @@ -0,0 +1,43 @@ +Образ приложения - современный способ запуска приложений. Образ приложения представляет собой контейнер, в который входит ОС и необходимые для работы приложения пакеты. +Способов создать образ приложения довольно много, для этого существуют программы контейнеризации: +- Docker +- Podman +- и другие +Образ представляет собой "зафиксированную" версию приложения, что означает, что никакие изменения в приложения внесены быть не могут. Так же означает то, что приложение не может создавать побочные файлы при работе. +Контейнер - это запущенный экземпляр образа. То есть, один образ может порождать множество контейнеров, каждый из которых будет включать в себя отдельный экземпляр приложения. +Одно из преимуществ работы приложения в контейнере - кроссплатформенность. Это преимущество обуславливается тем, что образ приложения уже включает в себя все необходимое для успешной работы приложения, в том числе операционную систему. Поэтому, пользователю достаточно установить на вычислительной машине программу, которая обеспечивает работу с образами приложений. + +## Docker +Docker является одной из самых популярных программ для работы с образами. +Docker позволяет: +- Создавать образы +- Запускать контейнеры +- Управлять контейнерами +- Управлять образами +Скачать и установить Docker можно по ссылке https://docs.docker.com/get-docker/ + +## Сборка terraform провайдера +### Требования: +- Docker +- git +- Компилятор языка GO += make +### Установка необходимых программ +1. Компилятор языка GO можно скачать и установить по ссылке: https://go.dev/dl/ +2. Docker можно скачать и установить по ссылке выше. +3. Git можно скачать и установить по ссылке: https://git-scm.com/ +4. Программа make входит в пакет установленных программ для ОС Linux. Для Windows можно воспользоваться инструкцией со stack overflow: https://stackoverflow.com/questions/32127524/how-to-install-and-use-make-in-windows +### Порядок действий +1. Склонировать репозиторий с провайдером: +```bash +git clone https://github.com/rudecs/terraform-provider-decort.git +``` +2. Перейти в директорию со скачанным кодом: +```bash +cd terraform-provider-decort +``` +3. Выполнить команду: +```bash +make image +``` +В результате выполнения данной последовательности, будет создан docker образ, который содержит в себе приложение terraform, terraform провайдер. diff --git a/wiki/4.6.0/05.-Работа-с-terraform.md b/wiki/4.6.0/05.-Работа-с-terraform.md new file mode 100644 index 0000000..675f2ea --- /dev/null +++ b/wiki/4.6.0/05.-Работа-с-terraform.md @@ -0,0 +1,4 @@ +Раздел описывает некоторые практики работы с terraform, которые могут быть полезны пользователю. +Раздел включает в себя следующие статьи: +- Импортирование ресурсов +- Работа с таймаутами diff --git a/wiki/4.6.0/05.01-Импортирование-ресурсов.md b/wiki/4.6.0/05.01-Импортирование-ресурсов.md new file mode 100644 index 0000000..8a419d3 --- /dev/null +++ b/wiki/4.6.0/05.01-Импортирование-ресурсов.md @@ -0,0 +1,75 @@ +Импортирование ресурсов в terraform позволяет привести в соответствие состояние terraform (.tfstate) к состоянию ресурса в платформе. +Необходимость такого приведения возникает в нескольких случаях: +- Ресурс был создан через портал платформы, работа продолжается через terraform провайдер, +- Ресурс был создан через terraform провайдер, однако был изменен через портал платформы, +- Ресурс был создан через terraform провайдер, однако был изменен другим пользователем через terraform провайдер, +- И так далее + +Такие расхождения в состоянии ресурсов нередки, путей их решения несколько: +- Использовать импортирование ресурсов, +- Использовать общие файлы состояний ресурсов, к которым будут иметь доступ все участники, занятые в работе с платформой. +В текущем разделе рассматривается первый вариант. + +## Импортирование ресурсов +Импортирование ресурсов позволяет совершить запрос к платформе, чтобы сформировать файл состояния. +Чтобы совершить импортирование ресурсов необходимо ввести сл. команду: +```bash +terraform import . +``` +## Пример +Предположим, что у нас ресурс, описывающий диск: +```terraform +resource "decort_disk" "disk" { + account_id = 121212 + gid = 3333 + disk_name = "mySuperDisk" + size_max = 100500 +} +``` +Если запустить команду: +```bash +terraform apply +``` +То у нас будет создан новый диск. +Но, такой диск уже есть на площадке и мы хотели бы сформировать .tfstate для этого ресурса. +Поэтому, для начала, необходимо получить список дисков: +```terraform +data "decort_disk_list" "dl"{ + +} +output "test" { + value = data.decort_disk_list.dl +} +``` +В полученных данных необходимо найти требуемый диск, получить его id - параметр disk_id. Пусть это будет - 777777 +Теперь можно выполнить импортирование: +```bash +terraform import decort_disk.disk 777777 +``` +Команда должна успешно завершиться, появиться файл состояний, который позволит манипулировать ресурсом. + +## Ошибки при импортировании +При импортировании ресурса может возникнуть сл. ошибка: +```bash +Error: : required field is not set +``` +Где - наименование поля. +Ошибка возникает в том случае, если в описании ресурса отсутствует обязательное поле. +Например: +```terraform +resource "decort_disk" "disk" { + account_id = 121212 + gid = 3333 + size_max = 100500 +} +``` +В приведенном выше описании отсутствует поле disk_name, поэтому, при попытке импортирования возникнет ошибка. +Для ее устранения, необходимо выполнить запрос на получение списка дисков, найти недостающее поле, после чего добавить его в описание ресурса. +После этого повторить попытку импортирования. + +## Общий алгоритм устранения ошибок +1. Выполнить запрос импортирования +2. В случае ошибки - внести недостающие поля. +3. Повторить п.1. + + diff --git a/wiki/4.6.0/05.02-Работа-с-таймаутами.md b/wiki/4.6.0/05.02-Работа-с-таймаутами.md new file mode 100644 index 0000000..9a739b4 --- /dev/null +++ b/wiki/4.6.0/05.02-Работа-с-таймаутами.md @@ -0,0 +1,100 @@ +Terraform провайдер DECORT поддерживает тонкую настройку таймаутов выполнения запросов к платформе. Таймауты необходимы для определения максимального времени выполнения запроса. При превышении этого времени соединение рвется и запрос считается невыполненным. +Таймауты применяются при работе с _resource_ функциями провайдера. _Data source_ функции по-умолчанию имеют таймаут в 20 минут и изменяться не может. + +## Стандартные таймауты terraform +| Операция | Время | Описание | +| --- | --- | --- | +| create | 20 минут | Создание ресурса | +| read | 20 минут | Чтение ресурса | +| update | 20 минут | Обновление ресурса | +| delete | 20 минут | Удаление ресурса | +| default | 20 минут | Значение по умолчанию. Устанавливает значение для всех операций | + +## Стандартные таймауты провайдера DECORT +В провайдере DECORT таймауты переопределены для того, чтобы уменьшить нагрузку на платформу. +| Операция | Время | Описание | +| --- | --- | --- | +| create | 10 минут | Создание ресурса | +| read | 5 минут | Чтение ресурса | +| update | 5 минут | Обновление ресурса | +| delete | 5 минут | Удаление ресурса | +| default | 5 минут | Значение по умолчанию. Устанавливает значение для всех операций | + +## Установка таймаутов +Все таймауты можно установить самостоятельно для каждого ресурса. +Для этого используется блок _timeouts_, который имеется в каждом ресурсе провайдера. +Пример: +```terraform +resource "decort_res" "res_name" { + timeouts { + create = "10m" + update = "1m" + delete = "2m" + read = "7m" + #default = "15m" + } +} +``` +Где: +- create - операция создания ресурса +- read - операция чтения ресурса +- update - операция обновления ресурса +- delete - операция удаления ресурса +- default - установит заданное время для всех операций +## Формат установления времени +Как видно из примера выше, провайдер принимает на вход строку вида: +``` +"" +``` +Где: +- time-num - число +- time-val - сокращенная запись значения временного отрезка. + +Таблица с временными отрезками: + +| Отрезок | Значение | +| --- | --- | +| n | наносекунда | +| ms | миллисекунда | +| s | секунда | +| m | минута | +| h | час | + +Примеры: +``` +"10m" +"1s" +"1h10m" +``` +И так далее + +## Работа с таймером через .tf-файл +В .tf-файле, в блоке ресурса можно задавать таймауты для операций над ресурсом, однако, при работе с таймаутом, следует помнить о правиле: +__В случае изменения таймаутов в .tf-файле, операции с новыми таймаутами будут производиться только после apply/plan/destroy__ +То есть, если изменить таймауты и выполнить операцию, то она выполнится со старыми таймаутами, а сл. операция уже будет выполнена с новыми таймаутами. +Это объясняется тем, что значения таймаутов считываются из файла состояний .tfstate при выполнении операции, и новые значения таймаутов попадут туда только при успешно выполненной операции. + +## Ошибки при работе с таймаутом +### context deadline exceeded +Если время таймаута слишком короткое, то можно получить сл. ошибку: +``` +context deadline exceeded +``` +Которая говорит, что было выполнено прерывание работы программы из-за истечения времени на операцию. +Для исправления можно увеличить размер окна таймаута и выполнить успешный запрос (например, с помощью терминала), чтобы новое значения таймаутов было добавлено в .tfstate. В противном случае, файл состояния придется править в ручную, либо удалить его и импортировать ресурс для формирования .tfstate. + +### 504 ошибка +Данная ошибка говорит о том, что сервер принудительно разорвал соединения из-за истечения времени на ответ. +В случае получения данной ошибки, обратитесь в службу технической поддержки. + +## Работа с таймаутами через терминал +Сл. команда выполнит операцию terraform с заданным таймаутом: +```bash +timeout