This commit is contained in:
asteam
2024-07-25 14:33:38 +03:00
commit 6f40af6a5f
946 changed files with 98335 additions and 0 deletions

View File

@@ -0,0 +1,88 @@
package image
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceImage{}
)
func NewDataSourceImage() datasource.DataSource {
return &dataSourceImage{}
}
// dataSourceImage is the data source implementation.
type dataSourceImage struct {
client *decort.DecortClient
}
func (d *dataSourceImage) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
// Read Terraform configuration data into the model
var state models.RecordImageModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source image state")
return
}
tflog.Info(ctx, "Start read data source image", map[string]any{"image_id": state.ImageId.ValueInt64()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceImage(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source image", map[string]any{"image_id": state.ImageId.ValueInt64()})
}
func (d *dataSourceImage) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceImage(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceImage) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_image"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceImage) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,87 @@
package image
import (
"context"
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/schemas"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &dataSourceImageList{}
)
func NewDataSourceImageList() datasource.DataSource {
return &dataSourceImageList{}
}
// dataSourceImageList is the data source implementation.
type dataSourceImageList struct {
client *decort.DecortClient
}
func (d *dataSourceImageList) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
tflog.Info(ctx, "Start read data source image list")
// Read Terraform configuration data into the model
var state models.ListImagesModel
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read data source image list state")
return
}
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout30s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
// Map response body to schema
resp.Diagnostics.Append(flattens.DataSourceImageList(ctx, &state, d.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image list")
return
}
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "End read data source image list")
}
func (d *dataSourceImageList) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaDataSourceImageList(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx),
},
}
}
func (d *dataSourceImageList) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_image_list"
}
// Configure adds the provider configured client to the data source.
func (d *dataSourceImageList) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
tflog.Info(ctx, "Get configure data source")
d.client = client.DataSource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure data source successfully")
}

View File

@@ -0,0 +1,108 @@
package flattens
import (
"context"
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/utilities"
)
func DataSourceImage(ctx context.Context, state *models.RecordImageModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceImage", map[string]any{"image_id": state.ImageId.ValueInt64()})
diags := diag.Diagnostics{}
image, err := utilities.ImageDataSourceCheckPresence(ctx, state, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about image with ID %d", state.ImageId.ValueInt64()), err.Error())
return diags
}
id := uuid.New()
cdPresentedTo, _ := json.Marshal(image.CdPresentedTo)
*state = models.RecordImageModel{
ImageId: types.Int64Value(int64(image.ID)),
ShowAll: state.ShowAll,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
UNCPath: types.StringValue(image.UNCPath),
CKey: types.StringValue(image.CKey),
AccountID: types.Int64Value(int64(image.AccountID)),
Architecture: types.StringValue(image.Architecture),
BootType: types.StringValue(image.BootType),
Bootable: types.BoolValue(image.Bootable),
ComputeCIID: types.Int64Value(int64(image.ComputeCIID)),
CdPresentedTo: types.StringValue(string(cdPresentedTo)),
GID: types.Int64Value(int64(image.GID)),
DeletedTime: types.Int64Value(int64(image.DeletedTime)),
Description: types.StringValue(image.Description),
Enabled: types.BoolValue(image.Enabled),
GUID: types.Int64Value(int64(image.GUID)),
History: flattenHistory(ctx, &image.History),
HotResize: types.BoolValue(image.HotResize),
LastModified: types.Int64Value(int64(image.LastModified)),
LinkTo: types.Int64Value(int64(image.LinkTo)),
Milestones: types.Int64Value(int64(image.Milestones)),
ImageName: types.StringValue(image.Name),
ImageType: types.StringValue(image.Type),
NetworkInterfaceNaming: types.StringValue(image.NetworkInterfaceNaming),
Password: types.StringValue(image.Password),
PoolName: types.StringValue(image.Pool),
ProviderName: types.StringValue(image.ProviderName),
PurgeAttempts: types.Int64Value(int64(image.PurgeAttempts)),
ResID: types.StringValue(image.ResID),
RescueCD: types.BoolValue(image.RescueCD),
SepID: types.Int64Value(int64(image.SepID)),
Size: types.Int64Value(int64(image.Size)),
Status: types.StringValue(image.Status),
TechStatus: types.StringValue(image.TechStatus),
Username: types.StringValue(image.Username),
Version: types.StringValue(image.Version),
}
state.ACL, diags = types.ListValueFrom(ctx, types.StringType, image.ACL)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACL", diags))
}
state.Drivers, diags = types.ListValueFrom(ctx, types.StringType, image.Drivers)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDrivers", diags))
}
state.PresentTo, diags = types.ListValueFrom(ctx, types.Int64Type, image.PresentTo)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenPresentTo", diags))
}
state.SharedWith, diags = types.ListValueFrom(ctx, types.Int64Type, image.SharedWith)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenSharedWith", diags))
}
tflog.Info(ctx, "End FlattenDataSourceImage", map[string]any{"image_id": state.ImageId.ValueInt64()})
return nil
}
func flattenHistory(ctx context.Context, history *image.ListHistories) []models.HistoryModel {
tflog.Info(ctx, "Start flattenHistory")
res := make([]models.HistoryModel, 0, len(*history))
for _, item := range *history {
temp := models.HistoryModel{
GUID: types.StringValue(item.GUID),
ID: types.Int64Value(int64(item.ID)),
Timestamp: types.Int64Value(int64(item.Timestamp)),
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenHistory")
return res
}

View File

@@ -0,0 +1,91 @@
package flattens
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/utilities"
)
func DataSourceImageList(ctx context.Context, state *models.ListImagesModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenDataSourceImageList")
diags := diag.Diagnostics{}
imageList, err := utilities.ImageListCheckPresence(ctx, state, c)
if err != nil {
diags.AddError("Error get image list info", err.Error())
return diags
}
id := uuid.New()
*state = models.ListImagesModel{
SEPID: state.SEPID,
ByID: state.ByID,
Name: state.Name,
Status: state.Status,
Architecture: state.Architecture,
TypeImage: state.TypeImage,
ImageSize: state.ImageSize,
SEPName: state.SEPName,
PoolName: state.PoolName,
Public: state.Public,
HotResize: state.HotResize,
Bootable: state.Bootable,
SortBy: state.SortBy,
Page: state.Page,
Size: state.Size,
Timeouts: state.Timeouts,
Id: types.StringValue(id.String()),
Items: flattenItems(ctx, imageList),
EntryCount: types.Int64Value(int64(imageList.EntryCount)),
}
tflog.Info(ctx, "End FlattenDataSourceImageList")
return nil
}
func flattenItems(ctx context.Context, data *image.ListImages) []models.ItemImageModel {
tflog.Info(ctx, "Start flattenItems")
var diags diag.Diagnostics
res := make([]models.ItemImageModel, 0, len(data.Data))
for _, item := range data.Data {
temp := models.ItemImageModel{
AccountID: types.Int64Value(int64(item.AccountID)),
Architecture: types.StringValue(item.Architecture),
BootType: types.StringValue(item.BootType),
Bootable: types.BoolValue(item.Bootable),
CDROM: types.BoolValue(item.CDROM),
Description: types.StringValue(item.Description),
HotResize: types.BoolValue(item.HotResize),
ImageID: types.Int64Value(int64(item.ID)),
ImageType: types.StringValue(item.Type),
LinkTo: types.Int64Value(int64(item.LinkTo)),
ImageName: types.StringValue(item.Name),
PoolName: types.StringValue(item.Pool),
SepID: types.Int64Value(int64(item.SepID)),
Size: types.Int64Value(int64(item.Size)),
Status: types.StringValue(item.Status),
NetworkInterfaceNaming: types.StringValue(item.NetworkInterfaceNaming),
Username: types.StringValue(item.Username),
Virtual: types.BoolValue(item.Virtual),
}
temp.Drivers, diags = types.ListValueFrom(ctx, types.StringType, item.Drivers)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDrivers", diags))
}
res = append(res, temp)
}
tflog.Info(ctx, "End flattenItems")
return res
}

