Feat/separate functions (#19)
* chore: work save * fix: refactor flavors * fix: refactor pg user and database * fix: refactor flavor parameters * fix: refactor tf script * chore: work save * chore: work save * chore: work save --------- Co-authored-by: Marcel S. Henselin <marcel.henselin@stackit.cloud>
This commit is contained in:
parent
910551f09d
commit
0150fea302
54 changed files with 6010 additions and 2826 deletions
|
|
@ -0,0 +1,252 @@
|
|||
package sqlserverFlexAlphaFlavor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/sqlserverflexalpha"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/utils"
|
||||
|
||||
sqlserverflex "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha"
|
||||
sqlserverflexUtils "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &flavorDataSource{}
|
||||
)
|
||||
|
||||
type FlavorModel struct {
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
StorageClass types.String `tfsdk:"storage_class"`
|
||||
Cpu types.Int64 `tfsdk:"cpu"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
Id types.String `tfsdk:"id"`
|
||||
FlavorId types.String `tfsdk:"flavor_id"`
|
||||
MaxGb types.Int64 `tfsdk:"max_gb"`
|
||||
Memory types.Int64 `tfsdk:"ram"`
|
||||
MinGb types.Int64 `tfsdk:"min_gb"`
|
||||
NodeType types.String `tfsdk:"node_type"`
|
||||
StorageClasses types.List `tfsdk:"storage_classes"`
|
||||
}
|
||||
|
||||
// NewFlavorDataSource is a helper function to simplify the provider implementation.
|
||||
func NewFlavorDataSource() datasource.DataSource {
|
||||
return &flavorDataSource{}
|
||||
}
|
||||
|
||||
// flavorDataSource is the data source implementation.
|
||||
type flavorDataSource struct {
|
||||
client *sqlserverflexalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (r *flavorDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_sqlserverflexalpha_flavor"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
func (r *flavorDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex instance client configured")
|
||||
}
|
||||
|
||||
func (r *flavorDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"project_id": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The cpu count of the instance.",
|
||||
MarkdownDescription: "The cpu count of the instance.",
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The flavor description.",
|
||||
MarkdownDescription: "The flavor description.",
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Required: true,
|
||||
Description: "The cpu count of the instance.",
|
||||
MarkdownDescription: "The cpu count of the instance.",
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Required: true,
|
||||
Description: "The memory of the instance in Gibibyte.",
|
||||
MarkdownDescription: "The memory of the instance in Gibibyte.",
|
||||
},
|
||||
"storage_class": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "The memory of the instance in Gibibyte.",
|
||||
MarkdownDescription: "The memory of the instance in Gibibyte.",
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The flavor description.",
|
||||
MarkdownDescription: "The flavor description.",
|
||||
},
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The terraform id of the instance flavor.",
|
||||
MarkdownDescription: "The terraform id of the instance flavor.",
|
||||
},
|
||||
"flavor_id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The flavor id of the instance flavor.",
|
||||
MarkdownDescription: "The flavor id of the instance flavor.",
|
||||
},
|
||||
"max_gb": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "maximum storage which can be ordered for the flavor in Gigabyte.",
|
||||
MarkdownDescription: "maximum storage which can be ordered for the flavor in Gigabyte.",
|
||||
},
|
||||
"min_gb": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
Description: "minimum storage which is required to order in Gigabyte.",
|
||||
MarkdownDescription: "minimum storage which is required to order in Gigabyte.",
|
||||
},
|
||||
"node_type": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "defines the nodeType it can be either single or replica",
|
||||
MarkdownDescription: "defines the nodeType it can be either single or replica",
|
||||
},
|
||||
"storage_classes": schema.ListNestedAttribute{
|
||||
Computed: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"max_io_per_sec": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"max_through_in_mb": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
CustomType: sqlserverflex.StorageClassesType{
|
||||
ObjectType: types.ObjectType{
|
||||
AttrTypes: sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *flavorDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
|
||||
var model FlavorModel
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
flavors, err := getAllFlavors(ctx, r.client, projectId, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading flavors", fmt.Sprintf("getAllFlavors: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
var foundFlavors []sqlserverflexalpha.ListFlavors
|
||||
for _, flavor := range flavors {
|
||||
if model.Cpu.ValueInt64() != *flavor.Cpu {
|
||||
continue
|
||||
}
|
||||
if model.Memory.ValueInt64() != *flavor.Memory {
|
||||
continue
|
||||
}
|
||||
if model.NodeType.ValueString() != *flavor.NodeType {
|
||||
continue
|
||||
}
|
||||
for _, sc := range *flavor.StorageClasses {
|
||||
if model.StorageClass.ValueString() != *sc.Class {
|
||||
continue
|
||||
}
|
||||
foundFlavors = append(foundFlavors, flavor)
|
||||
}
|
||||
}
|
||||
if len(foundFlavors) == 0 {
|
||||
resp.Diagnostics.AddError("get flavor", "could not find requested flavor")
|
||||
return
|
||||
}
|
||||
if len(foundFlavors) > 1 {
|
||||
resp.Diagnostics.AddError("get flavor", "found too many matching flavors")
|
||||
return
|
||||
}
|
||||
|
||||
f := foundFlavors[0]
|
||||
model.Description = types.StringValue(*f.Description)
|
||||
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, *f.Id)
|
||||
model.FlavorId = types.StringValue(*f.Id)
|
||||
model.MaxGb = types.Int64Value(*f.MaxGB)
|
||||
model.MinGb = types.Int64Value(*f.MinGB)
|
||||
|
||||
if f.StorageClasses == nil {
|
||||
model.StorageClasses = types.ListNull(sqlserverflex.StorageClassesType{
|
||||
ObjectType: basetypes.ObjectType{
|
||||
AttrTypes: sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
|
||||
},
|
||||
})
|
||||
} else {
|
||||
var scList []attr.Value
|
||||
for _, sc := range *f.StorageClasses {
|
||||
scList = append(
|
||||
scList,
|
||||
sqlserverflex.NewStorageClassesValueMust(
|
||||
sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
|
||||
map[string]attr.Value{
|
||||
"class": types.StringValue(*sc.Class),
|
||||
"max_io_per_sec": types.Int64Value(*sc.MaxIoPerSec),
|
||||
"max_through_in_mb": types.Int64Value(*sc.MaxThroughInMb),
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
storageClassesList := types.ListValueMust(
|
||||
sqlserverflex.StorageClassesType{
|
||||
ObjectType: basetypes.ObjectType{
|
||||
AttrTypes: sqlserverflex.StorageClassesValue{}.AttributeTypes(ctx),
|
||||
},
|
||||
},
|
||||
scList,
|
||||
)
|
||||
model.StorageClasses = storageClassesList
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex flavors read")
|
||||
}
|
||||
201
stackit/internal/services/sqlserverflexalpha/flavor/functions.go
Normal file
201
stackit/internal/services/sqlserverflexalpha/flavor/functions.go
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
package sqlserverFlexAlphaFlavor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
sqlserverflex "github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/sqlserverflexalpha"
|
||||
)
|
||||
|
||||
type flavorsClient interface {
|
||||
GetFlavorsRequestExecute(
|
||||
ctx context.Context,
|
||||
projectId, region string,
|
||||
page, size *int64,
|
||||
sort *sqlserverflex.FlavorSort,
|
||||
) (*sqlserverflex.GetFlavorsResponse, error)
|
||||
}
|
||||
|
||||
//func loadFlavorId(ctx context.Context, client flavorsClient, model *Model, flavor *flavorModel, storage *storageModel) error {
|
||||
// if model == nil {
|
||||
// return fmt.Errorf("nil model")
|
||||
// }
|
||||
// if flavor == nil {
|
||||
// return fmt.Errorf("nil flavor")
|
||||
// }
|
||||
// cpu := flavor.CPU.ValueInt64()
|
||||
// if cpu == 0 {
|
||||
// return fmt.Errorf("nil CPU")
|
||||
// }
|
||||
// ram := flavor.RAM.ValueInt64()
|
||||
// if ram == 0 {
|
||||
// return fmt.Errorf("nil RAM")
|
||||
// }
|
||||
//
|
||||
// nodeType := flavor.NodeType.ValueString()
|
||||
// if nodeType == "" {
|
||||
// if model.Replicas.IsNull() || model.Replicas.IsUnknown() {
|
||||
// return fmt.Errorf("nil NodeType")
|
||||
// }
|
||||
// switch model.Replicas.ValueInt64() {
|
||||
// case 1:
|
||||
// nodeType = "Single"
|
||||
// case 3:
|
||||
// nodeType = "Replica"
|
||||
// default:
|
||||
// return fmt.Errorf("unknown Replicas value: %d", model.Replicas.ValueInt64())
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// storageClass := conversion.StringValueToPointer(storage.Class)
|
||||
// if storageClass == nil {
|
||||
// return fmt.Errorf("nil StorageClass")
|
||||
// }
|
||||
// storageSize := conversion.Int64ValueToPointer(storage.Size)
|
||||
// if storageSize == nil {
|
||||
// return fmt.Errorf("nil StorageSize")
|
||||
// }
|
||||
//
|
||||
// projectId := model.ProjectId.ValueString()
|
||||
// region := model.Region.ValueString()
|
||||
//
|
||||
// flavorList, err := getAllFlavors(ctx, client, projectId, region)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// avl := ""
|
||||
// foundFlavorCount := 0
|
||||
// var foundFlavors []string
|
||||
// for _, f := range flavorList {
|
||||
// if f.Id == nil || f.Cpu == nil || f.Memory == nil {
|
||||
// continue
|
||||
// }
|
||||
// if !strings.EqualFold(*f.NodeType, nodeType) {
|
||||
// continue
|
||||
// }
|
||||
// if *f.Cpu == cpu && *f.Memory == ram {
|
||||
// var useSc *sqlserverflex.FlavorStorageClassesStorageClass
|
||||
// for _, sc := range *f.StorageClasses {
|
||||
// if *sc.Class != *storageClass {
|
||||
// continue
|
||||
// }
|
||||
// if *storageSize < *f.MinGB || *storageSize > *f.MaxGB {
|
||||
// return fmt.Errorf("storage size %d out of bounds (min: %d - max: %d)", *storageSize, *f.MinGB, *f.MaxGB)
|
||||
// }
|
||||
// useSc = &sc
|
||||
// }
|
||||
// if useSc == nil {
|
||||
// return fmt.Errorf("no storage class found for %s", *storageClass)
|
||||
// }
|
||||
//
|
||||
// flavor.Id = types.StringValue(*f.Id)
|
||||
// flavor.Description = types.StringValue(*f.Description)
|
||||
// foundFlavors = append(foundFlavors, fmt.Sprintf("%s (%d/%d - %s)", *f.Id, *f.Cpu, *f.Memory, *f.NodeType))
|
||||
// foundFlavorCount++
|
||||
// }
|
||||
// for _, cls := range *f.StorageClasses {
|
||||
// avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM, storage %s (min: %d - max: %d)", avl, *f.Cpu, *f.Memory, *cls.Class, *f.MinGB, *f.MaxGB)
|
||||
// }
|
||||
// }
|
||||
// if foundFlavorCount > 1 {
|
||||
// return fmt.Errorf(
|
||||
// "number of flavors returned: %d\nmultiple flavors found: %d flavors\n %s",
|
||||
// len(flavorList),
|
||||
// foundFlavorCount,
|
||||
// strings.Join(foundFlavors, "\n "),
|
||||
// )
|
||||
// }
|
||||
// if flavor.Id.ValueString() == "" {
|
||||
// return fmt.Errorf("couldn't find flavor, available specs are:%s", avl)
|
||||
// }
|
||||
//
|
||||
// return nil
|
||||
//}
|
||||
|
||||
func getAllFlavors(ctx context.Context, client flavorsClient, projectId, region string) ([]sqlserverflex.ListFlavors, error) {
|
||||
if projectId == "" || region == "" {
|
||||
return nil, fmt.Errorf("listing sqlserverflex flavors: projectId and region are required")
|
||||
}
|
||||
var flavorList []sqlserverflex.ListFlavors
|
||||
|
||||
page := int64(1)
|
||||
size := int64(10)
|
||||
sort := sqlserverflex.FLAVORSORT_INDEX_ASC
|
||||
counter := 0
|
||||
for {
|
||||
res, err := client.GetFlavorsRequestExecute(ctx, projectId, region, &page, &size, &sort)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing sqlserverflex flavors: %w", err)
|
||||
}
|
||||
if res.Flavors == nil {
|
||||
return nil, fmt.Errorf("finding flavors for project %s", projectId)
|
||||
}
|
||||
pagination := res.GetPagination()
|
||||
flavors := res.GetFlavors()
|
||||
flavorList = append(flavorList, flavors...)
|
||||
|
||||
if *pagination.TotalRows < int64(len(flavorList)) {
|
||||
return nil, fmt.Errorf("total rows is smaller than current accumulated list - that should not happen")
|
||||
}
|
||||
if *pagination.TotalRows == int64(len(flavorList)) {
|
||||
break
|
||||
}
|
||||
page++
|
||||
|
||||
if page > *pagination.TotalPages {
|
||||
break
|
||||
}
|
||||
|
||||
// implement a breakpoint
|
||||
counter++
|
||||
if counter > 1000 {
|
||||
panic("too many pagination results")
|
||||
}
|
||||
}
|
||||
return flavorList, nil
|
||||
}
|
||||
|
||||
//func getFlavorModelById(ctx context.Context, client flavorsClient, model *Model, flavor *flavorModel) error {
|
||||
// if model == nil {
|
||||
// return fmt.Errorf("nil model")
|
||||
// }
|
||||
// if flavor == nil {
|
||||
// return fmt.Errorf("nil flavor")
|
||||
// }
|
||||
// id := conversion.StringValueToPointer(flavor.Id)
|
||||
// if id == nil {
|
||||
// return fmt.Errorf("nil flavor ID")
|
||||
// }
|
||||
//
|
||||
// flavor.Id = types.StringValue("")
|
||||
//
|
||||
// projectId := model.ProjectId.ValueString()
|
||||
// region := model.Region.ValueString()
|
||||
//
|
||||
// flavorList, err := getAllFlavors(ctx, client, projectId, region)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// avl := ""
|
||||
// for _, f := range flavorList {
|
||||
// if f.Id == nil || f.Cpu == nil || f.Memory == nil {
|
||||
// continue
|
||||
// }
|
||||
// if *f.Id == *id {
|
||||
// flavor.Id = types.StringValue(*f.Id)
|
||||
// flavor.Description = types.StringValue(*f.Description)
|
||||
// flavor.CPU = types.Int64Value(*f.Cpu)
|
||||
// flavor.RAM = types.Int64Value(*f.Memory)
|
||||
// flavor.NodeType = types.StringValue(*f.NodeType)
|
||||
// break
|
||||
// }
|
||||
// avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM", avl, *f.Cpu, *f.Memory)
|
||||
// }
|
||||
// if flavor.Id.ValueString() == "" {
|
||||
// return fmt.Errorf("couldn't find flavor, available specs are: %s", avl)
|
||||
// }
|
||||
//
|
||||
// return nil
|
||||
//}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
package postgresFlexAlphaFlavor
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/postgresflexalpha"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha"
|
||||
postgresflexUtils "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &flavorListDataSource{}
|
||||
)
|
||||
|
||||
// NewFlavorListDataSource is a helper function to simplify the provider implementation.
|
||||
func NewFlavorListDataSource() datasource.DataSource {
|
||||
return &flavorListDataSource{}
|
||||
}
|
||||
|
||||
// flavorDataSource is the data source implementation.
|
||||
type flavorListDataSource struct {
|
||||
client *postgresflexalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (r *flavorListDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_flavorlist"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
func (r *flavorListDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex flavors client configured")
|
||||
}
|
||||
|
||||
func (r *flavorListDataSource) Schema(ctx context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = postgresflex.FlavorDataSourceSchema(ctx)
|
||||
}
|
||||
|
||||
func (r *flavorListDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
|
||||
var model postgresflex.FlavorModel
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex flavors read")
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -253,22 +253,6 @@ func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadReques
|
|||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if model.Flavor.IsNull() || model.Flavor.IsUnknown() {
|
||||
flavor.Id = types.StringValue(*instanceResp.FlavorId)
|
||||
if flavor.Id.IsNull() || flavor.Id.IsUnknown() || flavor.Id.String() == "" {
|
||||
panic("WTF FlavorId can not be null or empty string")
|
||||
}
|
||||
err = getFlavorModelById(ctx, r.client, &model, flavor)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError(err.Error(), err.Error())
|
||||
return
|
||||
}
|
||||
if flavor.CPU.IsNull() || flavor.CPU.IsUnknown() || flavor.CPU.String() == "" {
|
||||
panic("WTF FlavorId can not be null or empty string")
|
||||
}
|
||||
}
|
||||
|
||||
var storage = &storageModel{}
|
||||
if !model.Storage.IsNull() && !model.Storage.IsUnknown() {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
|
|
@ -296,7 +280,7 @@ func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadReques
|
|||
}
|
||||
}
|
||||
|
||||
err = mapFields(ctx, instanceResp, &model, flavor, storage, encryption, network, region)
|
||||
err = mapFields(ctx, instanceResp, &model, storage, encryption, network, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
|
|
|
|||
|
|
@ -4,11 +4,9 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
sqlserverflex "github.com/mhenselin/terraform-provider-stackitprivatepreview/pkg/sqlserverflexalpha"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/conversion"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
|
|
@ -19,7 +17,7 @@ type sqlserverflexClient interface {
|
|||
GetFlavorsRequestExecute(ctx context.Context, projectId, region string, page, size *int64, sort *sqlserverflex.FlavorSort) (*sqlserverflex.GetFlavorsResponse, error)
|
||||
}
|
||||
|
||||
func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, model *Model, flavor *flavorModel, storage *storageModel, encryption *encryptionModel, network *networkModel, region string) error {
|
||||
func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, model *Model, storage *storageModel, encryption *encryptionModel, network *networkModel, region string) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
|
|
@ -37,26 +35,6 @@ func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, mod
|
|||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
var flavorValues map[string]attr.Value
|
||||
if instance.FlavorId == nil {
|
||||
return fmt.Errorf("instance has no flavor id")
|
||||
}
|
||||
if *instance.FlavorId != flavor.Id.ValueString() {
|
||||
return fmt.Errorf("instance has different flavor id %s - %s", *instance.FlavorId, flavor.Id.ValueString())
|
||||
}
|
||||
|
||||
flavorValues = map[string]attr.Value{
|
||||
"id": flavor.Id,
|
||||
"description": flavor.Description,
|
||||
"cpu": flavor.CPU,
|
||||
"ram": flavor.RAM,
|
||||
"node_type": flavor.NodeType,
|
||||
}
|
||||
flavorObject, diags := types.ObjectValue(flavorTypes, flavorValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("creating flavor: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
var storageValues map[string]attr.Value
|
||||
if instance.Storage == nil {
|
||||
storageValues = map[string]attr.Value{
|
||||
|
|
@ -163,7 +141,7 @@ func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, mod
|
|||
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, instanceId)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.Flavor = flavorObject
|
||||
model.FlavorId = types.StringPointerValue(instance.FlavorId)
|
||||
model.Replicas = types.Int64Value(int64(*instance.Replicas))
|
||||
model.Storage = storageObject
|
||||
model.Version = types.StringValue(string(*instance.Version))
|
||||
|
|
@ -182,10 +160,6 @@ func toCreatePayload(model *Model, storage *storageModel, encryption *encryption
|
|||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if model.Flavor.IsNull() || model.Flavor.IsUnknown() {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
|
||||
storagePayload := &sqlserverflex.CreateInstanceRequestPayloadGetStorageArgType{}
|
||||
if storage != nil {
|
||||
storagePayload.Class = conversion.StringValueToPointer(storage.Class)
|
||||
|
|
@ -200,16 +174,6 @@ func toCreatePayload(model *Model, storage *storageModel, encryption *encryption
|
|||
encryptionPayload.ServiceAccount = conversion.StringValueToPointer(encryption.ServiceAccount)
|
||||
}
|
||||
|
||||
flavorId := ""
|
||||
if !model.Flavor.IsNull() && !model.Flavor.IsUnknown() {
|
||||
modelValues := model.Flavor.Attributes()
|
||||
if _, ok := modelValues["id"]; !ok {
|
||||
return nil, fmt.Errorf("flavor has not yet been created")
|
||||
}
|
||||
// TODO - how to get rid of that trim?
|
||||
flavorId = strings.Trim(modelValues["id"].String(), "\"")
|
||||
}
|
||||
|
||||
var aclElements []string
|
||||
if network != nil && !network.ACL.IsNull() && !network.ACL.IsUnknown() {
|
||||
aclElements = make([]string, 0, len(network.ACL.Elements()))
|
||||
|
|
@ -227,31 +191,20 @@ func toCreatePayload(model *Model, storage *storageModel, encryption *encryption
|
|||
|
||||
return &sqlserverflex.CreateInstanceRequestPayload{
|
||||
BackupSchedule: conversion.StringValueToPointer(model.BackupSchedule),
|
||||
FlavorId: &flavorId,
|
||||
Encryption: encryptionPayload,
|
||||
FlavorId: conversion.StringValueToPointer(model.FlavorId),
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
Network: networkPayload,
|
||||
RetentionDays: conversion.Int64ValueToPointer(model.RetentionDays),
|
||||
Storage: storagePayload,
|
||||
Version: sqlserverflex.CreateInstanceRequestPayloadGetVersionAttributeType(conversion.StringValueToPointer(model.Version)),
|
||||
Encryption: encryptionPayload,
|
||||
RetentionDays: conversion.Int64ValueToPointer(model.RetentionDays),
|
||||
Network: networkPayload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, storage *storageModel, network *networkModel) (*sqlserverflex.UpdateInstancePartiallyRequestPayload, error) {
|
||||
func toUpdatePartiallyPayload(model *Model, storage *storageModel, network *networkModel) (*sqlserverflex.UpdateInstancePartiallyRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if model.Flavor.IsNull() || model.Flavor.IsUnknown() {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
var flavorMdl flavorModel
|
||||
diag := model.Flavor.As(context.Background(), &flavorMdl, basetypes.ObjectAsOptions{
|
||||
UnhandledNullAsEmpty: true,
|
||||
UnhandledUnknownAsEmpty: false,
|
||||
})
|
||||
if diag.HasError() {
|
||||
return nil, fmt.Errorf("flavor conversion error: %v", diag.Errors())
|
||||
}
|
||||
|
||||
storagePayload := &sqlserverflex.UpdateInstanceRequestPayloadGetStorageArgType{}
|
||||
if storage != nil {
|
||||
|
|
@ -277,12 +230,11 @@ func toUpdatePayload(model *Model, storage *storageModel, network *networkModel)
|
|||
return nil, fmt.Errorf("replica count too big: %d", model.Replicas.ValueInt64())
|
||||
}
|
||||
replCount := int32(model.Replicas.ValueInt64()) // nolint:gosec // check is performed above
|
||||
flavorId := flavorMdl.Id.ValueString()
|
||||
return &sqlserverflex.UpdateInstancePartiallyRequestPayload{
|
||||
Network: networkPayload,
|
||||
BackupSchedule: conversion.StringValueToPointer(model.BackupSchedule),
|
||||
FlavorId: &flavorId,
|
||||
FlavorId: conversion.StringValueToPointer(model.FlavorId),
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
Network: networkPayload,
|
||||
Replicas: sqlserverflex.UpdateInstancePartiallyRequestPayloadGetReplicasAttributeType(&replCount),
|
||||
RetentionDays: conversion.Int64ValueToPointer(model.RetentionDays),
|
||||
Storage: storagePayload,
|
||||
|
|
@ -290,152 +242,15 @@ func toUpdatePayload(model *Model, storage *storageModel, network *networkModel)
|
|||
}, nil
|
||||
}
|
||||
|
||||
func getAllFlavors(ctx context.Context, client sqlserverflexClient, projectId, region string) ([]sqlserverflex.ListFlavors, error) {
|
||||
if projectId == "" || region == "" {
|
||||
return nil, fmt.Errorf("listing sqlserverflex flavors: projectId and region are required")
|
||||
}
|
||||
var flavorList []sqlserverflex.ListFlavors
|
||||
|
||||
page := int64(1)
|
||||
size := int64(10)
|
||||
for {
|
||||
sort := sqlserverflex.FLAVORSORT_INDEX_ASC
|
||||
res, err := client.GetFlavorsRequestExecute(ctx, projectId, region, &page, &size, &sort)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listing sqlserverflex flavors: %w", err)
|
||||
}
|
||||
if res.Flavors == nil {
|
||||
return nil, fmt.Errorf("finding flavors for project %s", projectId)
|
||||
}
|
||||
pagination := res.GetPagination()
|
||||
flavorList = append(flavorList, *res.Flavors...)
|
||||
|
||||
if *pagination.TotalRows == int64(len(flavorList)) {
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
return flavorList, nil
|
||||
}
|
||||
|
||||
func loadFlavorId(ctx context.Context, client sqlserverflexClient, model *Model, flavor *flavorModel, storage *storageModel) error {
|
||||
if model == nil {
|
||||
return fmt.Errorf("nil model")
|
||||
}
|
||||
if flavor == nil {
|
||||
return fmt.Errorf("nil flavor")
|
||||
}
|
||||
cpu := conversion.Int64ValueToPointer(flavor.CPU)
|
||||
if cpu == nil {
|
||||
return fmt.Errorf("nil CPU")
|
||||
}
|
||||
ram := conversion.Int64ValueToPointer(flavor.RAM)
|
||||
if ram == nil {
|
||||
return fmt.Errorf("nil RAM")
|
||||
}
|
||||
nodeType := conversion.StringValueToPointer(flavor.NodeType)
|
||||
if nodeType == nil {
|
||||
return fmt.Errorf("nil NodeType")
|
||||
}
|
||||
storageClass := conversion.StringValueToPointer(storage.Class)
|
||||
if storageClass == nil {
|
||||
return fmt.Errorf("nil StorageClass")
|
||||
}
|
||||
storageSize := conversion.Int64ValueToPointer(storage.Size)
|
||||
if storageSize == nil {
|
||||
return fmt.Errorf("nil StorageSize")
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
|
||||
flavorList, err := getAllFlavors(ctx, client, projectId, region)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
avl := ""
|
||||
foundFlavorCount := 0
|
||||
for _, f := range flavorList {
|
||||
if f.Id == nil || f.Cpu == nil || f.Memory == nil {
|
||||
continue
|
||||
}
|
||||
if !strings.EqualFold(*f.NodeType, *nodeType) {
|
||||
continue
|
||||
}
|
||||
if *f.Cpu == *cpu && *f.Memory == *ram {
|
||||
var useSc *sqlserverflex.FlavorStorageClassesStorageClass
|
||||
for _, sc := range *f.StorageClasses {
|
||||
if *sc.Class != *storageClass {
|
||||
continue
|
||||
}
|
||||
if *storageSize < *f.MinGB || *storageSize > *f.MaxGB {
|
||||
return fmt.Errorf("storage size %d out of bounds (min: %d - max: %d)", *storageSize, *f.MinGB, *f.MaxGB)
|
||||
}
|
||||
useSc = &sc
|
||||
}
|
||||
if useSc == nil {
|
||||
return fmt.Errorf("no storage class found for %s", *storageClass)
|
||||
}
|
||||
|
||||
flavor.Id = types.StringValue(*f.Id)
|
||||
flavor.Description = types.StringValue(*f.Description)
|
||||
foundFlavorCount++
|
||||
}
|
||||
for _, cls := range *f.StorageClasses {
|
||||
avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM, storage %s (min: %d - max: %d)", avl, *f.Cpu, *f.Memory, *cls.Class, *f.MinGB, *f.MaxGB)
|
||||
}
|
||||
}
|
||||
if foundFlavorCount > 1 {
|
||||
return fmt.Errorf("multiple flavors found: %d flavors", foundFlavorCount)
|
||||
}
|
||||
if flavor.Id.ValueString() == "" {
|
||||
return fmt.Errorf("couldn't find flavor, available specs are:%s", avl)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getFlavorModelById(ctx context.Context, client sqlserverflexClient, model *Model, flavor *flavorModel) error {
|
||||
if model == nil {
|
||||
return fmt.Errorf("nil model")
|
||||
}
|
||||
if flavor == nil {
|
||||
return fmt.Errorf("nil flavor")
|
||||
}
|
||||
id := conversion.StringValueToPointer(flavor.Id)
|
||||
if id == nil {
|
||||
return fmt.Errorf("nil flavor ID")
|
||||
}
|
||||
|
||||
flavor.Id = types.StringValue("")
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
|
||||
flavorList, err := getAllFlavors(ctx, client, projectId, region)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
avl := ""
|
||||
for _, f := range flavorList {
|
||||
if f.Id == nil || f.Cpu == nil || f.Memory == nil {
|
||||
continue
|
||||
}
|
||||
if *f.Id == *id {
|
||||
flavor.Id = types.StringValue(*f.Id)
|
||||
flavor.Description = types.StringValue(*f.Description)
|
||||
flavor.CPU = types.Int64Value(*f.Cpu)
|
||||
flavor.RAM = types.Int64Value(*f.Memory)
|
||||
flavor.NodeType = types.StringValue(*f.NodeType)
|
||||
break
|
||||
}
|
||||
avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM", avl, *f.Cpu, *f.Memory)
|
||||
}
|
||||
if flavor.Id.ValueString() == "" {
|
||||
return fmt.Errorf("couldn't find flavor, available specs are: %s", avl)
|
||||
}
|
||||
|
||||
return nil
|
||||
func toUpdatePayload(model *Model, storage *storageModel, network *networkModel) (*sqlserverflex.UpdateInstanceRequestPayload, error) {
|
||||
return &sqlserverflex.UpdateInstanceRequestPayload{
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Network: nil,
|
||||
Replicas: nil,
|
||||
RetentionDays: nil,
|
||||
Storage: nil,
|
||||
Version: nil,
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
|
||||
sqlserverflexUtils "github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/services/sqlserverflexalpha/utils"
|
||||
|
|
@ -57,7 +56,7 @@ type Model struct {
|
|||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
BackupSchedule types.String `tfsdk:"backup_schedule"`
|
||||
Flavor types.Object `tfsdk:"flavor"`
|
||||
FlavorId types.String `tfsdk:"flavor_id"`
|
||||
Encryption types.Object `tfsdk:"encryption"`
|
||||
IsDeletable types.Bool `tfsdk:"is_deletable"`
|
||||
Storage types.Object `tfsdk:"storage"`
|
||||
|
|
@ -98,24 +97,6 @@ var networkTypes = map[string]attr.Type{
|
|||
"router_address": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// Struct corresponding to Model.FlavorId
|
||||
type flavorModel struct {
|
||||
Id types.String `tfsdk:"id"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
CPU types.Int64 `tfsdk:"cpu"`
|
||||
RAM types.Int64 `tfsdk:"ram"`
|
||||
NodeType types.String `tfsdk:"node_type"`
|
||||
}
|
||||
|
||||
// Types corresponding to flavorModel
|
||||
var flavorTypes = map[string]attr.Type{
|
||||
"id": basetypes.StringType{},
|
||||
"description": basetypes.StringType{},
|
||||
"cpu": basetypes.Int64Type{},
|
||||
"ram": basetypes.Int64Type{},
|
||||
"node_type": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// Struct corresponding to Model.Storage
|
||||
type storageModel struct {
|
||||
Class types.String `tfsdk:"class"`
|
||||
|
|
@ -198,11 +179,13 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
|
|||
"instance_id": "ID of the SQLServer Flex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"access_scope": "The access scope of the instance. (e.g. SNA)",
|
||||
"access_scope": "The access scope of the instance. (SNA | PUBLIC)",
|
||||
"flavor_id": "The flavor ID of the instance.",
|
||||
"acl": "The Access Control List (ACL) for the SQLServer Flex instance.",
|
||||
"backup_schedule": `The backup schedule. Should follow the cron scheduling system format (e.g. "0 0 * * *")`,
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
"encryption": "The encryption block.",
|
||||
"replicas": "The number of replicas of the SQLServer Flex instance.",
|
||||
"network": "The network block.",
|
||||
"keyring_id": "STACKIT KMS - KeyRing ID of the encryption key to use.",
|
||||
"key_id": "STACKIT KMS - Key ID of the encryption key to use.",
|
||||
|
|
@ -271,78 +254,12 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
|
|||
boolplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
// TODO - make it either flavor_id or ram, cpu and node_type
|
||||
"flavor": schema.SingleNestedAttribute{
|
||||
PlanModifiers: []planmodifier.Object{
|
||||
objectplanmodifier.RequiresReplace(),
|
||||
objectplanmodifier.UseStateForUnknown(),
|
||||
"flavor_id": schema.StringAttribute{
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"node_type": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.ConflictsWith([]path.Expression{
|
||||
path.MatchRelative().AtParent().AtName("id"),
|
||||
}...),
|
||||
stringvalidator.OneOfCaseInsensitive(validNodeTypes...),
|
||||
stringvalidator.AlsoRequires([]path.Expression{
|
||||
path.MatchRelative().AtParent().AtName("cpu"),
|
||||
path.MatchRelative().AtParent().AtName("ram"),
|
||||
}...),
|
||||
},
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.RequiresReplace(),
|
||||
int64planmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.Int64{
|
||||
int64validator.ConflictsWith([]path.Expression{
|
||||
path.MatchRelative().AtParent().AtName("id"),
|
||||
}...),
|
||||
int64validator.AlsoRequires([]path.Expression{
|
||||
path.MatchRelative().AtParent().AtName("node_type"),
|
||||
path.MatchRelative().AtParent().AtName("ram"),
|
||||
}...),
|
||||
},
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.RequiresReplace(),
|
||||
int64planmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.Int64{
|
||||
int64validator.ConflictsWith([]path.Expression{
|
||||
path.MatchRelative().AtParent().AtName("id"),
|
||||
}...),
|
||||
int64validator.AlsoRequires([]path.Expression{
|
||||
path.MatchRelative().AtParent().AtName("node_type"),
|
||||
path.MatchRelative().AtParent().AtName("cpu"),
|
||||
}...),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"replicas": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
|
|
@ -506,7 +423,6 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
|
|||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
|
|
@ -548,37 +464,6 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
|
|||
}
|
||||
}
|
||||
|
||||
flavor := &flavorModel{}
|
||||
if !model.Flavor.IsNull() && !model.Flavor.IsUnknown() {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if flavor.Id.IsNull() || flavor.Id.IsUnknown() {
|
||||
err := loadFlavorId(ctx, r.client, &model, flavor, storage)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError(err.Error(), err.Error())
|
||||
return
|
||||
}
|
||||
flavorValues := map[string]attr.Value{
|
||||
"id": flavor.Id,
|
||||
"description": flavor.Description,
|
||||
"cpu": flavor.CPU,
|
||||
"ram": flavor.RAM,
|
||||
"node_type": flavor.NodeType,
|
||||
}
|
||||
var flavorObject basetypes.ObjectValue
|
||||
flavorObject, diags = types.ObjectValue(flavorTypes, flavorValues)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if diags.HasError() {
|
||||
return
|
||||
}
|
||||
model.Flavor = flavorObject
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, storage, encryption, network)
|
||||
if err != nil {
|
||||
|
|
@ -596,6 +481,7 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
|
|||
|
||||
instanceId := *createResp.Id
|
||||
utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
|
||||
"id": utils.BuildInternalTerraformId(projectId, region, instanceId),
|
||||
"instance_id": instanceId,
|
||||
})
|
||||
if resp.Diagnostics.HasError() {
|
||||
|
|
@ -615,25 +501,8 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
|
|||
return
|
||||
}
|
||||
|
||||
if *waitResp.FlavorId != flavor.Id.ValueString() {
|
||||
core.LogAndAddError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
"Error creating instance",
|
||||
fmt.Sprintf("Instance creation waiting: returned flavor id differs (expected: %s, current: %s)", flavor.Id.ValueString(), *waitResp.FlavorId),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if flavor.CPU.IsNull() || flavor.CPU.IsUnknown() {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", "Instance creation waiting: flavor cpu is null or unknown")
|
||||
}
|
||||
if flavor.RAM.IsNull() || flavor.RAM.IsUnknown() {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", "Instance creation waiting: flavor ram is null or unknown")
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, waitResp, &model, flavor, storage, encryption, network, region)
|
||||
err = mapFields(ctx, waitResp, &model, storage, encryption, network, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
|
|
@ -672,27 +541,6 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
|
|||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if !model.Flavor.IsNull() && !model.Flavor.IsUnknown() {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
err := getFlavorModelById(ctx, r.client, &model, flavor)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError(err.Error(), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var storage = &storageModel{}
|
||||
if !model.Storage.IsNull() && !model.Storage.IsUnknown() {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
|
|
@ -734,7 +582,7 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
|
|||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, instanceResp, &model, flavor, storage, encryption, network, region)
|
||||
err = mapFields(ctx, instanceResp, &model, storage, encryption, network, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
|
|
@ -795,37 +643,6 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
|
|||
}
|
||||
}
|
||||
|
||||
flavor := &flavorModel{}
|
||||
if !model.Flavor.IsNull() && !model.Flavor.IsUnknown() {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if flavor.Id.IsNull() || flavor.Id.IsUnknown() {
|
||||
err := loadFlavorId(ctx, r.client, &model, flavor, storage)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError(err.Error(), err.Error())
|
||||
return
|
||||
}
|
||||
flavorValues := map[string]attr.Value{
|
||||
"id": flavor.Id,
|
||||
"description": flavor.Description,
|
||||
"cpu": flavor.CPU,
|
||||
"ram": flavor.RAM,
|
||||
"node_type": flavor.NodeType,
|
||||
}
|
||||
var flavorObject basetypes.ObjectValue
|
||||
flavorObject, diags = types.ObjectValue(flavorTypes, flavorValues)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if diags.HasError() {
|
||||
return
|
||||
}
|
||||
model.Flavor = flavorObject
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, storage, network)
|
||||
if err != nil {
|
||||
|
|
@ -833,7 +650,8 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
|
|||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstancePartiallyRequest(ctx, projectId, region, instanceId).UpdateInstancePartiallyRequestPayload(*payload).Execute()
|
||||
err = r.client.UpdateInstanceRequest(ctx, projectId, region, instanceId).UpdateInstanceRequestPayload(*payload).Execute()
|
||||
// err = r.client.UpdateInstancePartiallyRequest(ctx, projectId, region, instanceId).UpdateInstancePartiallyRequestPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", err.Error())
|
||||
return
|
||||
|
|
@ -848,7 +666,7 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
|
|||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, waitResp, &model, flavor, storage, encryption, network, region)
|
||||
err = mapFields(ctx, waitResp, &model, storage, encryption, network, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
|
|
|
|||
|
|
@ -34,7 +34,6 @@ func TestMapFields(t *testing.T) {
|
|||
description string
|
||||
state Model
|
||||
input *sqlserverflex.GetInstanceResponse
|
||||
flavor *flavorModel
|
||||
storage *storageModel
|
||||
encryption *encryptionModel
|
||||
network *networkModel
|
||||
|
|
@ -53,13 +52,6 @@ func TestMapFields(t *testing.T) {
|
|||
Edition: types.StringValue("edition 1"),
|
||||
Status: types.StringValue("status"),
|
||||
IsDeletable: types.BoolValue(true),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringValue("flavor_id"),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Null(),
|
||||
"ram": types.Int64Null(),
|
||||
"node_type": types.StringNull(),
|
||||
}),
|
||||
},
|
||||
&sqlserverflex.GetInstanceResponse{
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
|
|
@ -70,9 +62,6 @@ func TestMapFields(t *testing.T) {
|
|||
Status: sqlserverflex.GetInstanceResponseGetStatusAttributeType(utils.Ptr("status")),
|
||||
IsDeletable: utils.Ptr(true),
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("flavor_id"),
|
||||
},
|
||||
&storageModel{},
|
||||
&encryptionModel{},
|
||||
&networkModel{
|
||||
|
|
@ -85,14 +74,7 @@ func TestMapFields(t *testing.T) {
|
|||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringNull(),
|
||||
BackupSchedule: types.StringNull(),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringValue("flavor_id"),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Null(),
|
||||
"ram": types.Int64Null(),
|
||||
"node_type": types.StringNull(),
|
||||
}),
|
||||
Replicas: types.Int64Value(1),
|
||||
Replicas: types.Int64Value(1),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringNull(),
|
||||
"size": types.Int64Null(),
|
||||
|
|
@ -151,13 +133,6 @@ func TestMapFields(t *testing.T) {
|
|||
RouterAddress: nil,
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
Id: basetypes.NewStringValue("flavor_id"),
|
||||
Description: basetypes.NewStringValue("description"),
|
||||
CPU: basetypes.NewInt64Value(12),
|
||||
RAM: basetypes.NewInt64Value(34),
|
||||
NodeType: basetypes.NewStringValue("node_type"),
|
||||
},
|
||||
&storageModel{},
|
||||
&encryptionModel{},
|
||||
&networkModel{
|
||||
|
|
@ -174,14 +149,7 @@ func TestMapFields(t *testing.T) {
|
|||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringValue("flavor_id"),
|
||||
"description": types.StringValue("description"),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
"node_type": types.StringValue("node_type"),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
|
|
@ -380,7 +348,7 @@ func TestMapFields(t *testing.T) {
|
|||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
err := mapFields(context.Background(), tt.input, &tt.state, tt.flavor, tt.storage, tt.encryption, tt.network, tt.region)
|
||||
err := mapFields(context.Background(), tt.input, &tt.state, tt.storage, tt.encryption, tt.network, tt.region)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import (
|
|||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/core"
|
||||
"github.com/mhenselin/terraform-provider-stackitprivatepreview/stackit/internal/testutil"
|
||||
core_config "github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
coreconfig "github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex/wait"
|
||||
|
|
@ -28,6 +28,7 @@ var (
|
|||
//go:embed testdata/resource-min.tf
|
||||
resourceMinConfig string
|
||||
)
|
||||
|
||||
var testConfigVarsMin = config.Variables{
|
||||
"project_id": config.StringVariable(testutil.ProjectId),
|
||||
"name": config.StringVariable(fmt.Sprintf("tf-acc-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlphaNum))),
|
||||
|
|
@ -440,7 +441,7 @@ func testAccChecksqlserverflexDestroy(s *terraform.State) error {
|
|||
client, err = sqlserverflex.NewAPIClient()
|
||||
} else {
|
||||
client, err = sqlserverflex.NewAPIClient(
|
||||
core_config.WithEndpoint(testutil.SQLServerFlexCustomEndpoint),
|
||||
coreconfig.WithEndpoint(testutil.SQLServerFlexCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue