Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions stackit/internal/services/sqlserverflex/instance/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
Expand Down Expand Up @@ -407,8 +406,21 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques

ctx = core.LogResponse(ctx)

if createResp.Id == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", "Got empty instance id")
return
}

instanceId := *createResp.Id
ctx = tflog.SetField(ctx, "instance_id", instanceId)
// Write id attributes to state before polling via the wait handler - just in case anything goes wrong during the wait handler
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": projectId,
"region": region,
"instance_id": instanceId,
})
if resp.Diagnostics.HasError() {
return
}
// 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, region).SetSleepBeforeWait(30 * time.Second).WaitWithContext(ctx)
Expand Down Expand Up @@ -653,9 +665,11 @@ func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportS
return
}

resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
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])...)
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": idParts[0],
"region": idParts[1],
"instance_id": idParts[2],
})
tflog.Info(ctx, "SQLServer Flex instance state imported")
}

Expand Down
102 changes: 102 additions & 0 deletions stackit/internal/services/sqlserverflex/sqlserverflex_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package sqlserverflex

import (
"fmt"
"net/http"
"regexp"
"testing"

"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
)

func TestSQLServerFlexInstanceSavesIDsOnError(t *testing.T) {
projectId := uuid.NewString()
instanceId := uuid.NewString()
const (
name = "instance-name"
flavorCpu = 4
flavorRam = 16
flavorId = "4.16-Single"
region = "eu01"
)
s := testutil.NewMockServer(t)
defer s.Server.Close()
tfConfig := fmt.Sprintf(`
provider "stackit" {
default_region = "%s"
sqlserverflex_custom_endpoint = "%s"
service_account_token = "mock-server-needs-no-auth"
}

resource "stackit_sqlserverflex_instance" "instance" {
project_id = "%s"
name = "%s"
flavor = {
cpu = %d
ram = %d
}
}

`, region, s.Server.URL, projectId, name, flavorCpu, flavorRam)
flavor := testutil.MockResponse{
ToJsonBody: &sqlserverflex.ListFlavorsResponse{
Flavors: &[]sqlserverflex.InstanceFlavorEntry{
{
Cpu: utils.Ptr(int64(flavorCpu)),
Memory: utils.Ptr(int64(flavorRam)),
Id: utils.Ptr(flavorId),
Description: utils.Ptr("test-flavor-id"),
},
},
},
}

resource.UnitTest(t, resource.TestCase{
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
PreConfig: func() {
s.Reset(
flavor,
testutil.MockResponse{
Description: "create",
ToJsonBody: sqlserverflex.CreateInstanceResponse{
Id: utils.Ptr(instanceId),
},
},
testutil.MockResponse{
Description: "failing waiter",
StatusCode: http.StatusInternalServerError,
},
)
},
Config: tfConfig,
ExpectError: regexp.MustCompile("Error creating instance.*"),
},
{
PreConfig: func() {
s.Reset(
testutil.MockResponse{
Description: "refresh",
Handler: func(w http.ResponseWriter, req *http.Request) {
expected := fmt.Sprintf("/v2/projects/%s/regions/%s/instances/%s", projectId, region, instanceId)
if req.URL.Path != expected {
t.Errorf("expected request to %s, got %s", expected, req.URL.Path)
}
w.WriteHeader(http.StatusInternalServerError)
},
},
testutil.MockResponse{Description: "delete", StatusCode: http.StatusAccepted},
testutil.MockResponse{Description: "delete waiter", StatusCode: http.StatusNotFound},
)
},
RefreshState: true,
ExpectError: regexp.MustCompile("Error reading instance*"),
},
},
})
}
19 changes: 12 additions & 7 deletions stackit/internal/services/sqlserverflex/user/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"

"github.com/hashicorp/terraform-plugin-framework/attr"
"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/resource/schema/planmodifier"
Expand Down Expand Up @@ -255,8 +254,12 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
return
}
userId := *userResp.Item.Id
ctx = tflog.SetField(ctx, "user_id", userId)

ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": projectId,
"region": region,
"instance_id": instanceId,
"user_id": userId,
})
// Map response body to schema
err = mapFieldsCreate(userResp, &model, region)
if err != nil {
Expand Down Expand Up @@ -372,10 +375,12 @@ func (r *userResource) ImportState(ctx context.Context, req resource.ImportState
return
}

resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
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])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), idParts[3])...)
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": idParts[0],
"region": idParts[1],
"instance_id": idParts[2],
"user_id": idParts[3],
})
core.LogAndAddWarning(ctx, &resp.Diagnostics,
"SQLServer Flex user imported with empty password",
"The user password is not imported as it is only available upon creation of a new user. The password field will be empty.",
Expand Down
Loading