View File

@@ -0,0 +1,127 @@
package flattens
import (
"context"
"encoding/json"
"fmt"
"strconv"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/utilities"
)
func ResourceImage(ctx context.Context, plan *models.ImageResourceModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenResourceImage", map[string]any{"image_id": plan.Id.ValueString()})
diags := diag.Diagnostics{}
imageId, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot parsed ID image from state %d", imageId), err.Error())
return diags
}
image, err := utilities.ImageResourceCheckPresence(ctx, imageId, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about image with ID %d", image.ID), err.Error())
return diags
}
cdPresentedTo, _ := json.Marshal(image.CdPresentedTo)
*plan = models.ImageResourceModel{
ImageName: types.StringValue(image.Name),
URL: plan.URL,
BootType: types.StringValue(image.BootType),
ImageType: types.StringValue(image.Type),
HotResize: types.BoolValue(image.HotResize),
NetworkInterfaceNaming: types.StringValue(image.NetworkInterfaceNaming),
Username: types.StringValue(image.Username),
Password: types.StringValue(image.Password),
AccountID: types.Int64Value(int64(image.AccountID)),
UsernameDL: plan.UsernameDL,
PasswordDL: plan.PasswordDL,
SepID: types.Int64Value(int64(image.SepID)),
PoolName: types.StringValue(image.Pool),
Architecture: types.StringValue(image.Architecture),
Permanently: plan.Permanently,
ImageId: types.Int64Value(int64(image.ID)),
Timeouts: plan.Timeouts,
Id: types.StringValue(strconv.Itoa(int(image.ID))),
LastUpdated: plan.LastUpdated,
UNCPath: types.StringValue(image.UNCPath),
CKey: types.StringValue(image.CKey),
Bootable: types.BoolValue(image.Bootable),
ComputeCIID: types.Int64Value(int64(image.ComputeCIID)),
CdPresentedTo: types.StringValue(string(cdPresentedTo)),
GID: types.Int64Value(int64(image.GID)),
DeletedTime: types.Int64Value(int64(image.DeletedTime)),
Description: types.StringValue(image.Description),
Enabled: types.BoolValue(image.Enabled),
GUID: types.Int64Value(int64(image.GUID)),
History: flattenHistoryInResource(ctx, &image.History),
LastModified: types.Int64Value(int64(image.LastModified)),
LinkTo: types.Int64Value(int64(image.LinkTo)),
Milestones: types.Int64Value(int64(image.Milestones)),
ProviderName: types.StringValue(image.ProviderName),
PurgeAttempts: types.Int64Value(int64(image.PurgeAttempts)),
ResID: types.StringValue(image.ResID),
RescueCD: types.BoolValue(image.RescueCD),
Size: types.Int64Value(int64(image.Size)),
Status: types.StringValue(image.Status),
TechStatus: types.StringValue(image.TechStatus),
Version: types.StringValue(image.Version),
}
plan.ACL, diags = types.ListValueFrom(ctx, types.StringType, image.ACL)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACL", diags))
}
plan.Drivers, diags = types.ListValueFrom(ctx, types.StringType, image.Drivers)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDrivers", diags))
}
plan.PresentTo, diags = types.ListValueFrom(ctx, types.Int64Type, image.PresentTo)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenPresentTo", diags))
}
plan.SharedWith, diags = types.ListValueFrom(ctx, types.Int64Type, image.SharedWith)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenSharedWith", diags))
}
tflog.Info(ctx, "End FlattenResourceImage", map[string]any{"image_id": plan.ImageId.ValueInt64()})
return nil
}
func flattenHistoryInResource(ctx context.Context, history *image.ListHistories) types.List {
tflog.Info(ctx, "Start flattenHistoryInResource")
tempSlice := make([]types.Object, 0, len(*history))
for _, item := range *history {
temp := models.HistoryInImageResourceModel{
GUID: types.StringValue(item.GUID),
ID: types.Int64Value(int64(item.ID)),
Timestamp: types.Int64Value(int64(item.Timestamp)),
}
obj, err := types.ObjectValueFrom(ctx, models.HistoryInResource, temp)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenHistoryInResource struct to obj", err))
}
tempSlice = append(tempSlice, obj)
}
res, err := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.HistoryInResource}, tempSlice)
if err != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenHistoryInResource", err))
}
tflog.Info(ctx, "End flattenHistoryInResource")
return res
}

View File

