feat: region adjustments SQLServerFlex (#707)

* feat: region adjustment sqlserverflex

* adapt acceptance tests

* add region to internal id of sqlserverflex resources to support import of different regions
This commit is contained in:
Marcel Jacek 2025-03-11 08:06:46 +01:00 committed by GitHub
parent 4cfdbc508f
commit 81f876adea
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 360 additions and 105 deletions

View file

@ -10,6 +10,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
@ -31,7 +32,8 @@ func NewInstanceDataSource() datasource.DataSource {
// instanceDataSource is the data source implementation.
type instanceDataSource struct {
client *sqlserverflex.APIClient
client *sqlserverflex.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
@ -46,7 +48,8 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
return
}
providerData, ok := req.ProviderData.(core.ProviderData)
var ok bool
r.providerData, ok = req.ProviderData.(core.ProviderData)
if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return
@ -54,15 +57,15 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
var apiClient *sqlserverflex.APIClient
var err error
if providerData.SQLServerFlexCustomEndpoint != "" {
if r.providerData.SQLServerFlexCustomEndpoint != "" {
apiClient, err = sqlserverflex.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithEndpoint(providerData.SQLServerFlexCustomEndpoint),
config.WithCustomAuth(r.providerData.RoundTripper),
config.WithEndpoint(r.providerData.SQLServerFlexCustomEndpoint),
)
} else {
apiClient, err = sqlserverflex.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithRegion(providerData.Region),
config.WithCustomAuth(r.providerData.RoundTripper),
config.WithRegion(r.providerData.Region),
)
}
@ -79,13 +82,14 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{
"main": "SQLServer Flex instance data source schema. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`instance_id`\".",
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`region`,`instance_id`\".",
"instance_id": "ID of the SQLServer Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"name": "Instance name.",
"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 * * *").`,
"options": "Custom parameters for the SQLServer Flex instance.",
"region": "The resource region. If not defined, the provider region is used.",
}
resp.Schema = schema.Schema{
@ -170,6 +174,11 @@ func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaReques
},
},
},
"region": schema.StringAttribute{
// the region cannot be found, so it has to be passed
Optional: true,
Description: descriptions["region"],
},
},
}
}
@ -185,9 +194,16 @@ func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadReques
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
var region string
if utils.IsUndefined(model.Region) {
region = r.providerData.Region
} else {
region = model.Region.ValueString()
}
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
ctx = tflog.SetField(ctx, "region", region)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId, region).Execute()
if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound {
@ -222,7 +238,7 @@ func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadReques
}
}
err = mapFields(ctx, instanceResp, &model, flavor, storage, options)
err = mapFields(ctx, instanceResp, &model, flavor, storage, options, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return

View file

@ -41,6 +41,7 @@ var (
_ resource.Resource = &instanceResource{}
_ resource.ResourceWithConfigure = &instanceResource{}
_ resource.ResourceWithImportState = &instanceResource{}
_ resource.ResourceWithModifyPlan = &instanceResource{}
)
type Model struct {
@ -55,6 +56,7 @@ type Model struct {
Version types.String `tfsdk:"version"`
Replicas types.Int64 `tfsdk:"replicas"`
Options types.Object `tfsdk:"options"`
Region types.String `tfsdk:"region"`
}
// Struct corresponding to Model.Flavor
@ -104,7 +106,8 @@ func NewInstanceResource() resource.Resource {
// instanceResource is the resource implementation.
type instanceResource struct {
client *sqlserverflex.APIClient
client *sqlserverflex.APIClient
providerData core.ProviderData
}
// Metadata returns the resource type name.
@ -119,7 +122,8 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
return
}
providerData, ok := req.ProviderData.(core.ProviderData)
var ok bool
r.providerData, ok = req.ProviderData.(core.ProviderData)
if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return
@ -127,15 +131,15 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
var apiClient *sqlserverflex.APIClient
var err error
if providerData.SQLServerFlexCustomEndpoint != "" {
if r.providerData.SQLServerFlexCustomEndpoint != "" {
apiClient, err = sqlserverflex.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithEndpoint(providerData.SQLServerFlexCustomEndpoint),
config.WithCustomAuth(r.providerData.RoundTripper),
config.WithEndpoint(r.providerData.SQLServerFlexCustomEndpoint),
)
} else {
apiClient, err = sqlserverflex.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithRegion(providerData.Region),
config.WithCustomAuth(r.providerData.RoundTripper),
config.WithRegion(r.providerData.Region),
)
}
@ -148,17 +152,48 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
tflog.Info(ctx, "SQLServer Flex instance client configured")
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *instanceResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
}
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.Region, resp)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
if resp.Diagnostics.HasError() {
return
}
}
// Schema defines the schema for the resource.
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{
"main": "SQLServer Flex instance resource schema. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`instance_id`\".",
"instance_id": "ID of the SQLServer Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"name": "Instance name.",
"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 * * *")`,
"options": "Custom parameters for the SQLServer Flex instance.",
"region": "The resource region. If not defined, the provider region is used.",
}
resp.Schema = schema.Schema{
@ -308,6 +343,15 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
},
},
},
"region": schema.StringAttribute{
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
Description: descriptions["region"],
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
}
}
@ -322,7 +366,9 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
return
}
projectId := model.ProjectId.ValueString()
region := model.Region.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
var acl []string
if !(model.ACL.IsNull() || model.ACL.IsUnknown()) {
@ -370,7 +416,7 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
return
}
// Create new instance
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
createResp, err := r.client.CreateInstance(ctx, projectId, region).CreateInstancePayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
return
@ -379,14 +425,14 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
ctx = tflog.SetField(ctx, "instance_id", instanceId)
// The creation waiter sometimes returns an error from the API: "instance with id xxx has unexpected status Failure"
// which can be avoided by sleeping before wait
waitResp, err := wait.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetSleepBeforeWait(30 * time.Second).WaitWithContext(ctx)
waitResp, err := wait.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId, region).SetSleepBeforeWait(30 * time.Second).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
return
}
// Map response body to schema
err = mapFields(ctx, waitResp, &model, flavor, storage, options)
err = mapFields(ctx, waitResp, &model, flavor, storage, options, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
return
@ -415,8 +461,14 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
}
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
region := model.Region.ValueString()
if region == "" {
region = r.providerData.Region
}
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "region", region)
var flavor = &flavorModel{}
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
@ -444,7 +496,7 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
}
}
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId, region).Execute()
if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound {
@ -456,7 +508,7 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
}
// Map response body to schema
err = mapFields(ctx, instanceResp, &model, flavor, storage, options)
err = mapFields(ctx, instanceResp, &model, flavor, storage, options, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return
@ -481,8 +533,11 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
}
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
region := model.Region.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "region", region)
var acl []string
if !(model.ACL.IsNull() || model.ACL.IsUnknown()) {
@ -530,19 +585,19 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
return
}
// Update existing instance
_, err = r.client.PartialUpdateInstance(ctx, projectId, instanceId).PartialUpdateInstancePayload(*payload).Execute()
_, err = r.client.PartialUpdateInstance(ctx, projectId, instanceId, region).PartialUpdateInstancePayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", err.Error())
return
}
waitResp, err := wait.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).WaitWithContext(ctx)
waitResp, err := wait.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId, region).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
return
}
// Map response body to schema
err = mapFields(ctx, waitResp, &model, flavor, storage, options)
err = mapFields(ctx, waitResp, &model, flavor, storage, options, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
return
@ -566,16 +621,18 @@ func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteReques
}
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
region := model.Region.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "region", region)
// Delete existing instance
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
err := r.client.DeleteInstance(ctx, projectId, instanceId, region).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
return
}
_, err = wait.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).WaitWithContext(ctx)
_, err = wait.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId, region).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
return
@ -588,20 +645,21 @@ func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteReques
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing instance",
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
fmt.Sprintf("Expected import identifier with format: [project_id],[region],[instance_id] Got: %q", req.ID),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
tflog.Info(ctx, "SQLServer Flex instance state imported")
}
func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, model *Model, flavor *flavorModel, storage *storageModel, options *optionsModel) error {
func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, model *Model, flavor *flavorModel, storage *storageModel, options *optionsModel, region string) error {
if resp == nil {
return fmt.Errorf("response input is nil")
}
@ -721,6 +779,7 @@ func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, mod
idParts := []string{
model.ProjectId.ValueString(),
region,
instanceId,
}
model.Id = types.StringValue(
@ -734,6 +793,7 @@ func mapFields(ctx context.Context, resp *sqlserverflex.GetInstanceResponse, mod
model.Storage = storageObject
model.Version = types.StringPointerValue(instance.Version)
model.Options = optionsObject
model.Region = types.StringValue(region)
return nil
}
@ -797,7 +857,7 @@ func toUpdatePayload(model *Model, acl []string, flavor *flavorModel) (*sqlserve
}
type sqlserverflexClient interface {
ListFlavorsExecute(ctx context.Context, projectId string) (*sqlserverflex.ListFlavorsResponse, error)
ListFlavorsExecute(ctx context.Context, projectId, region string) (*sqlserverflex.ListFlavorsResponse, error)
}
func loadFlavorId(ctx context.Context, client sqlserverflexClient, model *Model, flavor *flavorModel) error {
@ -817,7 +877,8 @@ func loadFlavorId(ctx context.Context, client sqlserverflexClient, model *Model,
}
projectId := model.ProjectId.ValueString()
res, err := client.ListFlavorsExecute(ctx, projectId)
region := model.Region.ValueString()
res, err := client.ListFlavorsExecute(ctx, projectId, region)
if err != nil {
return fmt.Errorf("listing sqlserverflex flavors: %w", err)
}

View file

@ -17,7 +17,7 @@ type sqlserverflexClientMocked struct {
listFlavorsResp *sqlserverflex.ListFlavorsResponse
}
func (c *sqlserverflexClientMocked) ListFlavorsExecute(_ context.Context, _ string) (*sqlserverflex.ListFlavorsResponse, error) {
func (c *sqlserverflexClientMocked) ListFlavorsExecute(_ context.Context, _, _ string) (*sqlserverflex.ListFlavorsResponse, error) {
if c.returnError {
return nil, fmt.Errorf("get flavors failed")
}
@ -26,6 +26,7 @@ func (c *sqlserverflexClientMocked) ListFlavorsExecute(_ context.Context, _ stri
}
func TestMapFields(t *testing.T) {
const testRegion = "region"
tests := []struct {
description string
state Model
@ -33,6 +34,7 @@ func TestMapFields(t *testing.T) {
flavor *flavorModel
storage *storageModel
options *optionsModel
region string
expected Model
isValid bool
}{
@ -48,8 +50,9 @@ func TestMapFields(t *testing.T) {
&flavorModel{},
&storageModel{},
&optionsModel{},
testRegion,
Model{
Id: types.StringValue("pid,iid"),
Id: types.StringValue("pid,region,iid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringNull(),
@ -71,6 +74,7 @@ func TestMapFields(t *testing.T) {
"retention_days": types.Int64Null(),
}),
Version: types.StringNull(),
Region: types.StringValue(testRegion),
},
true,
},
@ -114,8 +118,9 @@ func TestMapFields(t *testing.T) {
&flavorModel{},
&storageModel{},
&optionsModel{},
testRegion,
Model{
Id: types.StringValue("pid,iid"),
Id: types.StringValue("pid,region,iid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringValue("name"),
@ -141,6 +146,7 @@ func TestMapFields(t *testing.T) {
"retention_days": types.Int64Value(1),
}),
Version: types.StringValue("version"),
Region: types.StringValue(testRegion),
},
true,
},
@ -185,8 +191,9 @@ func TestMapFields(t *testing.T) {
Edition: types.StringValue("edition"),
RetentionDays: types.Int64Value(1),
},
testRegion,
Model{
Id: types.StringValue("pid,iid"),
Id: types.StringValue("pid,region,iid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringValue("name"),
@ -212,6 +219,7 @@ func TestMapFields(t *testing.T) {
"retention_days": types.Int64Value(1),
}),
Version: types.StringValue("version"),
Region: types.StringValue(testRegion),
},
true,
},
@ -258,8 +266,9 @@ func TestMapFields(t *testing.T) {
Size: types.Int64Value(78),
},
&optionsModel{},
testRegion,
Model{
Id: types.StringValue("pid,iid"),
Id: types.StringValue("pid,region,iid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Name: types.StringValue("name"),
@ -285,6 +294,7 @@ func TestMapFields(t *testing.T) {
"retention_days": types.Int64Value(1),
}),
Version: types.StringValue("version"),
Region: types.StringValue(testRegion),
},
true,
},
@ -298,6 +308,7 @@ func TestMapFields(t *testing.T) {
&flavorModel{},
&storageModel{},
&optionsModel{},
testRegion,
Model{},
false,
},
@ -311,13 +322,14 @@ func TestMapFields(t *testing.T) {
&flavorModel{},
&storageModel{},
&optionsModel{},
testRegion,
Model{},
false,
},
}
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.options)
err := mapFields(context.Background(), tt.input, &tt.state, tt.flavor, tt.storage, tt.options, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}