feat: mssql alpha instance (#2)

* fix: remove unused attribute types and functions from backup models

* fix: update API client references to use sqlserverflexalpha package

* fix: update package references to use sqlserverflexalpha and modify user data source model

* fix: add sqlserverflexalpha user data source to provider

* fix: add sqlserverflexalpha user resource and update related functionality

* chore: add stackit_sqlserverflexalpha_user resource and instance_id variable

* fix: refactor sqlserverflexalpha user resource and enhance schema with status and default_database

---------

Co-authored-by: Andre Harms <andre.harms@stackit.cloud>
Co-authored-by: Marcel S. Henselin <marcel.henselin@stackit.cloud>
This commit is contained in:
Marcel S. Henselin 2025-12-19 08:56:46 +01:00 committed by GitHub
parent df25ceffd4
commit 5381516661
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
385 changed files with 1431 additions and 14841 deletions

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package conversion
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package conversion
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package core
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package core
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package features
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package features
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package features
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package features
import (

View file

@ -1,114 +0,0 @@
package authorization_test
import (
"context"
"errors"
"fmt"
"regexp"
"slices"
"testing"
_ "embed"
"github.com/hashicorp/terraform-plugin-testing/config"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
stackitSdkConfig "github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/authorization"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
)
//go:embed testfiles/prerequisites.tf
var prerequisites string
//go:embed testfiles/double-definition.tf
var doubleDefinition string
//go:embed testfiles/project-owner.tf
var projectOwner string
//go:embed testfiles/invalid-role.tf
var invalidRole string
//go:embed testfiles/organization-role.tf
var organizationRole string
var testConfigVars = config.Variables{
"project_id": config.StringVariable(testutil.ProjectId),
"test_service_account": config.StringVariable(testutil.TestProjectServiceAccountEmail),
"organization_id": config.StringVariable(testutil.OrganizationId),
}
func TestAccProjectRoleAssignmentResource(t *testing.T) {
t.Log(testutil.AuthorizationProviderConfig())
resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
ConfigVariables: testConfigVars,
Config: testutil.AuthorizationProviderConfig() + prerequisites,
Check: func(_ *terraform.State) error {
client, err := authApiClient()
if err != nil {
return err
}
members, err := client.ListMembers(context.TODO(), "project", testutil.ProjectId).Execute()
if err != nil {
return err
}
if !slices.ContainsFunc(*members.Members, func(m authorization.Member) bool {
return *m.Role == "reader" && *m.Subject == testutil.TestProjectServiceAccountEmail
}) {
t.Log(members.Members)
return errors.New("Membership not found")
}
return nil
},
},
{
// Assign a resource to an organization
ConfigVariables: testConfigVars,
Config: testutil.AuthorizationProviderConfig() + prerequisites + organizationRole,
},
{
// The Service Account inherits owner permissions for the project from the organization. Check if you can still assign owner permissions on the project explicitly
ConfigVariables: testConfigVars,
Config: testutil.AuthorizationProviderConfig() + prerequisites + organizationRole + projectOwner,
},
{
// Expect failure on creating an already existing role_assignment
// Would be bad, since two resources could be created and deletion of one would lead to state drift for the second TF resource
ConfigVariables: testConfigVars,
Config: testutil.AuthorizationProviderConfig() + prerequisites + doubleDefinition,
ExpectError: regexp.MustCompile(".+"),
},
{
// Assign a non-existent role. Expect failure
ConfigVariables: testConfigVars,
Config: testutil.AuthorizationProviderConfig() + prerequisites + invalidRole,
ExpectError: regexp.MustCompile(".+"),
},
},
})
}
func authApiClient() (*authorization.APIClient, error) {
var client *authorization.APIClient
var err error
if testutil.AuthorizationCustomEndpoint == "" {
client, err = authorization.NewAPIClient(
stackitSdkConfig.WithRegion("eu01"),
)
} else {
client, err = authorization.NewAPIClient(
stackitSdkConfig.WithEndpoint(testutil.AuthorizationCustomEndpoint),
)
}
if err != nil {
return nil, fmt.Errorf("creating client: %w", err)
}
return client, nil
}

View file