@@ -0,0 +1,91 @@
package flattens
import (
"context"
"fmt"
"strconv"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/utilities"
)
func ResourceImageVirtual(ctx context.Context, plan *models.ImageVirtualResourceModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start FlattenResourceImageVirtual", map[string]any{"image_id": plan.ImageId.ValueInt64()})
diags := diag.Diagnostics{}
imageId, err := strconv.ParseUint(plan.Id.ValueString(), 10, 64)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot parsed ID image from state %d", imageId), err.Error())
return diags
}
image, err := utilities.ImageResourceCheckPresence(ctx, imageId, c)
if err != nil {
diags.AddError(fmt.Sprintf("Cannot get info about image with ID %d", plan.ImageId.ValueInt64()), err.Error())
return diags
}
*plan = models.ImageVirtualResourceModel{
ImageName: types.StringValue(image.Name),
LinkTo: types.Int64Value(int64(image.LinkTo)),
Permanently: plan.Permanently,
Timeouts: plan.Timeouts,
Id: types.StringValue(strconv.Itoa(int(image.ID))),
LastUpdated: plan.LastUpdated,
UNCPath: types.StringValue(image.UNCPath),
CKey: types.StringValue(image.CKey),
AccountID: types.Int64Value(int64(image.AccountID)),
Architecture: types.StringValue(image.Architecture),
BootType: types.StringValue(image.BootType),
Bootable: types.BoolValue(image.Bootable),
ComputeCIID: types.Int64Value(int64(image.ComputeCIID)),
DeletedTime: types.Int64Value(int64(image.DeletedTime)),
Description: types.StringValue(image.Description),
Enabled: types.BoolValue(image.Enabled),
GID: types.Int64Value(int64(image.GID)),
GUID: types.Int64Value(int64(image.GUID)),
History: flattenHistoryInResource(ctx, &image.History),
HotResize: types.BoolValue(image.HotResize),
LastModified: types.Int64Value(int64(image.LastModified)),
Milestones: types.Int64Value(int64(image.Milestones)),
ImageId: types.Int64Value(int64(image.ID)),
ImageType: types.StringValue(image.Type),
Password: types.StringValue(image.Password),
PoolName: types.StringValue(image.Pool),
ProviderName: types.StringValue(image.ProviderName),
PurgeAttempts: types.Int64Value(int64(image.PurgeAttempts)),
ResID: types.StringValue(image.ResID),
RescueCD: types.BoolValue(image.RescueCD),
SepID: types.Int64Value(int64(image.SepID)),
Size: types.Int64Value(int64(image.Size)),
Status: types.StringValue(image.Status),
TechStatus: types.StringValue(image.TechStatus),
Username: types.StringValue(image.Username),
Version: types.StringValue(image.Version),
}
plan.ACL, diags = types.ListValueFrom(ctx, types.StringType, image.ACL)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenACL", diags))
}
plan.Drivers, diags = types.ListValueFrom(ctx, types.StringType, image.Drivers)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenDrivers", diags))
}
plan.PresentTo, diags = types.ListValueFrom(ctx, types.Int64Type, image.PresentTo)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenPresentTo", diags))
}
plan.SharedWith, diags = types.ListValueFrom(ctx, types.Int64Type, image.SharedWith)
if diags != nil {
tflog.Error(ctx, fmt.Sprint("Error flattenSharedWith", diags))
}
tflog.Info(ctx, "End FlattenResourceImageVirtual", map[string]any{"image_id": plan.ImageId.ValueInt64()})
return nil
}

View File

@@ -0,0 +1,58 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type RecordImageModel struct {
// request fields
ImageId types.Int64 `tfsdk:"image_id"`
ShowAll types.Bool `tfsdk:"show_all"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// responce fields
Id types.String `tfsdk:"id"`
UNCPath types.String `tfsdk:"unc_path"`
CKey types.String `tfsdk:"ckey"`
AccountID types.Int64 `tfsdk:"account_id"`
ACL types.List `tfsdk:"acl"`
Architecture types.String `tfsdk:"architecture"`
BootType types.String `tfsdk:"boot_type"`
Bootable types.Bool `tfsdk:"bootable"`
ComputeCIID types.Int64 `tfsdk:"compute_ci_id"`
CdPresentedTo types.String `tfsdk:"cd_presented_to"`
GID types.Int64 `tfsdk:"gid"`
DeletedTime types.Int64 `tfsdk:"deleted_time"`
Description types.String `tfsdk:"desc"`
Drivers types.List `tfsdk:"drivers"`
Enabled types.Bool `tfsdk:"enabled"`
GUID types.Int64 `tfsdk:"guid"`
History []HistoryModel `tfsdk:"history"`
HotResize types.Bool `tfsdk:"hot_resize"`
LastModified types.Int64 `tfsdk:"last_modified"`
LinkTo types.Int64 `tfsdk:"link_to"`
Milestones types.Int64 `tfsdk:"milestones"`
ImageName types.String `tfsdk:"image_name"`
ImageType types.String `tfsdk:"image_type"`
Password types.String `tfsdk:"password"`
NetworkInterfaceNaming types.String `tfsdk:"network_interface_naming"`
PoolName types.String `tfsdk:"pool_name"`
PresentTo types.List `tfsdk:"present_to"`
ProviderName types.String `tfsdk:"provider_name"`
PurgeAttempts types.Int64 `tfsdk:"purge_attempts"`
ResID types.String `tfsdk:"res_id"`
RescueCD types.Bool `tfsdk:"rescuecd"`
SepID types.Int64 `tfsdk:"sep_id"`
SharedWith types.List `tfsdk:"shared_with"`
Size types.Int64 `tfsdk:"size"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Username types.String `tfsdk:"username"`
Version types.String `tfsdk:"version"`
}
type HistoryModel struct {
GUID types.String `tfsdk:"guid"`
ID types.Int64 `tfsdk:"id"`
Timestamp types.Int64 `tfsdk:"timestamp"`
}

View File

@@ -0,0 +1,53 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/datasource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type ListImagesModel struct {
// request fields
SEPID types.Int64 `tfsdk:"sep_id"`
ByID types.Int64 `tfsdk:"by_id"`
Name types.String `tfsdk:"name"`
Status types.String `tfsdk:"status"`
Architecture types.String `tfsdk:"architecture"`
TypeImage types.String `tfsdk:"type_image"`
ImageSize types.Int64 `tfsdk:"image_size"`
SEPName types.String `tfsdk:"sep_name"`
PoolName types.String `tfsdk:"pool_name"`
Public types.Bool `tfsdk:"public"`
HotResize types.Bool `tfsdk:"hot_resize"`
Bootable types.Bool `tfsdk:"bootable"`
SortBy types.String `tfsdk:"sort_by"`
Page types.Int64 `tfsdk:"page"`
Size types.Int64 `tfsdk:"size"`
// responce fields
Id types.String `tfsdk:"id"`
Items []ItemImageModel `tfsdk:"items"`
EntryCount types.Int64 `tfsdk:"entry_count"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
}
type ItemImageModel struct {
AccountID types.Int64 `tfsdk:"account_id"`
Architecture types.String `tfsdk:"architecture"`
BootType types.String `tfsdk:"boot_type"`
Bootable types.Bool `tfsdk:"bootable"`
CDROM types.Bool `tfsdk:"cdrom"`
Description types.String `tfsdk:"desc"`
Drivers types.List `tfsdk:"drivers"`
HotResize types.Bool `tfsdk:"hot_resize"`
ImageID types.Int64 `tfsdk:"image_id"`
ImageType types.String `tfsdk:"image_type"`
LinkTo types.Int64 `tfsdk:"link_to"`
ImageName types.String `tfsdk:"image_name"`
PoolName types.String `tfsdk:"pool_name"`
SepID types.Int64 `tfsdk:"sep_id"`
Size types.Int64 `tfsdk:"size"`
Status types.String `tfsdk:"status"`
NetworkInterfaceNaming types.String `tfsdk:"network_interface_naming"`
Username types.String `tfsdk:"username"`
Virtual types.Bool `tfsdk:"virtual"`
}

View File

@@ -0,0 +1,69 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type ImageResourceModel struct {
// request fields
ImageName types.String `tfsdk:"image_name"`
URL types.String `tfsdk:"url"`
BootType types.String `tfsdk:"boot_type"`
ImageType types.String `tfsdk:"image_type"`
Drivers types.List `tfsdk:"drivers"`
HotResize types.Bool `tfsdk:"hot_resize"`
NetworkInterfaceNaming types.String `tfsdk:"network_interface_naming"`
Username types.String `tfsdk:"username"`
Password types.String `tfsdk:"password"`
AccountID types.Int64 `tfsdk:"account_id"`
UsernameDL types.String `tfsdk:"username_dl"`
PasswordDL types.String `tfsdk:"password_dl"`
SepID types.Int64 `tfsdk:"sep_id"`
PoolName types.String `tfsdk:"pool_name"`
Architecture types.String `tfsdk:"architecture"`
Permanently types.Bool `tfsdk:"permanently"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// responce fields
Id types.String `tfsdk:"id"`
LastUpdated types.String `tfsdk:"last_updated"`
UNCPath types.String `tfsdk:"unc_path"`
CKey types.String `tfsdk:"ckey"`
ACL types.List `tfsdk:"acl"`
Bootable types.Bool `tfsdk:"bootable"`
ComputeCIID types.Int64 `tfsdk:"compute_ci_id"`
CdPresentedTo types.String `tfsdk:"cd_presented_to"`
GID types.Int64 `tfsdk:"gid"`
DeletedTime types.Int64 `tfsdk:"deleted_time"`
Description types.String `tfsdk:"desc"`
Enabled types.Bool `tfsdk:"enabled"`
GUID types.Int64 `tfsdk:"guid"`
History types.List `tfsdk:"history"`
LastModified types.Int64 `tfsdk:"last_modified"`
LinkTo types.Int64 `tfsdk:"link_to"`
Milestones types.Int64 `tfsdk:"milestones"`
ImageId types.Int64 `tfsdk:"image_id"`
PresentTo types.List `tfsdk:"present_to"`
ProviderName types.String `tfsdk:"provider_name"`
PurgeAttempts types.Int64 `tfsdk:"purge_attempts"`
ResID types.String `tfsdk:"res_id"`
RescueCD types.Bool `tfsdk:"rescuecd"`
SharedWith types.List `tfsdk:"shared_with"`
Size types.Int64 `tfsdk:"size"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Version types.String `tfsdk:"version"`
}
type HistoryInImageResourceModel struct {
GUID types.String `tfsdk:"guid"`
ID types.Int64 `tfsdk:"id"`
Timestamp types.Int64 `tfsdk:"timestamp"`
}
var HistoryInResource = map[string]attr.Type{
"guid": types.StringType,
"id": types.Int64Type,
"timestamp": types.Int64Type,
}

View File

@@ -0,0 +1,57 @@
package models
import (
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type ImageVirtualResourceModel struct {
// request fields
ImageName types.String `tfsdk:"image_name"`
LinkTo types.Int64 `tfsdk:"link_to"`
Permanently types.Bool `tfsdk:"permanently"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
// responce fields
Id types.String `tfsdk:"id"`
LastUpdated types.String `tfsdk:"last_updated"`
UNCPath types.String `tfsdk:"unc_path"`
CKey types.String `tfsdk:"ckey"`
AccountID types.Int64 `tfsdk:"account_id"`
ACL types.List `tfsdk:"acl"`
Architecture types.String `tfsdk:"architecture"`
BootType types.String `tfsdk:"boot_type"`
Bootable types.Bool `tfsdk:"bootable"`
ComputeCIID types.Int64 `tfsdk:"compute_ci_id"`
DeletedTime types.Int64 `tfsdk:"deleted_time"`
Description types.String `tfsdk:"desc"`
Drivers types.List `tfsdk:"drivers"`
Enabled types.Bool `tfsdk:"enabled"`
GID types.Int64 `tfsdk:"gid"`
GUID types.Int64 `tfsdk:"guid"`
History types.List `tfsdk:"history"`
HotResize types.Bool `tfsdk:"hot_resize"`
LastModified types.Int64 `tfsdk:"last_modified"`
Milestones types.Int64 `tfsdk:"milestones"`
ImageId types.Int64 `tfsdk:"image_id"`
ImageType types.String `tfsdk:"image_type"`
Password types.String `tfsdk:"password"`
PoolName types.String `tfsdk:"pool_name"`
PresentTo types.List `tfsdk:"present_to"`
ProviderName types.String `tfsdk:"provider_name"`
PurgeAttempts types.Int64 `tfsdk:"purge_attempts"`
ResID types.String `tfsdk:"res_id"`
RescueCD types.Bool `tfsdk:"rescuecd"`
SepID types.Int64 `tfsdk:"sep_id"`
SharedWith types.List `tfsdk:"shared_with"`
Size types.Int64 `tfsdk:"size"`
Status types.String `tfsdk:"status"`
TechStatus types.String `tfsdk:"tech_status"`
Username types.String `tfsdk:"username"`
Version types.String `tfsdk:"version"`
}
type HistoryInImageVirtualResourceModel struct {
GUID types.String `tfsdk:"guid"`
ID types.Int64 `tfsdk:"id"`
Timestamp types.Int64 `tfsdk:"timestamp"`
}

View File

@@ -0,0 +1,280 @@
package image
import (
"context"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/schemas"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/utilities"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &resourceImage{}
_ resource.ResourceWithImportState = &resourceImage{}
)
// NewResourceImage is a helper function to simplify the provider implementation.
func NewResourceImage() resource.Resource {
return &resourceImage{}
}
// resourceImage is the resource implementation.
type resourceImage struct {
client *decort.DecortClient
}
// Create the resource and sets the initial Terraform state.
func (r *resourceImage) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan models.ImageResourceModel
// Get plan for create cluster
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
tflog.Info(ctx, "Start create image", map[string]any{"name": plan.ImageName.ValueString()})
// Set timeouts
createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout600s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
// Сhecking for values in the platform
resp.Diagnostics.Append(utilities.CheckParamsExistenceImage(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error check input values")
return
}
// Create k8s_wg and validated
resp.Diagnostics.Append(utilities.ResourceImageCreate(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error create image")
return
}
// Map response body to schema
resp.Diagnostics.Append(flattens.ResourceImage(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image")
return
}
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End create image", map[string]any{"image_id": plan.ImageId.ValueInt64()})
}
// Read refreshes the Terraform state with the latest data.
func (r *resourceImage) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state models.ImageResourceModel
// Get current state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start read image", map[string]any{"image_id": state.Id.ValueString()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout300s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
imageId, err := strconv.Atoi(state.Id.ValueString())
if err != nil {
tflog.Error(ctx, "Cannot convert Id to int value"+err.Error())
}
// Read status image
resp.Diagnostics.Append(utilities.ImageReadStatus(ctx, uint64(imageId), r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read status")
return
}
// Overwrite items with refreshed state
resp.Diagnostics.Append(flattens.ResourceImage(ctx, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image")
return
}
// Set refreshed state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End read image", map[string]any{"image_id": state.Id.ValueString()})
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceImage) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan models.ImageResourceModel
var state models.ImageResourceModel
// Retrieve values from plan
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
// Retrieve values from state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the state")
return
}
tflog.Info(ctx, "Start update image", map[string]any{"image_id": state.ImageId.ValueInt64()})
// Set timeouts
updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout300s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, updateTimeout)
defer cancel()
// Сhecking for values in the platform
resp.Diagnostics.Append(utilities.CheckParamsExistenceImage(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error check input values")
return
}
// Update name image
if !plan.ImageName.Equal(state.ImageName) {
resp.Diagnostics.Append(utilities.ImageUpdateName(ctx, uint64(state.ImageId.ValueInt64()), plan.ImageName.ValueString(), r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error update name image")
return
}
}
// Map response body to schema
resp.Diagnostics.Append(flattens.ResourceImage(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image")
return
}
// Set data last update
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End update image", map[string]any{"image_id": plan.ImageId.ValueInt64()})
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceImage) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Get current state
var state models.ImageResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start delete image", map[string]any{"image_id": state.ImageId.ValueInt64()})
// Set timeouts
deleteTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout300s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
defer cancel()
var permanently bool
if state.Permanently.IsNull() {
permanently = true
} else {
permanently = state.Permanently.ValueBool()
}
// Delete image
_, err := r.client.CloudAPI().Image().Delete(ctx, image.DeleteRequest{ImageID: uint64(state.ImageId.ValueInt64()), Permanently: permanently})
if err != nil {
resp.Diagnostics.AddError("Error deleting image with error: ", err.Error())
return
}
tflog.Info(ctx, "End delete image", map[string]any{"image_id": state.ImageId.ValueInt64()})
}
// Schema defines the schema for the resource.
func (r *resourceImage) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaResourceImage(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}),
},
Version: 1,
}
}
// Metadata returns the resource type name.
func (r *resourceImage) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_image"
}
// Configure adds the provider configured client to the resource.
func (r *resourceImage) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
tflog.Info(ctx, "Get configure resource")
r.client = client.Resource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure resource successfully")
}
func (r *resourceImage) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Retrieve import ID and save to id attribute
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}