@ -1,370 +0,0 @@
package roleassignments
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
authorizationUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/authorization/utils"
"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"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/authorization"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
// List of permission assignments targets in form [TF resource name]:[api name]
var roleTargets = []string{
"project",
"organization",
}
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &roleAssignmentResource{}
_ resource.ResourceWithConfigure = &roleAssignmentResource{}
_ resource.ResourceWithImportState = &roleAssignmentResource{}
errRoleAssignmentNotFound = errors.New("response members did not contain expected role assignment")
errRoleAssignmentDuplicateFound = errors.New("found a duplicate role assignment.")
)
// Provider's internal model
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ResourceId types.String `tfsdk:"resource_id"`
Role types.String `tfsdk:"role"`
Subject types.String `tfsdk:"subject"`
}
// NewProjectRoleAssignmentResource is a helper function to simplify the provider implementation.
func NewRoleAssignmentResources() []func() resource.Resource {
resources := make([]func() resource.Resource, 0)
for _, v := range roleTargets {
resources = append(resources, func() resource.Resource {
return &roleAssignmentResource{
apiName: v,
}
})
}
return resources
}
// roleAssignmentResource is the resource implementation.
type roleAssignmentResource struct {
authorizationClient *authorization.APIClient
apiName string
}
// Metadata returns the resource type name.
func (r *roleAssignmentResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = fmt.Sprintf("%s_authorization_%s_role_assignment", req.ProviderTypeName, r.apiName)
}
// Configure adds the provider configured client to the resource.
func (r *roleAssignmentResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
features.CheckExperimentEnabled(ctx, &providerData, features.IamExperiment, fmt.Sprintf("stackit_authorization_%s_role_assignment", r.apiName), core.Resource, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
apiClient := authorizationUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.authorizationClient = apiClient
tflog.Info(ctx, fmt.Sprintf("Resource Manager %s Role Assignment client configured", r.apiName))
}
// Schema defines the schema for the resource.
func (r *roleAssignmentResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{
"main": features.AddExperimentDescription(fmt.Sprintf("%s Role Assignment resource schema.", r.apiName), features.IamExperiment, core.Resource),
"id": "Terraform's internal resource identifier. It is structured as \"[resource_id],[role],[subject]\".",
"resource_id": fmt.Sprintf("%s Resource to assign the role to.", r.apiName),
"role": "Role to be assigned",
"subject": "Identifier of user, service account or client. Usually email address or name in case of clients",
}
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"resource_id": schema.StringAttribute{
Description: descriptions["resource_id"],
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"role": schema.StringAttribute{
Description: descriptions["role"],
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"subject": schema.StringAttribute{
Description: descriptions["subject"],
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *roleAssignmentResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
ctx = r.annotateLogger(ctx, &model)
if err := r.checkDuplicate(ctx, model); err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error while checking for duplicate role assignments", err.Error())
return
}
// Create new project role assignment
payload, err := r.toCreatePayload(&model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credential", fmt.Sprintf("Creating API payload: %v", err))
return
}
createResp, err := r.authorizationClient.AddMembers(ctx, model.ResourceId.ValueString()).AddMembersPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, fmt.Sprintf("Error creating %s role assignment", r.apiName), fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
// Map response body to schema
err = mapMembersResponse(createResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, fmt.Sprintf("Error creating %s role assignment", r.apiName), fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, fmt.Sprintf("%s role assignment created", r.apiName))
}
// Read refreshes the Terraform state with the latest data.
func (r *roleAssignmentResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
ctx = r.annotateLogger(ctx, &model)
listResp, err := r.authorizationClient.ListMembers(ctx, r.apiName, model.ResourceId.ValueString()).Subject(model.Subject.ValueString()).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading authorizations", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
// Map response body to schema
err = mapListMembersResponse(listResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading authorization", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, fmt.Sprintf("%s role assignment read successful", r.apiName))
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *roleAssignmentResource) Update(_ context.Context, _ resource.UpdateRequest, _ *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// does nothing since resource updates should always trigger resource replacement
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *roleAssignmentResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
ctx = r.annotateLogger(ctx, &model)
payload := authorization.RemoveMembersPayload{
ResourceType: &r.apiName,
Members: &[]authorization.Member{
*authorization.NewMember(model.Role.ValueString(), model.Subject.ValueString()),
},
}
// Delete existing project role assignment
_, err := r.authorizationClient.RemoveMembers(ctx, model.ResourceId.ValueString()).RemoveMembersPayload(payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, fmt.Sprintf("Error deleting %s role assignment", r.apiName), fmt.Sprintf("Calling API: %v", err))
}
ctx = core.LogResponse(ctx)
tflog.Info(ctx, fmt.Sprintf("%s role assignment deleted", r.apiName))
}
// ImportState imports a resource into the Terraform state on success.
// The expected format of the project role assignment resource import identifier is: resource_id,role,subject
func (r *roleAssignmentResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
fmt.Sprintf("Error importing %s role assignment", r.apiName),
fmt.Sprintf("Expected import identifier with format [resource_id],[role],[subject], got %q", req.ID),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("resource_id"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("role"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("subject"), idParts[2])...)
tflog.Info(ctx, fmt.Sprintf("%s role assignment state imported", r.apiName))
}
// Maps project role assignment fields to the provider's internal model.
func mapListMembersResponse(resp *authorization.ListMembersResponse, model *Model) error {
if resp == nil {
return fmt.Errorf("response input is nil")
}
if resp.Members == nil {
return fmt.Errorf("response members are nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
model.Id = utils.BuildInternalTerraformId(model.ResourceId.ValueString(), model.Role.ValueString(), model.Subject.ValueString())
model.ResourceId = types.StringPointerValue(resp.ResourceId)
for _, m := range *resp.Members {
if *m.Role == model.Role.ValueString() && *m.Subject == model.Subject.ValueString() {
model.Role = types.StringPointerValue(m.Role)
model.Subject = types.StringPointerValue(m.Subject)
return nil
}
}
return errRoleAssignmentNotFound
}
func mapMembersResponse(resp *authorization.MembersResponse, model *Model) error {
listMembersResponse, err := typeConverter[authorization.ListMembersResponse](resp)
if err != nil {
return err
}
return mapListMembersResponse(listMembersResponse, model)
}
// Helper to convert objects with equal JSON tags
func typeConverter[R any](data any) (*R, error) {
var result R
b, err := json.Marshal(&data)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &result)
if err != nil {
return nil, err
}
return &result, err
}
// Build Createproject role assignmentPayload from provider's model
func (r *roleAssignmentResource) toCreatePayload(model *Model) (*authorization.AddMembersPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
return &authorization.AddMembersPayload{
ResourceType: &r.apiName,
Members: &[]authorization.Member{
*authorization.NewMember(model.Role.ValueString(), model.Subject.ValueString()),
},
}, nil
}
func (r *roleAssignmentResource) annotateLogger(ctx context.Context, model *Model) context.Context {
resourceId := model.ResourceId.ValueString()
ctx = tflog.SetField(ctx, "resource_id", resourceId)
ctx = tflog.SetField(ctx, "subject", model.Subject.ValueString())
ctx = tflog.SetField(ctx, "role", model.Role.ValueString())
ctx = tflog.SetField(ctx, "resource_type", r.apiName)
return ctx
}
// returns an error if duplicate role assignment exists
func (r *roleAssignmentResource) checkDuplicate(ctx context.Context, model Model) error { //nolint:gocritic // A read only copy is required since an api response is parsed into the model and this check should not affect the model parameter
listResp, err := r.authorizationClient.ListMembers(ctx, r.apiName, model.ResourceId.ValueString()).Subject(model.Subject.ValueString()).Execute()
if err != nil {
return err
}
// Map response body to schema
err = mapListMembersResponse(listResp, &model)
if err != nil {
if errors.Is(err, errRoleAssignmentNotFound) {
return nil
}
return err
}
return errRoleAssignmentDuplicateFound
}

View file

@ -1,6 +0,0 @@
resource "stackit_authorization_project_role_assignment" "serviceaccount_duplicate" {
resource_id = var.project_id
role = "reader"
subject = var.test_service_account
}

View file

@ -1,6 +0,0 @@
resource "stackit_authorization_project_role_assignment" "invalid_role" {
resource_id = var.project_id
role = "thisrolesdoesnotexist"
subject = var.test_service_account
}

View file

@ -1,6 +0,0 @@
resource "stackit_authorization_organization_role_assignment" "serviceaccount" {
resource_id = var.organization_id
role = "organization.member"
subject = var.test_service_account
}

View file

@ -1,10 +0,0 @@
variable "project_id" {}
variable "test_service_account" {}
variable "organization_id" {}
resource "stackit_authorization_project_role_assignment" "serviceaccount" {
resource_id = var.project_id
role = "reader"
subject = var.test_service_account
}

View file

@ -1,6 +0,0 @@
resource "stackit_authorization_project_role_assignment" "serviceaccount_project_owner" {
resource_id = var.project_id
role = "owner"
subject = var.test_service_account
}

View file

@ -1,29 +0,0 @@
package utils
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/authorization"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
)
func ConfigureClient(ctx context.Context, providerData *core.ProviderData, diags *diag.Diagnostics) *authorization.APIClient {
apiClientConfigOptions := []config.ConfigurationOption{
config.WithCustomAuth(providerData.RoundTripper),
utils.UserAgentConfigOption(providerData.Version),
}
if providerData.AuthorizationCustomEndpoint != "" {
apiClientConfigOptions = append(apiClientConfigOptions, config.WithEndpoint(providerData.AuthorizationCustomEndpoint))
}
apiClient, err := authorization.NewAPIClient(apiClientConfigOptions...)
if err != nil {
core.LogAndAddError(ctx, diags, "Error configuring API client", fmt.Sprintf("Configuring client: %v. This is an error related to the provider configuration, not to the resource configuration", err))
return nil
}
return apiClient
}

View file

@ -1,93 +0,0 @@
package utils
import (
"context"
"os"
"reflect"
"testing"
"github.com/hashicorp/terraform-plugin-framework/diag"
sdkClients "github.com/stackitcloud/stackit-sdk-go/core/clients"
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/authorization"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
)
const (
testVersion = "1.2.3"
testCustomEndpoint = "https://authorization-custom-endpoint.api.stackit.cloud"
)
func TestConfigureClient(t *testing.T) {
/* mock authentication by setting service account token env variable */
os.Clearenv()
err := os.Setenv(sdkClients.ServiceAccountToken, "mock-val")
if err != nil {
t.Errorf("error setting env variable: %v", err)
}
type args struct {
providerData *core.ProviderData
}
tests := []struct {
name string
args args
wantErr bool
expected *authorization.APIClient
}{
{
name: "default endpoint",
args: args{
providerData: &core.ProviderData{
Version: testVersion,
},
},
expected: func() *authorization.APIClient {
apiClient, err := authorization.NewAPIClient(
utils.UserAgentConfigOption(testVersion),
)
if err != nil {
t.Errorf("error configuring client: %v", err)
}
return apiClient
}(),
wantErr: false,
},
{
name: "custom endpoint",
args: args{
providerData: &core.ProviderData{
Version: testVersion,
AuthorizationCustomEndpoint: testCustomEndpoint,
},
},
expected: func() *authorization.APIClient {
apiClient, err := authorization.NewAPIClient(
utils.UserAgentConfigOption(testVersion),
config.WithEndpoint(testCustomEndpoint),
)
if err != nil {
t.Errorf("error configuring client: %v", err)
}
return apiClient
}(),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
diags := diag.Diagnostics{}
actual := ConfigureClient(ctx, tt.args.providerData, &diags)
if diags.HasError() != tt.wantErr {
t.Errorf("ConfigureClient() error = %v, want %v", diags.HasError(), tt.wantErr)
}
if !reflect.DeepEqual(actual, tt.expected) {
t.Errorf("ConfigureClient() = %v, want %v", actual, tt.expected)
}
})
}
}

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflexa
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflexa
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflexa
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflex_test
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflexa
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflexa
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflexa
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package postgresflexa
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package sqlserverflex
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package sqlserverflex
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package sqlserverflex
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package sqlserverflex_test
import (

View file

@ -1,3 +1,5 @@
# Copyright (c) STACKIT
variable "project_id" {}
variable "name" {}
variable "acl1" {}

View file

@ -1,3 +1,5 @@
# Copyright (c) STACKIT
variable "project_id" {}
variable "name" {}
variable "flavor_cpu" {}

View file

@ -1,14 +1,19 @@
package sqlserverflex
// Copyright (c) STACKIT
package sqlserverflexalpha
import (
"context"
"fmt"
"net/http"
"strconv"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
sqlserverflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/sqlserverflex/utils"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/stackitcloud/terraform-provider-stackit/pkg/sqlserverflexalpha"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
sqlserverflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/sqlserverflexalpha/utils"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-log/tflog"
@ -18,7 +23,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
)
// Ensure the implementation satisfies the expected interfaces.
@ -27,15 +31,17 @@ var (
)
type DataSourceModel struct {
Id types.String `tfsdk:"id"` // needed by TF
UserId types.String `tfsdk:"user_id"`
InstanceId types.String `tfsdk:"instance_id"`
ProjectId types.String `tfsdk:"project_id"`
Username types.String `tfsdk:"username"`
Roles types.Set `tfsdk:"roles"`
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Region types.String `tfsdk:"region"`
Id types.String `tfsdk:"id"` // needed by TF
UserId types.Int64 `tfsdk:"user_id"`
InstanceId types.String `tfsdk:"instance_id"`
ProjectId types.String `tfsdk:"project_id"`
Username types.String `tfsdk:"username"`
Roles types.Set `tfsdk:"roles"`
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Region types.String `tfsdk:"region"`
Status types.String `tfsdk:"status"`
DefaultDatabase types.String `tfsdk:"default_database"`
}
// NewUserDataSource is a helper function to simplify the provider implementation.
@ -45,17 +51,25 @@ func NewUserDataSource() datasource.DataSource {
// userDataSource is the data source implementation.
type userDataSource struct {
client *sqlserverflex.APIClient
client *sqlserverflexalpha.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
func (r *userDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_sqlserverflex_user"
func (r *userDataSource) Metadata(
_ context.Context,
req datasource.MetadataRequest,
resp *datasource.MetadataResponse,
) {
resp.TypeName = req.ProviderTypeName + "_sqlserverflexalpha_user"
}
// Configure adds the provider configured client to the data source.
func (r *userDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
func (r *userDataSource) 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 {
@ -73,15 +87,17 @@ func (r *userDataSource) Configure(ctx context.Context, req datasource.Configure
// Schema defines the schema for the data source.
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{
"main": "SQLServer Flex user 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`,`region`,`instance_id`,`user_id`\".",
"user_id": "User ID.",
"instance_id": "ID of the SQLServer Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"username": "Username of the SQLServer Flex instance.",
"roles": "Database access levels for the user.",
"password": "Password of the user account.",
"region": "The resource region. If not defined, the provider region is used.",
"main": "SQLServer Flex user 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`,`region`,`instance_id`,`user_id`\".",
"user_id": "User ID.",
"instance_id": "ID of the SQLServer Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"username": "Username of the SQLServer Flex instance.",
"roles": "Database access levels for the user.",
"password": "Password of the user account.",
"region": "The resource region. If not defined, the provider region is used.",
"status": "Status of the user.",
"default_database": "Default database of the user.",
}
resp.Schema = schema.Schema{
@ -91,11 +107,11 @@ func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, r
Description: descriptions["id"],
Computed: true,
},
"user_id": schema.StringAttribute{
"user_id": schema.Int64Attribute{
Description: descriptions["user_id"],
Required: true,
Validators: []validator.String{
validate.NoSeparator(),
Validators: []validator.Int64{
int64validator.AtLeast(1),
},
},
"instance_id": schema.StringAttribute{
@ -134,12 +150,22 @@ func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, r
Optional: true,
Description: descriptions["region"],
},
"status": schema.StringAttribute{
Computed: true,
},
"default_database": schema.StringAttribute{
Computed: true,
},
},
}
}
// Read refreshes the Terraform state with the latest data.
func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
func (r *userDataSource) Read(
ctx context.Context,
req datasource.ReadRequest,
resp *datasource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
var model DataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -151,21 +177,26 @@ func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueString()
userId := model.UserId.ValueInt64()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "user_id", userId)
ctx = tflog.SetField(ctx, "region", region)
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId, region).Execute()
recordSetResp, err := r.client.GetUserRequest(ctx, projectId, region, instanceId, userId).Execute()
if err != nil {
utils.LogError(
ctx,
&resp.Diagnostics,
err,
"Reading user",
fmt.Sprintf("User with ID %q or instance with ID %q does not exist in project %q.", userId, instanceId, projectId),
fmt.Sprintf(
"User with ID %q or instance with ID %q does not exist in project %q.",
userId,
instanceId,
projectId,
),
map[int]string{
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
},
@ -179,7 +210,12 @@ func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
// Map response body to schema and populate Computed attribute values
err = mapDataSourceFields(recordSetResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Processing API payload: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error reading user",
fmt.Sprintf("Processing API payload: %v", err),
)
return
}
@ -189,38 +225,38 @@ func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "SQLServer Flex user read")
tflog.Info(ctx, "SQLServer Flex instance read")
}
func mapDataSourceFields(userResp *sqlserverflex.GetUserResponse, model *DataSourceModel, region string) error {
if userResp == nil || userResp.Item == nil {
func mapDataSourceFields(userResp *sqlserverflexalpha.GetUserResponse, model *DataSourceModel, region string) error {
if userResp == nil {
return fmt.Errorf("response is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
user := userResp.Item
user := userResp
var userId string
if model.UserId.ValueString() != "" {
userId = model.UserId.ValueString()
var userId int64
if model.UserId.ValueInt64() != 0 {
userId = model.UserId.ValueInt64()
} else if user.Id != nil {
userId = *user.Id
} else {
return fmt.Errorf("user id not present")
}
model.Id = utils.BuildInternalTerraformId(
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), userId,
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), strconv.FormatInt(userId, 10),
)
model.UserId = types.StringValue(userId)
model.UserId = types.Int64Value(userId)
model.Username = types.StringPointerValue(user.Username)
if user.Roles == nil {
model.Roles = types.SetNull(types.StringType)
} else {
roles := []attr.Value{}
var roles []attr.Value
for _, role := range *user.Roles {
roles = append(roles, types.StringValue(role))
roles = append(roles, types.StringValue(string(role)))
}
rolesSet, diags := types.SetValue(types.StringType, roles)
if diags.HasError() {
@ -231,5 +267,8 @@ func mapDataSourceFields(userResp *sqlserverflex.GetUserResponse, model *DataSou
model.Host = types.StringPointerValue(user.Host)
model.Port = types.Int64PointerValue(user.Port)
model.Region = types.StringValue(region)
model.Status = types.StringPointerValue(user.Status)
model.DefaultDatabase = types.StringPointerValue(user.DefaultDatabase)
return nil
}

View file

@ -1,4 +1,6 @@
package sqlserverflex
// Copyright (c) STACKIT
package sqlserverflexalpha
import (
"testing"
@ -7,84 +9,87 @@ import (
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
"github.com/stackitcloud/terraform-provider-stackit/pkg/sqlserverflexalpha"
)
func TestMapDataSourceFields(t *testing.T) {
const testRegion = "region"
tests := []struct {
description string
input *sqlserverflex.GetUserResponse
input *sqlserverflexalpha.GetUserResponse
region string
expected DataSourceModel
isValid bool
}{
{
"default_values",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{},
},
&sqlserverflexalpha.GetUserResponse{},
testRegion,
DataSourceModel{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
Roles: types.SetNull(types.StringType),
Host: types.StringNull(),
Port: types.Int64Null(),
Region: types.StringValue(testRegion),
Id: types.StringValue("pid,region,iid,1"),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
Roles: types.SetNull(types.StringType),
Host: types.StringNull(),
Port: types.Int64Null(),
Region: types.StringValue(testRegion),
Status: types.StringNull(),
DefaultDatabase: types.StringNull(),
},
true,
},
{
"simple_values",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{
Roles: &[]string{
"role_1",
"role_2",
"",
},
Username: utils.Ptr("username"),
Host: utils.Ptr("host"),
Port: utils.Ptr(int64(1234)),
&sqlserverflexalpha.GetUserResponse{
Roles: &[]sqlserverflexalpha.UserRole{
"role_1",
"role_2",
"",
},
Username: utils.Ptr("username"),
Host: utils.Ptr("host"),
Port: utils.Ptr(int64(1234)),
Status: utils.Ptr("active"),
DefaultDatabase: utils.Ptr("default_db"),
},
testRegion,
DataSourceModel{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
Id: types.StringValue("pid,region,iid,1"),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringValue("username"),
Roles: types.SetValueMust(types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
}),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Region: types.StringValue(testRegion),
Roles: types.SetValueMust(
types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
},
),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Region: types.StringValue(testRegion),
Status: types.StringValue("active"),
DefaultDatabase: types.StringValue("default_db"),
},
true,
},
{
"null_fields_and_int_conversions",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{
Id: utils.Ptr("uid"),
Roles: &[]string{},
Username: nil,
Host: nil,
Port: utils.Ptr(int64(2123456789)),
},
&sqlserverflexalpha.GetUserResponse{
Id: utils.Ptr(int64(1)),
Roles: &[]sqlserverflexalpha.UserRole{},
Username: nil,
Host: nil,
Port: utils.Ptr(int64(2123456789)),
},
testRegion,
DataSourceModel{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
Id: types.StringValue("pid,region,iid,1"),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
@ -104,41 +109,41 @@ func TestMapDataSourceFields(t *testing.T) {
},
{
"nil_response_2",
&sqlserverflex.GetUserResponse{},
&sqlserverflexalpha.GetUserResponse{},
testRegion,
DataSourceModel{},
false,
},
{
"no_resource_id",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{},
},
&sqlserverflexalpha.GetUserResponse{},
testRegion,
DataSourceModel{},
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
state := &DataSourceModel{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
UserId: tt.expected.UserId,
}
err := mapDataSourceFields(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(state, &tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
t.Run(
tt.description, func(t *testing.T) {
state := &DataSourceModel{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
UserId: tt.expected.UserId,
}
}
})
err := mapDataSourceFields(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(state, &tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
},
)
}
}

View file

@ -1,12 +1,17 @@
package sqlserverflex
// Copyright (c) STACKIT
package sqlserverflexalpha
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
sqlserverflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/sqlserverflex/utils"
"github.com/stackitcloud/terraform-provider-stackit/pkg/sqlserverflexalpha"
sqlserverflexalphaUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/sqlserverflexalpha/utils"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-log/tflog"
@ -24,7 +29,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
)
// Ensure the implementation satisfies the expected interfaces.
@ -36,16 +40,18 @@ var (
)
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
UserId types.String `tfsdk:"user_id"`
InstanceId types.String `tfsdk:"instance_id"`
ProjectId types.String `tfsdk:"project_id"`
Username types.String `tfsdk:"username"`
Roles types.Set `tfsdk:"roles"`
Password types.String `tfsdk:"password"`
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Region types.String `tfsdk:"region"`
Id types.String `tfsdk:"id"` // needed by TF
UserId types.Int64 `tfsdk:"user_id"`
InstanceId types.String `tfsdk:"instance_id"`
ProjectId types.String `tfsdk:"project_id"`
Username types.String `tfsdk:"username"`
Roles types.Set `tfsdk:"roles"`
Password types.String `tfsdk:"password"`
Host types.String `tfsdk:"host"`
Port types.Int64 `tfsdk:"port"`
Region types.String `tfsdk:"region"`
Status types.String `tfsdk:"status"`
DefaultDatabase types.String `tfsdk:"default_database"`
}
// NewUserResource is a helper function to simplify the provider implementation.
@ -55,13 +61,13 @@ func NewUserResource() resource.Resource {
// userResource is the resource implementation.
type userResource struct {
client *sqlserverflex.APIClient
client *sqlserverflexalpha.APIClient
providerData core.ProviderData
}
// Metadata returns the resource type name.
func (r *userResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_sqlserverflex_user"
resp.TypeName = req.ProviderTypeName + "_sqlserverflexalpha_user"
}
// Configure adds the provider configured client to the resource.
@ -72,17 +78,21 @@ func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequ
return
}
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
apiClient := sqlserverflexalphaUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "SQLServer Flex user client configured")
tflog.Info(ctx, "SQLServer Alpha Flex user client configured")
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *userResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
func (r *userResource) 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() {
@ -113,14 +123,16 @@ func (r *userResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRe
// Schema defines the schema for the resource.
func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{
"main": "SQLServer Flex user resource schema. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`instance_id`,`user_id`\".",
"user_id": "User ID.",
"instance_id": "ID of the SQLServer Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"username": "Username of the SQLServer Flex instance.",
"roles": "Database access levels for the user. The values for the default roles are: `##STACKIT_DatabaseManager##`, `##STACKIT_LoginManager##`, `##STACKIT_ProcessManager##`, `##STACKIT_ServerManager##`, `##STACKIT_SQLAgentManager##`, `##STACKIT_SQLAgentUser##`",
"password": "Password of the user account.",
"main": "SQLServer Flex user resource schema. Must have a `region` specified in the provider configuration.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`instance_id`,`user_id`\".",
"user_id": "User ID.",
"instance_id": "ID of the SQLServer Flex instance.",
"project_id": "STACKIT project ID to which the instance is associated.",
"username": "Username of the SQLServer Flex instance.",
"roles": "Database access levels for the user. The values for the default roles are: `##STACKIT_DatabaseManager##`, `##STACKIT_LoginManager##`, `##STACKIT_ProcessManager##`, `##STACKIT_ServerManager##`, `##STACKIT_SQLAgentManager##`, `##STACKIT_SQLAgentUser##`",
"password": "Password of the user account.",
"status": "Status of the user.",
"default_database": "Default database of the user.",
}
resp.Schema = schema.Schema{
@ -203,12 +215,22 @@ func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp
stringplanmodifier.RequiresReplace(),
},
},
"status": schema.StringAttribute{
Computed: true,
},
"default_database": schema.StringAttribute{
Computed: true,
},
},
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
func (r *userResource) Create(
ctx context.Context,
req resource.CreateRequest,
resp *resource.CreateResponse,
) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -226,7 +248,7 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "region", region)
var roles []string
var roles []sqlserverflexalpha.UserRole
if !(model.Roles.IsNull() || model.Roles.IsUnknown()) {
diags = model.Roles.ElementsAs(ctx, &roles, false)
resp.Diagnostics.Append(diags...)
@ -242,7 +264,12 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
return
}
// Create new user
userResp, err := r.client.CreateUser(ctx, projectId, instanceId, region).CreateUserPayload(*payload).Execute()
userResp, err := r.client.CreateUserRequest(
ctx,
projectId,
region,
instanceId,
).CreateUserRequestPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Calling API: %v", err))
return
@ -250,17 +277,27 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
ctx = core.LogResponse(ctx)
if userResp == nil || userResp.Item == nil || userResp.Item.Id == nil || *userResp.Item.Id == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", "API didn't return user Id. A user might have been created")
if userResp == nil || userResp.Id == nil || *userResp.Id == 0 {
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error creating user",
"API didn't return user Id. A user might have been created",
)
return
}
userId := *userResp.Item.Id
userId := *userResp.Id
ctx = tflog.SetField(ctx, "user_id", userId)
// Map response body to schema
err = mapFieldsCreate(userResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Processing API payload: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error creating user",
fmt.Sprintf("Processing API payload: %v", err),
)
return
}
// Set state to fully populated data
@ -273,7 +310,11 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
}
// Read refreshes the Terraform state with the latest data.
func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
func (r *userResource) Read(
ctx context.Context,
req resource.ReadRequest,
resp *resource.ReadResponse,
) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
@ -285,16 +326,21 @@ func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueString()
userId := model.UserId.ValueInt64()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
ctx = tflog.SetField(ctx, "user_id", userId)
ctx = tflog.SetField(ctx, "region", region)
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId, region).Execute()
recordSetResp, err := r.client.GetUserRequest(ctx, projectId, region, instanceId, userId).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
var oapiErr *oapierror.GenericOpenAPIError
ok := errors.As(
err,
&oapiErr,
)
//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 {
resp.State.RemoveResource(ctx)
return
@ -308,7 +354,12 @@ func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp
// Map response body to schema
err = mapFields(recordSetResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Processing API payload: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error reading user",
fmt.Sprintf("Processing API payload: %v", err),
)
return
}
@ -322,13 +373,21 @@ func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *userResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
func (r *userResource) Update(
ctx context.Context,
_ resource.UpdateRequest,
resp *resource.UpdateResponse,
) { // nolint:gocritic // function signature required by Terraform
// Update shouldn't be called
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", "User can't be updated")
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
func (r *userResource) Delete(
ctx context.Context,
req resource.DeleteRequest,
resp *resource.DeleteResponse,
) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
var model Model
diags := req.State.Get(ctx, &model)
@ -341,7 +400,7 @@ func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, r
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
userId := model.UserId.ValueString()
userId := model.UserId.ValueInt64()
region := model.Region.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
@ -349,7 +408,7 @@ func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, r
ctx = tflog.SetField(ctx, "region", region)
// Delete existing record set
err := r.client.DeleteUser(ctx, projectId, instanceId, userId, region).Execute()
err := r.client.DeleteUserRequest(ctx, projectId, region, instanceId, userId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Calling API: %v", err))
return
@ -362,12 +421,20 @@ func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, r
// ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
func (r *userResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
func (r *userResource) ImportState(
ctx context.Context,
req resource.ImportStateRequest,
resp *resource.ImportStateResponse,
) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
core.LogAndAddError(
ctx, &resp.Diagnostics,
"Error importing user",
fmt.Sprintf("Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q", req.ID),
fmt.Sprintf(
"Expected import identifier with format [project_id],[region],[instance_id],[user_id], got %q",
req.ID,
),
)
return
}
@ -376,28 +443,35 @@ func (r *userResource) ImportState(ctx context.Context, req resource.ImportState
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])...)
core.LogAndAddWarning(ctx, &resp.Diagnostics,
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.",
)
tflog.Info(ctx, "SQLServer Flex user state imported")
}
func mapFieldsCreate(userResp *sqlserverflex.CreateUserResponse, model *Model, region string) error {
if userResp == nil || userResp.Item == nil {
func mapFieldsCreate(userResp *sqlserverflexalpha.CreateUserResponse, model *Model, region string) error {
if userResp == nil {
return fmt.Errorf("response is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
user := userResp.Item
user := userResp
if user.Id == nil {
return fmt.Errorf("user id not present")
}
userId := *user.Id
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), userId)
model.UserId = types.StringValue(userId)
model.Id = utils.BuildInternalTerraformId(
model.ProjectId.ValueString(),
region,
model.InstanceId.ValueString(),
strconv.FormatInt(userId, 10),
)
model.UserId = types.Int64Value(userId)
model.Username = types.StringPointerValue(user.Username)
if user.Password == nil {
@ -406,9 +480,9 @@ func mapFieldsCreate(userResp *sqlserverflex.CreateUserResponse, model *Model, r
model.Password = types.StringValue(*user.Password)
if user.Roles != nil {
roles := []attr.Value{}
var roles []attr.Value
for _, role := range *user.Roles {
roles = append(roles, types.StringValue(role))
roles = append(roles, types.StringValue(string(role)))
}
rolesSet, diags := types.SetValue(types.StringType, roles)
if diags.HasError() {
@ -424,21 +498,24 @@ func mapFieldsCreate(userResp *sqlserverflex.CreateUserResponse, model *Model, r
model.Host = types.StringPointerValue(user.Host)
model.Port = types.Int64PointerValue(user.Port)
model.Region = types.StringValue(region)
model.Status = types.StringPointerValue(user.Status)
model.DefaultDatabase = types.StringPointerValue(user.DefaultDatabase)
return nil
}
func mapFields(userResp *sqlserverflex.GetUserResponse, model *Model, region string) error {
if userResp == nil || userResp.Item == nil {
func mapFields(userResp *sqlserverflexalpha.GetUserResponse, model *Model, region string) error {
if userResp == nil {
return fmt.Errorf("response is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
user := userResp.Item
user := userResp
var userId string
if model.UserId.ValueString() != "" {
userId = model.UserId.ValueString()
var userId int64
if model.UserId.ValueInt64() != 0 {
userId = model.UserId.ValueInt64()
} else if user.Id != nil {
userId = *user.Id
} else {
@ -448,15 +525,15 @@ func mapFields(userResp *sqlserverflex.GetUserResponse, model *Model, region str
model.ProjectId.ValueString(),
region,
model.InstanceId.ValueString(),
userId,
strconv.FormatInt(userId, 10),
)
model.UserId = types.StringValue(userId)
model.UserId = types.Int64Value(userId)
model.Username = types.StringPointerValue(user.Username)
if user.Roles != nil {
roles := []attr.Value{}
var roles []attr.Value
for _, role := range *user.Roles {
roles = append(roles, types.StringValue(role))
roles = append(roles, types.StringValue(string(role)))
}
rolesSet, diags := types.SetValue(types.StringType, roles)
if diags.HasError() {
@ -475,13 +552,17 @@ func mapFields(userResp *sqlserverflex.GetUserResponse, model *Model, region str
return nil
}
func toCreatePayload(model *Model, roles []string) (*sqlserverflex.CreateUserPayload, error) {
func toCreatePayload(
model *Model,
roles []sqlserverflexalpha.UserRole,
) (*sqlserverflexalpha.CreateUserRequestPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
return &sqlserverflex.CreateUserPayload{
Username: conversion.StringValueToPointer(model.Username),
Roles: &roles,
return &sqlserverflexalpha.CreateUserRequestPayload{
Username: conversion.StringValueToPointer(model.Username),
DefaultDatabase: conversion.StringValueToPointer(model.DefaultDatabase),
Roles: &roles,
}, nil
}

View file

@ -1,4 +1,6 @@
package sqlserverflex
// Copyright (c) STACKIT
package sqlserverflexalpha
import (
"testing"
@ -7,30 +9,28 @@ import (
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
"github.com/stackitcloud/terraform-provider-stackit/pkg/sqlserverflexalpha"
)
func TestMapFieldsCreate(t *testing.T) {
const testRegion = "region"
tests := []struct {
description string
input *sqlserverflex.CreateUserResponse
input *sqlserverflexalpha.CreateUserResponse
region string
expected Model
isValid bool
}{
{
"default_values",
&sqlserverflex.CreateUserResponse{
Item: &sqlserverflex.SingleUser{
Id: utils.Ptr("uid"),
Password: utils.Ptr(""),
},
&sqlserverflexalpha.CreateUserResponse{
Id: utils.Ptr(int64(1)),
Password: utils.Ptr(""),
},
testRegion,
Model{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
Id: types.StringValue("pid,region,iid,1"),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
@ -44,63 +44,67 @@ func TestMapFieldsCreate(t *testing.T) {
},
{
"simple_values",
&sqlserverflex.CreateUserResponse{
Item: &sqlserverflex.SingleUser{
Id: utils.Ptr("uid"),
Roles: &[]string{
"role_1",
"role_2",
"",
},
Username: utils.Ptr("username"),
Password: utils.Ptr("password"),
Host: utils.Ptr("host"),
Port: utils.Ptr(int64(1234)),
&sqlserverflexalpha.CreateUserResponse{
Id: utils.Ptr(int64(2)),
Roles: &[]sqlserverflexalpha.UserRole{
"role_1",
"role_2",
"",
},
Username: utils.Ptr("username"),
Password: utils.Ptr("password"),
Host: utils.Ptr("host"),
Port: utils.Ptr(int64(1234)),
Status: utils.Ptr("status"),
DefaultDatabase: utils.Ptr("default_db"),
},
testRegion,
Model{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
Id: types.StringValue("pid,region,iid,2"),
UserId: types.Int64Value(2),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringValue("username"),
Roles: types.SetValueMust(types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
}),
Password: types.StringValue("password"),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Region: types.StringValue(testRegion),
Roles: types.SetValueMust(
types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
},
),
Password: types.StringValue("password"),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Region: types.StringValue(testRegion),
Status: types.StringValue("status"),
DefaultDatabase: types.StringValue("default_db"),
},
true,
},
{
"null_fields_and_int_conversions",
&sqlserverflex.CreateUserResponse{
Item: &sqlserverflex.SingleUser{
Id: utils.Ptr("uid"),
Roles: &[]string{},
Username: nil,
Password: utils.Ptr(""),
Host: nil,
Port: utils.Ptr(int64(2123456789)),
},
&sqlserverflexalpha.CreateUserResponse{
Id: utils.Ptr(int64(3)),
Roles: &[]sqlserverflexalpha.UserRole{},
Username: nil,
Password: utils.Ptr(""),
Host: nil,
Port: utils.Ptr(int64(2123456789)),
},
testRegion,
Model{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
Password: types.StringValue(""),
Host: types.StringNull(),
Port: types.Int64Value(2123456789),
Region: types.StringValue(testRegion),
Id: types.StringValue("pid,region,iid,3"),
UserId: types.Int64Value(3),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
Password: types.StringValue(""),
Host: types.StringNull(),
Port: types.Int64Value(2123456789),
Region: types.StringValue(testRegion),
DefaultDatabase: types.StringNull(),
Status: types.StringNull(),
},
true,
},
@ -113,26 +117,22 @@ func TestMapFieldsCreate(t *testing.T) {
},
{
"nil_response_2",
&sqlserverflex.CreateUserResponse{},
&sqlserverflexalpha.CreateUserResponse{},
testRegion,
Model{},
false,
},
{
"no_resource_id",
&sqlserverflex.CreateUserResponse{
Item: &sqlserverflex.SingleUser{},
},
&sqlserverflexalpha.CreateUserResponse{},
testRegion,
Model{},
false,
},
{
"no_password",
&sqlserverflex.CreateUserResponse{
Item: &sqlserverflex.SingleUser{
Id: utils.Ptr("uid"),
},
&sqlserverflexalpha.CreateUserResponse{
Id: utils.Ptr(int64(1)),
},
testRegion,
Model{},
@ -140,25 +140,27 @@ func TestMapFieldsCreate(t *testing.T) {
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
state := &Model{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
}
err := mapFieldsCreate(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(state, &tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
t.Run(
tt.description, func(t *testing.T) {
state := &Model{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
}
}
})
err := mapFieldsCreate(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(state, &tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
},
)
}
}
@ -166,20 +168,18 @@ func TestMapFields(t *testing.T) {
const testRegion = "region"
tests := []struct {
description string
input *sqlserverflex.GetUserResponse
input *sqlserverflexalpha.GetUserResponse
region string
expected Model
isValid bool
}{
{
"default_values",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{},
},
&sqlserverflexalpha.GetUserResponse{},
testRegion,
Model{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
Id: types.StringValue("pid,region,iid,1"),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
@ -192,30 +192,30 @@ func TestMapFields(t *testing.T) {
},
{
"simple_values",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{
Roles: &[]string{
"role_1",
"role_2",
"",
},
Username: utils.Ptr("username"),
Host: utils.Ptr("host"),
Port: utils.Ptr(int64(1234)),
&sqlserverflexalpha.GetUserResponse{
Roles: &[]sqlserverflexalpha.UserRole{
"role_1",
"role_2",
"",
},
Username: utils.Ptr("username"),
Host: utils.Ptr("host"),
Port: utils.Ptr(int64(1234)),
},
testRegion,
Model{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
Id: types.StringValue("pid,region,iid,2"),
UserId: types.Int64Value(2),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringValue("username"),
Roles: types.SetValueMust(types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
}),
Roles: types.SetValueMust(
types.StringType, []attr.Value{
types.StringValue("role_1"),
types.StringValue("role_2"),
types.StringValue(""),
},
),
Host: types.StringValue("host"),
Port: types.Int64Value(1234),
Region: types.StringValue(testRegion),
@ -224,19 +224,17 @@ func TestMapFields(t *testing.T) {
},
{
"null_fields_and_int_conversions",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{
Id: utils.Ptr("uid"),
Roles: &[]string{},
Username: nil,
Host: nil,
Port: utils.Ptr(int64(2123456789)),
},
&sqlserverflexalpha.GetUserResponse{
Id: utils.Ptr(int64(1)),
Roles: &[]sqlserverflexalpha.UserRole{},
Username: nil,
Host: nil,
Port: utils.Ptr(int64(2123456789)),
},
testRegion,
Model{
Id: types.StringValue("pid,region,iid,uid"),
UserId: types.StringValue("uid"),
Id: types.StringValue("pid,region,iid,1"),
UserId: types.Int64Value(1),
InstanceId: types.StringValue("iid"),
ProjectId: types.StringValue("pid"),
Username: types.StringNull(),
@ -256,42 +254,42 @@ func TestMapFields(t *testing.T) {
},
{
"nil_response_2",
&sqlserverflex.GetUserResponse{},
&sqlserverflexalpha.GetUserResponse{},
testRegion,
Model{},
false,
},
{
"no_resource_id",
&sqlserverflex.GetUserResponse{
Item: &sqlserverflex.UserResponseUser{},
},
&sqlserverflexalpha.GetUserResponse{},
testRegion,
Model{},
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
state := &Model{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
UserId: tt.expected.UserId,
}
err := mapFields(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(state, &tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
t.Run(
tt.description, func(t *testing.T) {
state := &Model{
ProjectId: tt.expected.ProjectId,
InstanceId: tt.expected.InstanceId,
UserId: tt.expected.UserId,
}
}
})
err := mapFields(tt.input, state, tt.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(state, &tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
},
)
}
}
@ -299,16 +297,16 @@ func TestToCreatePayload(t *testing.T) {
tests := []struct {
description string
input *Model
inputRoles []string
expected *sqlserverflex.CreateUserPayload
inputRoles []sqlserverflexalpha.UserRole
expected *sqlserverflexalpha.CreateUserRequestPayload
isValid bool
}{
{
"default_values",
&Model{},
[]string{},
&sqlserverflex.CreateUserPayload{
Roles: &[]string{},
[]sqlserverflexalpha.UserRole{},
&sqlserverflexalpha.CreateUserRequestPayload{
Roles: &[]sqlserverflexalpha.UserRole{},
Username: nil,
},
true,
@ -318,12 +316,12 @@ func TestToCreatePayload(t *testing.T) {
&Model{
Username: types.StringValue("username"),
},
[]string{
[]sqlserverflexalpha.UserRole{
"role_1",
"role_2",
},
&sqlserverflex.CreateUserPayload{
Roles: &[]string{
&sqlserverflexalpha.CreateUserRequestPayload{
Roles: &[]sqlserverflexalpha.UserRole{
"role_1",
"role_2",
},
@ -336,11 +334,11 @@ func TestToCreatePayload(t *testing.T) {
&Model{
Username: types.StringNull(),
},
[]string{
[]sqlserverflexalpha.UserRole{
"",
},
&sqlserverflex.CreateUserPayload{
Roles: &[]string{
&sqlserverflexalpha.CreateUserRequestPayload{
Roles: &[]sqlserverflexalpha.UserRole{
"",
},
Username: nil,
@ -350,7 +348,7 @@ func TestToCreatePayload(t *testing.T) {
{
"nil_model",
nil,
[]string{},
[]sqlserverflexalpha.UserRole{},
nil,
false,
},
@ -359,29 +357,31 @@ func TestToCreatePayload(t *testing.T) {
&Model{
Username: types.StringValue("username"),
},
[]string{},
&sqlserverflex.CreateUserPayload{
Roles: &[]string{},
[]sqlserverflexalpha.UserRole{},
&sqlserverflexalpha.CreateUserRequestPayload{
Roles: &[]sqlserverflexalpha.UserRole{},
Username: utils.Ptr("username"),
},
true,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
output, err := toCreatePayload(tt.input, tt.inputRoles)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(output, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
t.Run(
tt.description, func(t *testing.T) {
output, err := toCreatePayload(tt.input, tt.inputRoles)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
}
})
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(output, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
},
)
}
}

View file

@ -1,10 +1,12 @@
// Copyright (c) STACKIT
package utils
import (
"context"
"fmt"
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
sqlserverflex "github.com/stackitcloud/terraform-provider-stackit/pkg/sqlserverflexalpha"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/stackitcloud/stackit-sdk-go/core/config"
@ -12,19 +14,34 @@ import (
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
)
func ConfigureClient(ctx context.Context, providerData *core.ProviderData, diags *diag.Diagnostics) *sqlserverflex.APIClient {
func ConfigureClient(
ctx context.Context,
providerData *core.ProviderData,
diags *diag.Diagnostics,
) *sqlserverflex.APIClient {
apiClientConfigOptions := []config.ConfigurationOption{
config.WithCustomAuth(providerData.RoundTripper),
utils.UserAgentConfigOption(providerData.Version),
}
if providerData.SQLServerFlexCustomEndpoint != "" {
apiClientConfigOptions = append(apiClientConfigOptions, config.WithEndpoint(providerData.SQLServerFlexCustomEndpoint))
apiClientConfigOptions = append(
apiClientConfigOptions,
config.WithEndpoint(providerData.SQLServerFlexCustomEndpoint),
)
} else {
apiClientConfigOptions = append(apiClientConfigOptions, config.WithRegion(providerData.GetRegion()))
}
apiClient, err := sqlserverflex.NewAPIClient(apiClientConfigOptions...)
if err != nil {
core.LogAndAddError(ctx, diags, "Error configuring API client", fmt.Sprintf("Configuring client: %v. This is an error related to the provider configuration, not to the resource configuration", err))
core.LogAndAddError(
ctx,
diags,
"Error configuring API client",
fmt.Sprintf(
"Configuring client: %v. This is an error related to the provider configuration, not to the resource configuration",
err,
),
)
return nil
}

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (
@ -9,7 +11,8 @@ import (
"github.com/hashicorp/terraform-plugin-framework/diag"
sdkClients "github.com/stackitcloud/stackit-sdk-go/core/clients"
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
"github.com/stackitcloud/terraform-provider-stackit/pkg/sqlserverflexalpha"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
)
@ -34,7 +37,7 @@ func TestConfigureClient(t *testing.T) {
name string
args args
wantErr bool
expected *sqlserverflex.APIClient
expected *sqlserverflexalpha.APIClient
}{
{
name: "default endpoint",
@ -43,8 +46,8 @@ func TestConfigureClient(t *testing.T) {
Version: testVersion,
},
},
expected: func() *sqlserverflex.APIClient {
apiClient, err := sqlserverflex.NewAPIClient(
expected: func() *sqlserverflexalpha.APIClient {
apiClient, err := sqlserverflexalpha.NewAPIClient(
config.WithRegion("eu01"),
utils.UserAgentConfigOption(testVersion),
)
@ -63,8 +66,8 @@ func TestConfigureClient(t *testing.T) {
SQLServerFlexCustomEndpoint: testCustomEndpoint,
},
},
expected: func() *sqlserverflex.APIClient {
apiClient, err := sqlserverflex.NewAPIClient(
expected: func() *sqlserverflexalpha.APIClient {
apiClient, err := sqlserverflexalpha.NewAPIClient(
utils.UserAgentConfigOption(testVersion),
config.WithEndpoint(testCustomEndpoint),
)
@ -77,18 +80,20 @@ func TestConfigureClient(t *testing.T) {
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
diags := diag.Diagnostics{}
t.Run(
tt.name, func(t *testing.T) {
ctx := context.Background()
diags := diag.Diagnostics{}
actual := ConfigureClient(ctx, tt.args.providerData, &diags)
if diags.HasError() != tt.wantErr {
t.Errorf("ConfigureClient() error = %v, want %v", diags.HasError(), tt.wantErr)
}
actual := ConfigureClient(ctx, tt.args.providerData, &diags)
if diags.HasError() != tt.wantErr {
t.Errorf("ConfigureClient() error = %v, want %v", diags.HasError(), tt.wantErr)
}
if !reflect.DeepEqual(actual, tt.expected) {
t.Errorf("ConfigureClient() = %v, want %v", actual, tt.expected)
}
})
if !reflect.DeepEqual(actual, tt.expected) {
t.Errorf("ConfigureClient() = %v, want %v", actual, tt.expected)
}
},
)
}
}

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package testutil
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package testutil
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package utils
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package validate
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package validate
import (

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package stackit
import (
@ -18,8 +20,8 @@ import (
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
roleAssignements "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/authorization/roleassignments"
postgresFlexAlphaInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflexalpha/instance"
sqlServerFlexAlpaUser "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/sqlserverflexalpha/user"
)
// Ensure the implementation satisfies the expected interfaces
@ -42,7 +44,7 @@ func New(version string) func() provider.Provider {
}
func (p *Provider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "stackitalpha"
resp.TypeName = "stackitprivatepreview"
resp.Version = p.version
}
@ -131,7 +133,10 @@ func (p *Provider) Schema(_ context.Context, _ provider.SchemaRequest, resp *pro
"service_enablement_custom_endpoint": "Custom endpoint for the Service Enablement API",
"token_custom_endpoint": "Custom endpoint for the token API, which is used to request access tokens when using the key flow",
"enable_beta_resources": "Enable beta resources. Default is false.",
"experiments": fmt.Sprintf("Enables experiments. These are unstable features without official support. More information can be found in the README. Available Experiments: %v", strings.Join(features.AvailableExperiments, ", ")),
"experiments": fmt.Sprintf(
"Enables experiments. These are unstable features without official support. More information can be found in the README. Available Experiments: %v",
strings.Join(features.AvailableExperiments, ", "),
),
}
resp.Schema = schema.Schema{
@ -331,7 +336,12 @@ func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest,
if !v.IsUnknown() && !v.IsNull() {
val, err := v.ToBoolValue(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring provider", fmt.Sprintf("Setting up bool value: %v", diags.Errors()))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error configuring provider",
fmt.Sprintf("Setting up bool value: %v", diags.Errors()),
)
}
setter(val.ValueBool())
}
@ -347,48 +357,106 @@ func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest,
setStringField(providerConfig.TokenCustomEndpoint, func(v string) { sdkConfig.TokenCustomUrl = v })
setStringField(providerConfig.DefaultRegion, func(v string) { providerData.DefaultRegion = v })
setStringField(providerConfig.Region, func(v string) { providerData.Region = v }) // nolint:staticcheck // preliminary handling of deprecated attribute
setStringField(
providerConfig.Region,
func(v string) { providerData.Region = v },
) // nolint:staticcheck // preliminary handling of deprecated attribute
setBoolField(providerConfig.EnableBetaResources, func(v bool) { providerData.EnableBetaResources = v })
setStringField(providerConfig.AuthorizationCustomEndpoint, func(v string) { providerData.AuthorizationCustomEndpoint = v })
setStringField(
providerConfig.AuthorizationCustomEndpoint,
func(v string) { providerData.AuthorizationCustomEndpoint = v },
)
setStringField(providerConfig.CdnCustomEndpoint, func(v string) { providerData.CdnCustomEndpoint = v })
setStringField(providerConfig.DnsCustomEndpoint, func(v string) { providerData.DnsCustomEndpoint = v })
setStringField(providerConfig.GitCustomEndpoint, func(v string) { providerData.GitCustomEndpoint = v })
setStringField(providerConfig.IaaSCustomEndpoint, func(v string) { providerData.IaaSCustomEndpoint = v })
setStringField(providerConfig.KmsCustomEndpoint, func(v string) { providerData.KMSCustomEndpoint = v })
setStringField(providerConfig.LoadBalancerCustomEndpoint, func(v string) { providerData.LoadBalancerCustomEndpoint = v })
setStringField(
providerConfig.LoadBalancerCustomEndpoint,
func(v string) { providerData.LoadBalancerCustomEndpoint = v },
)
setStringField(providerConfig.LogMeCustomEndpoint, func(v string) { providerData.LogMeCustomEndpoint = v })
setStringField(providerConfig.MariaDBCustomEndpoint, func(v string) { providerData.MariaDBCustomEndpoint = v })
setStringField(providerConfig.ModelServingCustomEndpoint, func(v string) { providerData.ModelServingCustomEndpoint = v })
setStringField(providerConfig.MongoDBFlexCustomEndpoint, func(v string) { providerData.MongoDBFlexCustomEndpoint = v })
setStringField(providerConfig.ObjectStorageCustomEndpoint, func(v string) { providerData.ObjectStorageCustomEndpoint = v })
setStringField(providerConfig.ObservabilityCustomEndpoint, func(v string) { providerData.ObservabilityCustomEndpoint = v })
setStringField(providerConfig.OpenSearchCustomEndpoint, func(v string) { providerData.OpenSearchCustomEndpoint = v })
setStringField(providerConfig.PostgresFlexCustomEndpoint, func(v string) { providerData.PostgresFlexCustomEndpoint = v })
setStringField(
providerConfig.ModelServingCustomEndpoint,
func(v string) { providerData.ModelServingCustomEndpoint = v },
)
setStringField(
providerConfig.MongoDBFlexCustomEndpoint,
func(v string) { providerData.MongoDBFlexCustomEndpoint = v },
)
setStringField(
providerConfig.ObjectStorageCustomEndpoint,
func(v string) { providerData.ObjectStorageCustomEndpoint = v },
)
setStringField(
providerConfig.ObservabilityCustomEndpoint,
func(v string) { providerData.ObservabilityCustomEndpoint = v },
)
setStringField(
providerConfig.OpenSearchCustomEndpoint,
func(v string) { providerData.OpenSearchCustomEndpoint = v },
)
setStringField(
providerConfig.PostgresFlexCustomEndpoint,
func(v string) { providerData.PostgresFlexCustomEndpoint = v },
)
setStringField(providerConfig.RabbitMQCustomEndpoint, func(v string) { providerData.RabbitMQCustomEndpoint = v })
setStringField(providerConfig.RedisCustomEndpoint, func(v string) { providerData.RedisCustomEndpoint = v })
setStringField(providerConfig.ResourceManagerCustomEndpoint, func(v string) { providerData.ResourceManagerCustomEndpoint = v })
setStringField(
providerConfig.ResourceManagerCustomEndpoint,
func(v string) { providerData.ResourceManagerCustomEndpoint = v },
)
setStringField(providerConfig.ScfCustomEndpoint, func(v string) { providerData.ScfCustomEndpoint = v })
setStringField(providerConfig.SecretsManagerCustomEndpoint, func(v string) { providerData.SecretsManagerCustomEndpoint = v })
setStringField(providerConfig.ServerBackupCustomEndpoint, func(v string) { providerData.ServerBackupCustomEndpoint = v })
setStringField(providerConfig.ServerUpdateCustomEndpoint, func(v string) { providerData.ServerUpdateCustomEndpoint = v })
setStringField(providerConfig.ServiceAccountCustomEndpoint, func(v string) { providerData.ServiceAccountCustomEndpoint = v })
setStringField(providerConfig.ServiceEnablementCustomEndpoint, func(v string) { providerData.ServiceEnablementCustomEndpoint = v })
setStringField(
providerConfig.SecretsManagerCustomEndpoint,
func(v string) { providerData.SecretsManagerCustomEndpoint = v },
)
setStringField(
providerConfig.ServerBackupCustomEndpoint,
func(v string) { providerData.ServerBackupCustomEndpoint = v },
)
setStringField(
providerConfig.ServerUpdateCustomEndpoint,
func(v string) { providerData.ServerUpdateCustomEndpoint = v },
)
setStringField(
providerConfig.ServiceAccountCustomEndpoint,
func(v string) { providerData.ServiceAccountCustomEndpoint = v },
)
setStringField(
providerConfig.ServiceEnablementCustomEndpoint,
func(v string) { providerData.ServiceEnablementCustomEndpoint = v },
)
setStringField(providerConfig.SkeCustomEndpoint, func(v string) { providerData.SKECustomEndpoint = v })
setStringField(providerConfig.SqlServerFlexCustomEndpoint, func(v string) { providerData.SQLServerFlexCustomEndpoint = v })
setStringField(
providerConfig.SqlServerFlexCustomEndpoint,
func(v string) { providerData.SQLServerFlexCustomEndpoint = v },
)
if !(providerConfig.Experiments.IsUnknown() || providerConfig.Experiments.IsNull()) {
var experimentValues []string
diags := providerConfig.Experiments.ElementsAs(ctx, &experimentValues, false)
if diags.HasError() {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring provider", fmt.Sprintf("Setting up experiments: %v", diags.Errors()))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error configuring provider",
fmt.Sprintf("Setting up experiments: %v", diags.Errors()),
)
}
providerData.Experiments = experimentValues
}
roundTripper, err := sdkauth.SetupAuth(sdkConfig)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring provider", fmt.Sprintf("Setting up authentication: %v", err))
core.LogAndAddError(
ctx,
&resp.Diagnostics,
"Error configuring provider",
fmt.Sprintf("Setting up authentication: %v", err),
)
return
}
@ -402,7 +470,10 @@ func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest,
var ephemeralProviderData core.EphemeralProviderData
ephemeralProviderData.ProviderData = providerData
setStringField(providerConfig.ServiceAccountKey, func(v string) { ephemeralProviderData.ServiceAccountKey = v })
setStringField(providerConfig.ServiceAccountKeyPath, func(v string) { ephemeralProviderData.ServiceAccountKeyPath = v })
setStringField(
providerConfig.ServiceAccountKeyPath,
func(v string) { ephemeralProviderData.ServiceAccountKeyPath = v },
)
setStringField(providerConfig.PrivateKey, func(v string) { ephemeralProviderData.PrivateKey = v })
setStringField(providerConfig.PrivateKeyPath, func(v string) { ephemeralProviderData.PrivateKeyPath = v })
setStringField(providerConfig.TokenCustomEndpoint, func(v string) { ephemeralProviderData.TokenCustomEndpoint = v })
@ -413,15 +484,16 @@ func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest,
// DataSources defines the data sources implemented in the provider.
func (p *Provider) DataSources(_ context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{}
return []func() datasource.DataSource{
sqlServerFlexAlpaUser.NewUserDataSource,
}
}
// Resources defines the resources implemented in the provider.
func (p *Provider) Resources(_ context.Context) []func() resource.Resource {
resources := []func() resource.Resource{
postgresFlexAlphaInstance.NewInstanceResource,
sqlServerFlexAlpaUser.NewUserResource,
}
resources = append(resources, roleAssignements.NewRoleAssignmentResources()...)
return resources
}

View file

@ -1,3 +1,5 @@
// Copyright (c) STACKIT
package stackit_test
import (

View file

@ -1,3 +1,5 @@
# Copyright (c) STACKIT
variable "project_id" {}
variable "name" {}

View file

@ -1,3 +1,5 @@
# Copyright (c) STACKIT
variable "project_id" {}
variable "name" {}

View file

@ -1,3 +1,5 @@
# Copyright (c) STACKIT
variable "project_id" {}
variable "name" {}