View File

@@ -0,0 +1,275 @@
package image
import (
"context"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/flattens"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/schemas"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/utilities"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &resourceImageVirtual{}
_ resource.ResourceWithImportState = &resourceImageVirtual{}
)
// NewResourceImageVirtual is a helper function to simplify the provider implementation.
func NewResourceImageVirtual() resource.Resource {
return &resourceImageVirtual{}
}
// resourceImage is the resource implementation.
type resourceImageVirtual struct {
client *decort.DecortClient
}
// Create the resource and sets the initial Terraform state.
func (r *resourceImageVirtual) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan models.ImageVirtualResourceModel
// Get plan for create cluster
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
tflog.Info(ctx, "Start create image virtual", map[string]any{"name": plan.ImageName.ValueString()})
// Set timeouts
createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout600s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
// Create k8s_wg and validated
resp.Diagnostics.Append(utilities.ResourceImageVirtualCreate(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error create image virtual")
return
}
// Map response body to schema
resp.Diagnostics.Append(flattens.ResourceImageVirtual(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image virtual")
return
}
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End create image virtual", map[string]any{"image_id": plan.ImageId.ValueInt64()})
}
// Read refreshes the Terraform state with the latest data.
func (r *resourceImageVirtual) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state models.ImageVirtualResourceModel
// Get current state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start read image virtual", map[string]any{"image_id": state.Id.ValueString()})
// Set timeouts
readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout300s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
imageId, err := strconv.Atoi(state.Id.ValueString())
if err != nil {
tflog.Error(ctx, "Cannot convert Id to int value"+err.Error())
}
// Read status image virtual
resp.Diagnostics.Append(utilities.ImageReadStatus(ctx, uint64(imageId), r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error read status")
return
}
// Overwrite items with refreshed state
resp.Diagnostics.Append(flattens.ResourceImageVirtual(ctx, &state, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image virtual")
return
}
// Set refreshed state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End read image virtual", map[string]any{"image_id": state.Id.ValueString()})
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceImageVirtual) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan models.ImageVirtualResourceModel
var state models.ImageVirtualResourceModel
// Retrieve values from plan
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the plan")
return
}
// Retrieve values from state
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error receiving the state")
return
}
tflog.Info(ctx, "Start update image virtual", map[string]any{"image_id": state.ImageId.ValueInt64()})
// Set timeouts
updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout300s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, updateTimeout)
defer cancel()
// Update name image virtual
if !plan.ImageName.Equal(state.ImageName) {
resp.Diagnostics.Append(utilities.ImageUpdateName(ctx, uint64(state.ImageId.ValueInt64()), plan.ImageName.ValueString(), r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error update name image virtual")
return
}
}
// Update link_to image virtual
if !plan.LinkTo.Equal(state.LinkTo) {
resp.Diagnostics.Append(utilities.ImageUpdateLink(ctx, uint64(state.ImageId.ValueInt64()), uint64(plan.LinkTo.ValueInt64()), r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error update link_to image virtual")
return
}
}
// Map response body to schema
resp.Diagnostics.Append(flattens.ResourceImageVirtual(ctx, &plan, r.client)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error flatten image virtual")
return
}
// Set data last update
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
// Set state to fully populated data
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set state")
return
}
tflog.Info(ctx, "End update image virtual", map[string]any{"image_id": plan.ImageId.ValueInt64()})
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceImageVirtual) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Get current state
var state models.ImageVirtualResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error get state")
return
}
tflog.Info(ctx, "Start delete image virtual", map[string]any{"image_id": state.ImageId.ValueInt64()})
// Set timeouts
deleteTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout300s)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, "Error set timeout")
return
}
ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
defer cancel()
var permanently bool
if state.Permanently.IsNull() {
permanently = true
} else {
permanently = state.Permanently.ValueBool()
}
// Delete image
_, err := r.client.CloudAPI().Image().Delete(ctx, image.DeleteRequest{ImageID: uint64(state.ImageId.ValueInt64()), Permanently: permanently})
if err != nil {
resp.Diagnostics.AddError("Error deleting image virtual with error: ", err.Error())
return
}
tflog.Info(ctx, "End delete image virtual", map[string]any{"image_id": state.ImageId.ValueInt64()})
}
// Schema defines the schema for the resource.
func (r *resourceImageVirtual) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: schemas.MakeSchemaResourceImageVirtual(),
Blocks: map[string]schema.Block{
"timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}),
},
Version: 1,
}
}
// Metadata returns the resource type name.
func (r *resourceImageVirtual) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_image_virtual"
}
// Configure adds the provider configured client to the resource.
func (r *resourceImageVirtual) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
tflog.Info(ctx, "Get configure resource")
r.client = client.Resource(ctx, &req, resp)
tflog.Info(ctx, "Getting configure resource successfully")
}
func (r *resourceImageVirtual) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Retrieve import ID and save to id attribute
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}

View File

@@ -0,0 +1,151 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceImage() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"image_id": schema.Int64Attribute{
Required: true,
},
// optional attributes
"show_all": schema.BoolAttribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"unc_path": schema.StringAttribute{
Computed: true,
},
"ckey": schema.StringAttribute{
Computed: true,
},
"account_id": schema.Int64Attribute{
Computed: true,
},
"acl": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"architecture": schema.StringAttribute{
Computed: true,
},
"boot_type": schema.StringAttribute{
Computed: true,
},
"bootable": schema.BoolAttribute{
Computed: true,
},
"compute_ci_id": schema.Int64Attribute{
Computed: true,
},
"cd_presented_to": schema.StringAttribute{
Computed: true,
},
"gid": schema.Int64Attribute{
Computed: true,
},
"deleted_time": schema.Int64Attribute{
Computed: true,
},
"desc": schema.StringAttribute{
Computed: true,
},
"drivers": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"enabled": schema.BoolAttribute{
Computed: true,
},
"guid": schema.Int64Attribute{
Computed: true,
},
"history": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"guid": schema.StringAttribute{
Computed: true,
},
"id": schema.Int64Attribute{
Computed: true,
},
"timestamp": schema.Int64Attribute{
Computed: true,
},
},
},
},
"hot_resize": schema.BoolAttribute{
Computed: true,
},
"last_modified": schema.Int64Attribute{
Computed: true,
},
"link_to": schema.Int64Attribute{
Computed: true,
},
"milestones": schema.Int64Attribute{
Computed: true,
},
"image_name": schema.StringAttribute{
Computed: true,
},
"image_type": schema.StringAttribute{
Computed: true,
},
"password": schema.StringAttribute{
Computed: true,
},
"network_interface_naming": schema.StringAttribute{
Computed: true,
},
"pool_name": schema.StringAttribute{
Computed: true,
},
"provider_name": schema.StringAttribute{
Computed: true,
},
"purge_attempts": schema.Int64Attribute{
Computed: true,
},
"present_to": schema.ListAttribute{
Computed: true,
ElementType: types.Int64Type,
},
"res_id": schema.StringAttribute{
Computed: true,
},
"rescuecd": schema.BoolAttribute{
Computed: true,
},
"sep_id": schema.Int64Attribute{
Computed: true,
},
"shared_with": schema.ListAttribute{
Computed: true,
ElementType: types.Int64Type,
},
"size": schema.Int64Attribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"username": schema.StringAttribute{
Computed: true,
},
"version": schema.StringAttribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,130 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaDataSourceImageList() map[string]schema.Attribute {
return map[string]schema.Attribute{
// optional attributes
"sep_id": schema.Int64Attribute{
Optional: true,
},
"by_id": schema.Int64Attribute{
Optional: true,
},
"name": schema.StringAttribute{
Optional: true,
},
"status": schema.StringAttribute{
Optional: true,
},
"architecture": schema.StringAttribute{
Optional: true,
},
"type_image": schema.StringAttribute{
Optional: true,
},
"image_size": schema.Int64Attribute{
Optional: true,
},
"sep_name": schema.StringAttribute{
Optional: true,
},
"pool_name": schema.StringAttribute{
Optional: true,
},
"public": schema.BoolAttribute{
Optional: true,
},
"hot_resize": schema.BoolAttribute{
Optional: true,
},
"bootable": schema.BoolAttribute{
Optional: true,
},
"sort_by": schema.StringAttribute{
Optional: true,
Description: "sort by one of supported fields, format +|-(field)",
},
"page": schema.Int64Attribute{
Optional: true,
},
"size": schema.Int64Attribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
},
"items": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"account_id": schema.Int64Attribute{
Computed: true,
},
"architecture": schema.StringAttribute{
Computed: true,
},
"boot_type": schema.StringAttribute{
Computed: true,
},
"bootable": schema.BoolAttribute{
Computed: true,
},
"cdrom": schema.BoolAttribute{
Computed: true,
},
"desc": schema.StringAttribute{
Computed: true,
},
"drivers": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"hot_resize": schema.BoolAttribute{
Computed: true,
},
"image_id": schema.Int64Attribute{
Computed: true,
},
"image_type": schema.StringAttribute{
Computed: true,
},
"link_to": schema.Int64Attribute{
Computed: true,
},
"image_name": schema.StringAttribute{
Computed: true,
},
"pool_name": schema.StringAttribute{
Computed: true,
},
"sep_id": schema.Int64Attribute{
Computed: true,
},
"size": schema.Int64Attribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"network_interface_naming": schema.StringAttribute{
Computed: true,
},
"username": schema.StringAttribute{
Computed: true,
},
"virtual": schema.BoolAttribute{
Computed: true,
},
},
},
},
"entry_count": schema.Int64Attribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,200 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaResourceImage() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"image_name": schema.StringAttribute{
Required: true,
Description: "Name of the rescue disk",
},
"url": schema.StringAttribute{
Required: true,
Description: "URL where to download media from",
},
"boot_type": schema.StringAttribute{
Required: true,
Validators: []validator.String{
stringvalidator.OneOf("bios", "uefi"),
},
Description: "Boot type of image bios or uefi",
},
"image_type": schema.StringAttribute{
Required: true,
Validators: []validator.String{
stringvalidator.OneOf("linux", "windows", "other"),
},
Description: "Image type linux, windows or other",
},
"drivers": schema.ListAttribute{
Required: true,
ElementType: types.StringType,
Description: "List of types of compute suitable for image. Example: [ \"KVM_X86\" ]",
},
"account_id": schema.Int64Attribute{
Required: true,
Description: "AccountId to make the image exclusive",
},
// optional attributes
"hot_resize": schema.BoolAttribute{
Computed: true,
Optional: true,
Description: "Does this machine supports hot resize",
},
"network_interface_naming": schema.StringAttribute{
Computed: true,
},
"username": schema.StringAttribute{
Computed: true,
Optional: true,
Description: "Optional username for the image",
},
"password": schema.StringAttribute{
Computed: true,
Optional: true,
Description: "Optional password for the image",
},
"username_dl": schema.StringAttribute{
Optional: true,
Description: "Username for upload binary media",
},
"password_dl": schema.StringAttribute{
Optional: true,
Description: "Password for upload binary media",
},
"sep_id": schema.Int64Attribute{
Computed: true,
Optional: true,
Description: "Storage endpoint provider ID",
},
"pool_name": schema.StringAttribute{
Computed: true,
Optional: true,
Description: "Pool for image create",
},
"architecture": schema.StringAttribute{
Computed: true,
Optional: true,
Validators: []validator.String{
stringvalidator.OneOf("X86_64", "PPC64_LE"),
},
Description: "Binary architecture of this image, one of X86_64 of PPC64_LE",
},
"permanently": schema.BoolAttribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"last_updated": schema.StringAttribute{
Computed: true,
Description: "Timestamp of the last Terraform update of the order.",
},
"unc_path": schema.StringAttribute{
Computed: true,
},
"ckey": schema.StringAttribute{
Computed: true,
},
"acl": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"bootable": schema.BoolAttribute{
Computed: true,
},
"compute_ci_id": schema.Int64Attribute{
Computed: true,
},
"cd_presented_to": schema.StringAttribute{
Computed: true,
},
"gid": schema.Int64Attribute{
Computed: true,
},
"deleted_time": schema.Int64Attribute{
Computed: true,
},
"desc": schema.StringAttribute{
Computed: true,
},
"enabled": schema.BoolAttribute{
Computed: true,
},
"guid": schema.Int64Attribute{
Computed: true,
},
"history": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"guid": schema.StringAttribute{
Computed: true,
},
"id": schema.Int64Attribute{
Computed: true,
},
"timestamp": schema.Int64Attribute{
Computed: true,
},
},
},
},
"last_modified": schema.Int64Attribute{
Computed: true,
},
"link_to": schema.Int64Attribute{
Computed: true,
},
"milestones": schema.Int64Attribute{
Computed: true,
},
"image_id": schema.Int64Attribute{
Computed: true,
},
"provider_name": schema.StringAttribute{
Computed: true,
},
"purge_attempts": schema.Int64Attribute{
Computed: true,
},
"present_to": schema.ListAttribute{
Computed: true,
ElementType: types.Int64Type,
},
"res_id": schema.StringAttribute{
Computed: true,
},
"rescuecd": schema.BoolAttribute{
Computed: true,
},
"shared_with": schema.ListAttribute{
Computed: true,
ElementType: types.Int64Type,
},
"size": schema.Int64Attribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"version": schema.StringAttribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,156 @@
package schemas
import (
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func MakeSchemaResourceImageVirtual() map[string]schema.Attribute {
return map[string]schema.Attribute{
// required attributes
"image_name": schema.StringAttribute{
Required: true,
Description: "Name of the rescue disk",
},
"link_to": schema.Int64Attribute{
Required: true,
Description: "ID of real image to link this virtual image to upon creation",
},
// optional attributes
"permanently": schema.BoolAttribute{
Optional: true,
},
// computed attributes
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"last_updated": schema.StringAttribute{
Computed: true,
Description: "Timestamp of the last Terraform update of the order.",
},
"unc_path": schema.StringAttribute{
Computed: true,
},
"ckey": schema.StringAttribute{
Computed: true,
},
"account_id": schema.Int64Attribute{
Computed: true,
},
"acl": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"architecture": schema.StringAttribute{
Computed: true,
},
"boot_type": schema.StringAttribute{
Computed: true,
},
"bootable": schema.BoolAttribute{
Computed: true,
},
"compute_ci_id": schema.Int64Attribute{
Computed: true,
},
"deleted_time": schema.Int64Attribute{
Computed: true,
},
"desc": schema.StringAttribute{
Computed: true,
},
"drivers": schema.ListAttribute{
Computed: true,
ElementType: types.StringType,
},
"enabled": schema.BoolAttribute{
Computed: true,
},
"gid": schema.Int64Attribute{
Computed: true,
},
"guid": schema.Int64Attribute{
Computed: true,
},
"history": schema.ListNestedAttribute{
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"guid": schema.StringAttribute{
Computed: true,
},
"id": schema.Int64Attribute{
Computed: true,
},
"timestamp": schema.Int64Attribute{
Computed: true,
},
},
},
},
"hot_resize": schema.BoolAttribute{
Computed: true,
},
"last_modified": schema.Int64Attribute{
Computed: true,
},
"milestones": schema.Int64Attribute{
Computed: true,
},
"image_id": schema.Int64Attribute{
Computed: true,
},
"image_type": schema.StringAttribute{
Computed: true,
},
"password": schema.StringAttribute{
Computed: true,
},
"pool_name": schema.StringAttribute{
Computed: true,
},
"provider_name": schema.StringAttribute{
Computed: true,
},
"purge_attempts": schema.Int64Attribute{
Computed: true,
},
"present_to": schema.ListAttribute{
Computed: true,
ElementType: types.Int64Type,
},
"res_id": schema.StringAttribute{
Computed: true,
},
"rescuecd": schema.BoolAttribute{
Computed: true,
},
"sep_id": schema.Int64Attribute{
Computed: true,
},
"shared_with": schema.ListAttribute{
Computed: true,
ElementType: types.Int64Type,
},
"size": schema.Int64Attribute{
Computed: true,
},
"status": schema.StringAttribute{
Computed: true,
},
"tech_status": schema.StringAttribute{
Computed: true,
},
"username": schema.StringAttribute{
Computed: true,
},
"version": schema.StringAttribute{
Computed: true,
},
}
}

View File

@@ -0,0 +1,26 @@
package utilities
import (
"context"
"github.com/hashicorp/terraform-plugin-framework/diag"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/ic"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
)
func CheckParamsExistenceImage(ctx context.Context, plan *models.ImageResourceModel, c *decort.DecortClient) diag.Diagnostics {
diags := diag.Diagnostics{}
// if err := ic.ExistGID(ctx, uint64(plan.GID.ValueInt64()), c); err != nil {
// diags.AddError("Error check input values", err.Error())
// }
if !plan.AccountID.IsUnknown() {
if err := ic.ExistAccount(ctx, uint64(plan.AccountID.ValueInt64()), c); err != nil {
diags.AddError("Error check input values", err.Error())
}
}
return diags
}

View File

@@ -0,0 +1,32 @@
package utilities
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
)
func ImageDataSourceCheckPresence(ctx context.Context, state *models.RecordImageModel, c *decort.DecortClient) (*image.RecordImage, error) {
tflog.Info(ctx, "Get info about image with ID", map[string]any{"image_id": state.ImageId.ValueInt64()})
req := image.GetRequest{ImageID: uint64(state.ImageId.ValueInt64())}
if state.ShowAll.IsNull() {
req.ShowAll = false
} else {
req.ShowAll = state.ShowAll.ValueBool()
}
image, err := c.CloudAPI().Image().Get(ctx, req)
if err != nil {
return nil, fmt.Errorf("cannot get info about image with error: %w", err)
}
tflog.Info(ctx, "Getting info about image successfully", map[string]any{"image_id": state.ImageId.ValueInt64()})
return image, nil
}

View File

@@ -0,0 +1,70 @@
package utilities
import (
"context"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
)
func ImageListCheckPresence(ctx context.Context, state *models.ListImagesModel, c *decort.DecortClient) (*image.ListImages, error) {
tflog.Info(ctx, "Get image list info")
req := image.ListRequest{}
if !state.SEPID.IsNull() {
req.SEPID = uint64(state.SEPID.ValueInt64())
}
if !state.ByID.IsNull() {
req.ByID = uint64(state.ByID.ValueInt64())
}
if !state.Name.IsNull() {
req.Name = state.Name.ValueString()
}
if !state.Status.IsNull() {
req.Status = state.Status.ValueString()
}
if !state.Architecture.IsNull() {
req.Architecture = state.Architecture.ValueString()
}
if !state.TypeImage.IsNull() {
req.TypeImage = state.TypeImage.ValueString()
}
if !state.ImageSize.IsNull() {
req.ImageSize = uint64(state.ImageSize.ValueInt64())
}
if !state.SEPName.IsNull() {
req.SEPName = state.SEPName.ValueString()
}
if !state.PoolName.IsNull() {
req.Pool = state.PoolName.ValueString()
}
if !state.Public.IsNull() {
req.Public = state.Public.ValueBool()
}
if !state.HotResize.IsNull() {
req.HotResize = state.HotResize.ValueBool()
}
if !state.Bootable.IsNull() {
req.Bootable = state.Bootable.ValueBool()
}
if !state.SortBy.IsNull() {
req.SortBy = state.SortBy.ValueString()
}
if !state.Size.IsNull() {
req.Size = uint64(state.Size.ValueInt64())
}
if !state.Page.IsNull() {
req.Page = uint64(state.Page.ValueInt64())
}
imageList, err := c.CloudAPI().Image().List(ctx, req)
if err != nil {
return nil, err
}
tflog.Info(ctx, "Getting image list info, successfully")
return imageList, nil
}

View File

@@ -0,0 +1,143 @@
package utilities
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/status"
)
func createRequestResourceImage(ctx context.Context, plan *models.ImageResourceModel) image.CreateRequest {
tflog.Info(ctx, "Start createRequestResourceImage", map[string]any{"name": plan.ImageName.ValueString()})
req := image.CreateRequest{
Name: plan.ImageName.ValueString(),
URL: plan.URL.ValueString(),
BootType: plan.BootType.ValueString(),
ImageType: plan.ImageType.ValueString(),
}
result := make([]string, 0, len(plan.Drivers.Elements()))
for _, val := range plan.Drivers.Elements() {
result = append(result, strings.Trim(val.String(), "\""))
}
req.Drivers = result
if plan.HotResize.IsUnknown() {
req.HotResize = false
} else {
req.HotResize = plan.HotResize.ValueBool()
}
if !plan.Username.IsUnknown() {
req.Username = plan.Username.ValueString()
}
if !plan.Password.IsUnknown() {
req.Password = plan.Password.ValueString()
}
if !plan.AccountID.IsUnknown() {
req.AccountID = uint64(plan.AccountID.ValueInt64())
}
if !plan.UsernameDL.IsNull() {
req.UsernameDL = plan.UsernameDL.ValueString()
}
if !plan.PasswordDL.IsNull() {
req.PasswordDL = plan.PasswordDL.ValueString()
}
if !plan.SepID.IsUnknown() {
req.SEPID = uint64(plan.SepID.ValueInt64())
}
if !plan.PoolName.IsUnknown() {
req.Pool = plan.PoolName.ValueString()
}
if plan.Architecture.IsUnknown() {
req.Architecture = "X86_64"
} else {
req.Architecture = plan.Architecture.ValueString()
}
tflog.Info(ctx, "End createRequestResourceImage", map[string]any{"name": plan.ImageName.ValueString()})
return req
}
func ResourceImageCreate(ctx context.Context, plan *models.ImageResourceModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start ResourceImageCreate", map[string]any{"name": plan.ImageName.ValueString()})
diags := diag.Diagnostics{}
// Make request and get response
imageId, err := c.CloudAPI().Image().Create(ctx, createRequestResourceImage(ctx, plan))
if err != nil {
tflog.Error(ctx, "Error response for create image")
diags.AddError("Unable to Create image", err.Error())
return diags
}
plan.Id = types.StringValue(strconv.Itoa(int(imageId)))
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
tflog.Info(ctx, "End ResourceImageCreate", map[string]any{"image_id": imageId})
return nil
}
func ImageResourceCheckPresence(ctx context.Context, imageId uint64, c *decort.DecortClient) (*image.RecordImage, error) {
tflog.Info(ctx, "Get info about image with ID", map[string]any{"image_id": imageId})
image, err := c.CloudAPI().Image().Get(ctx, image.GetRequest{ImageID: imageId})
if err != nil {
return nil, fmt.Errorf("cannot get info about image with error: %w", err)
}
tflog.Info(ctx, "Getting info about image successfully", map[string]any{"image_id": imageId})
return image, nil
}
func ImageReadStatus(ctx context.Context, imageId uint64, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Read status image with ID", map[string]any{"image": imageId})
diags := diag.Diagnostics{}
image, err := ImageResourceCheckPresence(ctx, imageId, c)
if err != nil {
diags.AddError("Cannot get info about image ", err.Error())
return diags
}
switch image.Status {
case status.Modeled:
diags.AddError("Error:", fmt.Sprintf("The image is in status: %s, please, contact support for more information", image.Status))
return diags
case status.Destroying:
diags.AddError("Error:", fmt.Sprintf("The image is in progress with status: %s", image.Status))
return diags
case status.Destroyed, status.Purged:
diags.AddError("Error:", "The resource cannot be updated because it has been destroyed")
return diags
}
tflog.Info(ctx, "Read status image successfully", map[string]any{"image_id": imageId})
return nil
}
func ImageUpdateName(ctx context.Context, imageId uint64, name string, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Update name image with ID", map[string]any{"image_id": imageId})
diags := diag.Diagnostics{}
_, err := c.CloudAPI().Image().Rename(ctx, image.RenameRequest{ImageID: imageId, Name: name})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot update name image with ID - %d", imageId), err.Error())
return diags
}
tflog.Info(ctx, "Update name image successfully", map[string]any{"image_id": imageId})
return nil
}

View File

@@ -0,0 +1,62 @@
package utilities
import (
"context"
"fmt"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
decort "repository.basistech.ru/BASIS/decort-golang-sdk"
"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/image/models"
)
func createRequestResourceImageVirtual(ctx context.Context, plan *models.ImageVirtualResourceModel) image.CreateVirtualRequest {
tflog.Info(ctx, "Start createRequestResourceImageVirtual", map[string]any{"name": plan.ImageName.ValueString()})
req := image.CreateVirtualRequest{
Name: plan.ImageName.ValueString(),
TargetID: uint64(plan.LinkTo.ValueInt64()),
}
tflog.Info(ctx, "End createRequestResourceImageVirtual", map[string]any{"name": plan.ImageName.ValueString()})
return req
}
func ResourceImageVirtualCreate(ctx context.Context, plan *models.ImageVirtualResourceModel, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Start ResourceImageVirtualCreate", map[string]any{"name": plan.ImageName.ValueString()})
diags := diag.Diagnostics{}
// Make request and get response
imageId, err := c.CloudAPI().Image().CreateVirtual(ctx, createRequestResourceImageVirtual(ctx, plan))
if err != nil {
tflog.Error(ctx, "Error response for create image_virtual")
diags.AddError("Unable to Create image_virtual", err.Error())
return diags
}
plan.Id = types.StringValue(strconv.Itoa(int(imageId)))
plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
tflog.Info(ctx, "End ResourceImageVirtualCreate", map[string]any{"image_id": imageId})
return nil
}
func ImageUpdateLink(ctx context.Context, imageId, linkTo uint64, c *decort.DecortClient) diag.Diagnostics {
tflog.Info(ctx, "Update link_to image virtual with ID", map[string]any{"image_id": imageId})
diags := diag.Diagnostics{}
_, err := c.CloudAPI().Image().Link(ctx, image.LinkRequest{ImageID: imageId, TargetID: linkTo})
if err != nil {
diags.AddError(fmt.Sprintf("Cannot update link_to image virtual with ID - %d", imageId), err.Error())
return diags
}
tflog.Info(ctx, "Update link_to image virtual successfully", map[string]any{"image_id": imageId})
return nil
}