chore: add missing folders
This commit is contained in:
parent
48b1c99ede
commit
3b07f3f1d3
28 changed files with 8597 additions and 2 deletions
|
|
@ -0,0 +1,171 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
postgresflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"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"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/pkg/postgresflexalpha"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &databaseDataSource{}
|
||||
)
|
||||
|
||||
// NewDatabaseDataSource is a helper function to simplify the provider implementation.
|
||||
func NewDatabaseDataSource() datasource.DataSource {
|
||||
return &databaseDataSource{}
|
||||
}
|
||||
|
||||
// databaseDataSource is the data source implementation.
|
||||
type databaseDataSource struct {
|
||||
client *postgresflexalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (r *databaseDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_database"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
func (r *databaseDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex database client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *databaseDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex database 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`,`database_id`\".",
|
||||
"database_id": "Database ID.",
|
||||
"instance_id": "ID of the Postgres Flex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Database name.",
|
||||
"owner": "Username of the database owner.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"database_id": schema.StringAttribute{
|
||||
Description: descriptions["database_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"owner": schema.StringAttribute{
|
||||
Description: descriptions["owner"],
|
||||
Computed: true,
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
// the region cannot be found, so it has to be passed
|
||||
Optional: true,
|
||||
Description: descriptions["region"],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *databaseDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
databaseResp, err := getDatabase(ctx, r.client, projectId, region, instanceId, databaseId)
|
||||
if err != nil {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading database",
|
||||
fmt.Sprintf("Database with ID %q or instance with ID %q does not exist in project %q.", databaseId, instanceId, projectId),
|
||||
map[int]string{
|
||||
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
|
||||
},
|
||||
)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(databaseResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", 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, "Postgres Flex database read")
|
||||
}
|
||||
|
|
@ -0,0 +1,447 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/pkg/postgresflexalpha"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
postgresflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"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/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/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &databaseResource{}
|
||||
_ resource.ResourceWithConfigure = &databaseResource{}
|
||||
_ resource.ResourceWithImportState = &databaseResource{}
|
||||
_ resource.ResourceWithModifyPlan = &databaseResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
DatabaseId types.String `tfsdk:"database_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Owner types.String `tfsdk:"owner"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Encryption encryptionModel `tfsdk:"encryption"`
|
||||
}
|
||||
|
||||
type encryptionModel struct {
|
||||
KeyId types.String `tfsdk:"key_id"`
|
||||
//keyringid = xxxx
|
||||
//keyversion = xxxx
|
||||
//serviceaccount = xxxx
|
||||
}
|
||||
|
||||
// NewDatabaseResource is a helper function to simplify the provider implementation.
|
||||
func NewDatabaseResource() resource.Resource {
|
||||
return &databaseResource{}
|
||||
}
|
||||
|
||||
// databaseResource is the resource implementation.
|
||||
type databaseResource struct {
|
||||
client *postgresflexalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// ModifyPlan implements resource.ResourceWithModifyPlan.
|
||||
// Use the modifier to set the effective region in the current plan.
|
||||
func (r *databaseResource) 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.GetRegion(), resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *databaseResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_database"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *databaseResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex database client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *databaseResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex database 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`,`database_id`\".",
|
||||
"database_id": "Database ID.",
|
||||
"instance_id": "ID of the Postgres Flex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Database name.",
|
||||
"owner": "Username of the database owner.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
}
|
||||
|
||||
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(),
|
||||
},
|
||||
},
|
||||
"database_id": schema.StringAttribute{
|
||||
Description: descriptions["database_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"owner": schema.StringAttribute{
|
||||
Description: descriptions["owner"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"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(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *databaseResource) 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)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new database
|
||||
databaseResp, err := r.client.CreateDatabaseRequest(ctx, projectId, region, instanceId).CreateDatabaseRequestPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
if databaseResp == nil || databaseResp.Id == nil || *databaseResp.Id == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", "API didn't return database Id. A database might have been created")
|
||||
return
|
||||
}
|
||||
databaseId := *databaseResp.Id
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
database, err := getDatabase(ctx, r.client, projectId, region, instanceId, databaseId)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Getting database details after creation: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(database, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex database created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *databaseResource) 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)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
databaseResp, err := getDatabase(ctx, r.client, projectId, region, instanceId, databaseId)
|
||||
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) || errors.Is(err, databaseNotFoundErr) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(databaseResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", 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, "Postgres Flex database read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *databaseResource) 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 database", "Database can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *databaseResource) 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)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteDatabase(ctx, projectId, region, instanceId, databaseId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting database", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
tflog.Info(ctx, "Postgres Flex database deleted")
|
||||
}
|
||||
|
||||
// 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 *databaseResource) 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,
|
||||
"Error importing database",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[region],[instance_id],[database_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("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("database_id"), idParts[3])...)
|
||||
core.LogAndAddWarning(ctx, &resp.Diagnostics,
|
||||
"Postgresflex database imported with empty password",
|
||||
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
|
||||
)
|
||||
tflog.Info(ctx, "Postgres Flex database state imported")
|
||||
}
|
||||
|
||||
func mapFields(databaseResp *postgresflex.InstanceDatabase, model *Model, region string) error {
|
||||
if databaseResp == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if databaseResp.Id == nil || *databaseResp.Id == "" {
|
||||
return fmt.Errorf("id not present")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var databaseId string
|
||||
if model.DatabaseId.ValueString() != "" {
|
||||
databaseId = model.DatabaseId.ValueString()
|
||||
} else if databaseResp.Id != nil {
|
||||
databaseId = *databaseResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("database id not present")
|
||||
}
|
||||
model.Id = utils.BuildInternalTerraformId(
|
||||
model.ProjectId.ValueString(), region, model.InstanceId.ValueString(), databaseId,
|
||||
)
|
||||
model.DatabaseId = types.StringValue(databaseId)
|
||||
model.Name = types.StringPointerValue(databaseResp.Name)
|
||||
model.Region = types.StringValue(region)
|
||||
|
||||
if databaseResp.Options != nil {
|
||||
owner, ok := (*databaseResp.Options)["owner"]
|
||||
if ok {
|
||||
ownerStr, ok := owner.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("owner is not a string")
|
||||
}
|
||||
// If the field is returned between with quotes, we trim them to prevent an inconsistent result after apply
|
||||
ownerStr = strings.TrimPrefix(ownerStr, `"`)
|
||||
ownerStr = strings.TrimSuffix(ownerStr, `"`)
|
||||
model.Owner = types.StringValue(ownerStr)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model) (*postgresflexalpha.CreateDatabaseRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
return &postgresflexalpha.CreateDatabaseRequestPayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
// TODO
|
||||
//Options: &map[string]string{
|
||||
// "owner": model.Owner.ValueString(),
|
||||
//},
|
||||
}, nil
|
||||
}
|
||||
|
||||
var databaseNotFoundErr = errors.New("database not found")
|
||||
|
||||
// The API does not have a GetDatabase endpoint, only ListDatabases
|
||||
func getDatabase(ctx context.Context, client *postgresflexalpha.APIClient, projectId, region, instanceId, databaseId string) (*postgresflex.InstanceDatabase, error) {
|
||||
resp, err := client.ListDatabasesRequest(ctx, projectId, region, instanceId).Execute()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil || resp.Databases == nil {
|
||||
return nil, fmt.Errorf("response is nil")
|
||||
}
|
||||
for _, database := range *resp.Databases {
|
||||
if database.Id != nil && *database.Id == databaseId {
|
||||
return &database, nil
|
||||
}
|
||||
}
|
||||
return nil, databaseNotFoundErr
|
||||
}
|
||||
|
|
@ -0,0 +1,190 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.InstanceDatabase
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr("uid"),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
DatabaseId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringNull(),
|
||||
Owner: types.StringNull(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr("uid"),
|
||||
Name: utils.Ptr("dbname"),
|
||||
Options: &map[string]interface{}{
|
||||
"owner": "username",
|
||||
},
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
DatabaseId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("dbname"),
|
||||
Owner: types.StringValue("username"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr("uid"),
|
||||
Name: utils.Ptr(""),
|
||||
Options: &map[string]interface{}{
|
||||
"owner": "",
|
||||
},
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
DatabaseId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue(""),
|
||||
Owner: types.StringValue(""),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"empty_response",
|
||||
&postgresflex.InstanceDatabase{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr(""),
|
||||
Name: utils.Ptr("dbname"),
|
||||
Options: &map[string]interface{}{
|
||||
"owner": "username",
|
||||
},
|
||||
},
|
||||
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,
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *postgresflex.CreateDatabasePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Name: types.StringValue("dbname"),
|
||||
Owner: types.StringValue("username"),
|
||||
},
|
||||
&postgresflex.CreateDatabasePayload{
|
||||
Name: utils.Ptr("dbname"),
|
||||
Options: &map[string]string{
|
||||
"owner": "username",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields",
|
||||
&Model{
|
||||
Name: types.StringNull(),
|
||||
Owner: types.StringNull(),
|
||||
},
|
||||
&postgresflex.CreateDatabasePayload{
|
||||
Name: nil,
|
||||
Options: &map[string]string{
|
||||
"owner": "",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,222 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/stackitcloud/terraform-provider-stackit/pkg/postgresflexalpha"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
postgresflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"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"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/pkg/postgresflexalpha/wait"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *postgresflexalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres 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`,`region`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"acl": "The Access Control List (ACL) for the PostgresFlex instance.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"acl": schema.ListAttribute{
|
||||
Description: descriptions["acl"],
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"backup_schedule": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"flavor": schema.SingleNestedAttribute{
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"replicas": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"storage": schema.SingleNestedAttribute{
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"size": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
// the region cannot be found, so it has to be passed
|
||||
Optional: true,
|
||||
Description: descriptions["region"],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
instanceResp, err := r.client.GetInstanceRequest(ctx, projectId, region, instanceId).Execute()
|
||||
if err != nil {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading instance",
|
||||
fmt.Sprintf("Instance with ID %q does not exist in project %q.", instanceId, projectId),
|
||||
map[int]string{
|
||||
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
|
||||
},
|
||||
)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
if instanceResp != nil && instanceResp.Status != nil && *instanceResp.Status == wait.InstanceStateDeleted {
|
||||
resp.State.RemoveResource(ctx)
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", "Instance was deleted successfully")
|
||||
return
|
||||
}
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err = mapFields(ctx, instanceResp, &model, flavor, storage, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", 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, "Postgres Flex instance read")
|
||||
}
|
||||
893
stackit/internal/services/postgresflexalpha/instance/resource.go
Normal file
893
stackit/internal/services/postgresflexalpha/instance/resource.go
Normal file
|
|
@ -0,0 +1,893 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/stackitcloud/terraform-provider-stackit/pkg/postgresflexalpha"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/pkg/postgresflexalpha/wait"
|
||||
postgresflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflexalpha/utils"
|
||||
|
||||
"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/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"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/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/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
_ resource.ResourceWithModifyPlan = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
ACL types.List `tfsdk:"acl"`
|
||||
BackupSchedule types.String `tfsdk:"backup_schedule"`
|
||||
Flavor types.Object `tfsdk:"flavor"`
|
||||
Replicas types.Int64 `tfsdk:"replicas"`
|
||||
Storage types.Object `tfsdk:"storage"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Encryption types.Object `tfsdk:"encryption"`
|
||||
Network types.Object `tfsdk:"network"`
|
||||
}
|
||||
|
||||
type encryptionModel struct {
|
||||
KeyRingId types.String `tfsdk:"keyring_id"`
|
||||
KeyId types.String `tfsdk:"key_id"`
|
||||
KeyVersion types.String `tfsdk:"key_version"`
|
||||
ServiceAccount types.String `tfsdk:"service_account"`
|
||||
}
|
||||
|
||||
var encryptionTypes = map[string]attr.Type{
|
||||
"keyring_id": basetypes.StringType{},
|
||||
"key_id": basetypes.StringType{},
|
||||
"key_version": basetypes.StringType{},
|
||||
"service_account": basetypes.StringType{},
|
||||
}
|
||||
|
||||
type networkModel struct {
|
||||
AccessScope types.String `tfsdk:"access_scope"`
|
||||
}
|
||||
|
||||
var networkTypes = map[string]attr.Type{
|
||||
"access_scope": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// Struct corresponding to Model.Flavor
|
||||
type flavorModel struct {
|
||||
Id types.String `tfsdk:"id"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
CPU types.Int64 `tfsdk:"cpu"`
|
||||
RAM types.Int64 `tfsdk:"ram"`
|
||||
}
|
||||
|
||||
// Types corresponding to flavorModel
|
||||
var flavorTypes = map[string]attr.Type{
|
||||
"id": basetypes.StringType{},
|
||||
"description": basetypes.StringType{},
|
||||
"cpu": basetypes.Int64Type{},
|
||||
"ram": basetypes.Int64Type{},
|
||||
}
|
||||
|
||||
// Struct corresponding to Model.Storage
|
||||
type storageModel struct {
|
||||
Class types.String `tfsdk:"class"`
|
||||
Size types.Int64 `tfsdk:"size"`
|
||||
}
|
||||
|
||||
// Types corresponding to storageModel
|
||||
var storageTypes = map[string]attr.Type{
|
||||
"class": basetypes.StringType{},
|
||||
"size": basetypes.Int64Type{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *postgresflexalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// 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.GetRegion(), resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflexalpha_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres 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`,`region`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"acl": "The Access Control List (ACL) for the PostgresFlex instance.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
"encryption": "The encryption block.",
|
||||
"key_id": "Key ID of the encryption key.",
|
||||
}
|
||||
|
||||
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(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile("^[a-z]([-a-z0-9]*[a-z0-9])?$"),
|
||||
"must start with a letter, must have lower case letters, numbers or hyphens, and no hyphen at the end",
|
||||
),
|
||||
},
|
||||
},
|
||||
"acl": schema.ListAttribute{
|
||||
Description: descriptions["acl"],
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
},
|
||||
"backup_schedule": schema.StringAttribute{
|
||||
Required: true,
|
||||
},
|
||||
"flavor": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
UseStateForUnknownIfFlavorUnchanged(req),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
UseStateForUnknownIfFlavorUnchanged(req),
|
||||
},
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"replicas": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
"storage": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"size": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Required: true,
|
||||
},
|
||||
"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(),
|
||||
},
|
||||
},
|
||||
"encryption": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"key_id": schema.StringAttribute{
|
||||
Description: descriptions["key_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"key_version": schema.StringAttribute{
|
||||
Description: descriptions["key_version"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"key_ring_id": schema.StringAttribute{
|
||||
Description: descriptions["key_ring_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"service_account": schema.StringAttribute{
|
||||
Description: descriptions["service_account"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
},
|
||||
//Blocks: nil,
|
||||
//CustomType: nil,
|
||||
Description: descriptions["encryption"],
|
||||
//MarkdownDescription: "",
|
||||
//DeprecationMessage: "",
|
||||
//Validators: nil,
|
||||
PlanModifiers: []planmodifier.Object{},
|
||||
},
|
||||
"network": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"access_scope": schema.StringAttribute{
|
||||
Description: descriptions["access_scope"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
},
|
||||
//Blocks: nil,
|
||||
//CustomType: nil,
|
||||
Description: descriptions["network"],
|
||||
//MarkdownDescription: "",
|
||||
//DeprecationMessage: "",
|
||||
//Validators: nil,
|
||||
PlanModifiers: []planmodifier.Object{},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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()) {
|
||||
diags = model.ACL.ElementsAs(ctx, &acl, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
err := loadFlavorId(ctx, r.client, &model, flavor)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading flavor ID: %v", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var encryption = &encryptionModel{}
|
||||
if !(model.Encryption.IsNull() || model.Encryption.IsUnknown()) {
|
||||
diags = model.Encryption.As(ctx, encryption, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var network = &networkModel{}
|
||||
if !(model.Network.IsNull() || model.Network.IsUnknown()) {
|
||||
diags = model.Network.As(ctx, network, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, acl, flavor, storage, encryption, network)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstanceRequest(ctx, projectId, region).CreateInstanceRequestPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
instanceId := *createResp.Id
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
waitResp, err := wait.CreateInstanceWaitHandler(ctx, r.client, projectId, region, instanceId).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, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) 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)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.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()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
instanceResp, err := r.client.GetInstanceRequest(ctx, projectId, region, instanceId).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 {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
if instanceResp != nil && instanceResp.Status != nil && *instanceResp.Status == wait.InstanceStateDeleted {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, instanceResp, &model, flavor, storage, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", 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, "Postgres Flex instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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()) {
|
||||
diags = model.ACL.ElementsAs(ctx, &acl, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
err := loadFlavorId(ctx, r.client, &model, flavor)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading flavor ID: %v", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, acl, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstancePartiallyRequest(ctx, projectId, region, instanceId).UpdateInstancePartiallyRequestPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
waitResp, err := wait.PartialUpdateInstanceWaitHandler(ctx, r.client, projectId, region, instanceId).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, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", 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, "Postgresflex instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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.DeleteInstanceRequest(ctx, projectId, region, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
_, err = wait.DeleteInstanceWaitHandler(ctx, r.client, projectId, region, instanceId).SetTimeout(45 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) 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,
|
||||
"Error importing instance",
|
||||
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("region"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "Postgres Flex instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(ctx context.Context, resp *postgresflexalpha.GetInstanceResponse, model *Model, flavor *flavorModel, storage *storageModel, region string) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
instance := resp
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.Id != nil {
|
||||
instanceId = *instance.Id
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
var aclList basetypes.ListValue
|
||||
var diags diag.Diagnostics
|
||||
if instance.Acl == nil {
|
||||
aclList = types.ListNull(types.StringType)
|
||||
} else {
|
||||
respACL := *instance.Acl
|
||||
modelACL, err := utils.ListValuetoStringSlice(model.ACL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reconciledACL := utils.ReconcileStringSlices(modelACL, respACL)
|
||||
|
||||
aclList, diags = types.ListValueFrom(ctx, types.StringType, reconciledACL)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("mapping ACL: %w", core.DiagsToError(diags))
|
||||
}
|
||||
}
|
||||
|
||||
var flavorValues map[string]attr.Value
|
||||
if instance.FlavorId == nil {
|
||||
flavorValues = map[string]attr.Value{
|
||||
"id": flavor.Id,
|
||||
"description": flavor.Description,
|
||||
"cpu": flavor.CPU,
|
||||
"ram": flavor.RAM,
|
||||
}
|
||||
} else {
|
||||
// TODO
|
||||
//flavorValues = map[string]attr.Value{
|
||||
// "id": types.StringValue(*instance.FlavorId),
|
||||
// "description": types.StringValue(*instance.Flavor.Description),
|
||||
// "cpu": types.Int64PointerValue(instance.Flavor.Cpu),
|
||||
// "ram": types.Int64PointerValue(instance.Flavor.Memory),
|
||||
//}
|
||||
}
|
||||
flavorObject, diags := types.ObjectValue(flavorTypes, flavorValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("creating flavor: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
var storageValues map[string]attr.Value
|
||||
if instance.Storage == nil {
|
||||
storageValues = map[string]attr.Value{
|
||||
"class": storage.Class,
|
||||
"size": storage.Size,
|
||||
}
|
||||
} else {
|
||||
storageValues = map[string]attr.Value{
|
||||
"class": types.StringValue(*instance.Storage.PerformanceClass),
|
||||
"size": types.Int64PointerValue(instance.Storage.Size),
|
||||
}
|
||||
}
|
||||
storageObject, diags := types.ObjectValue(storageTypes, storageValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("creating storage: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, instanceId)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.ACL = aclList
|
||||
model.BackupSchedule = types.StringPointerValue(instance.BackupSchedule)
|
||||
model.Flavor = flavorObject
|
||||
// TODO - verify working
|
||||
model.Replicas = types.Int64Value(int64(*instance.Replicas))
|
||||
model.Storage = storageObject
|
||||
model.Version = types.StringPointerValue(instance.Version)
|
||||
model.Region = types.StringValue(region)
|
||||
//model.Encryption = types.ObjectValue()
|
||||
//model.Network = networkModel
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, acl []string, flavor *flavorModel, storage *storageModel, enc *encryptionModel, net *networkModel) (*postgresflexalpha.CreateInstanceRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if acl == nil {
|
||||
return nil, fmt.Errorf("nil acl")
|
||||
}
|
||||
if flavor == nil {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
if storage == nil {
|
||||
return nil, fmt.Errorf("nil storage")
|
||||
}
|
||||
|
||||
replVal := int32(model.Replicas.ValueInt64())
|
||||
return &postgresflexalpha.CreateInstanceRequestPayload{
|
||||
// TODO - verify working
|
||||
Acl: &[]string{
|
||||
strings.Join(acl, ","),
|
||||
},
|
||||
BackupSchedule: conversion.StringValueToPointer(model.BackupSchedule),
|
||||
FlavorId: conversion.StringValueToPointer(flavor.Id),
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
// TODO - verify working
|
||||
Replicas: postgresflexalpha.CreateInstanceRequestPayloadGetReplicasAttributeType(&replVal),
|
||||
// TODO - verify working
|
||||
Storage: postgresflexalpha.CreateInstanceRequestPayloadGetStorageAttributeType(&postgresflexalpha.Storage{
|
||||
PerformanceClass: conversion.StringValueToPointer(storage.Class),
|
||||
Size: conversion.Int64ValueToPointer(storage.Size),
|
||||
}),
|
||||
Version: conversion.StringValueToPointer(model.Version),
|
||||
// TODO - verify working
|
||||
Encryption: postgresflexalpha.CreateInstanceRequestPayloadGetEncryptionAttributeType(
|
||||
&postgresflexalpha.InstanceEncryption{
|
||||
KekKeyId: conversion.StringValueToPointer(enc.KeyId), // model.Encryption.Attributes(),
|
||||
KekKeyRingId: conversion.StringValueToPointer(enc.KeyRingId),
|
||||
KekKeyVersion: conversion.StringValueToPointer(enc.KeyVersion),
|
||||
ServiceAccount: conversion.StringValueToPointer(enc.ServiceAccount),
|
||||
},
|
||||
),
|
||||
Network: &postgresflexalpha.InstanceNetwork{
|
||||
AccessScope: postgresflexalpha.InstanceNetworkGetAccessScopeAttributeType(
|
||||
conversion.StringValueToPointer(net.AccessScope),
|
||||
),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, acl []string, flavor *flavorModel, storage *storageModel) (*postgresflexalpha.UpdateInstancePartiallyRequestPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if acl == nil {
|
||||
return nil, fmt.Errorf("nil acl")
|
||||
}
|
||||
if flavor == nil {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
if storage == nil {
|
||||
return nil, fmt.Errorf("nil storage")
|
||||
}
|
||||
|
||||
return &postgresflexalpha.UpdateInstancePartiallyRequestPayload{
|
||||
//Acl: postgresflexalpha.UpdateInstancePartiallyRequestPayloadGetAclAttributeType{
|
||||
// Items: &acl,
|
||||
//},
|
||||
BackupSchedule: conversion.StringValueToPointer(model.BackupSchedule),
|
||||
FlavorId: conversion.StringValueToPointer(flavor.Id),
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
//Replicas: conversion.Int64ValueToPointer(model.Replicas),
|
||||
Storage: &postgresflexalpha.StorageUpdate{
|
||||
Size: conversion.Int64ValueToPointer(storage.Size),
|
||||
},
|
||||
Version: conversion.StringValueToPointer(model.Version),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type postgresflexClient interface {
|
||||
GetFlavorsRequestExecute(ctx context.Context, projectId string, region string) (*postgresflexalpha.GetFlavorsResponse, error)
|
||||
}
|
||||
|
||||
func loadFlavorId(ctx context.Context, client postgresflexClient, model *Model, flavor *flavorModel) error {
|
||||
if model == nil {
|
||||
return fmt.Errorf("nil model")
|
||||
}
|
||||
if flavor == nil {
|
||||
return fmt.Errorf("nil flavor")
|
||||
}
|
||||
cpu := conversion.Int64ValueToPointer(flavor.CPU)
|
||||
if cpu == nil {
|
||||
return fmt.Errorf("nil CPU")
|
||||
}
|
||||
ram := conversion.Int64ValueToPointer(flavor.RAM)
|
||||
if ram == nil {
|
||||
return fmt.Errorf("nil RAM")
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
res, err := client.GetFlavorsRequestExecute(ctx, projectId, region)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listing postgresflex flavors: %w", err)
|
||||
}
|
||||
|
||||
avl := ""
|
||||
if res.Flavors == nil {
|
||||
return fmt.Errorf("finding flavors for project %s", projectId)
|
||||
}
|
||||
for _, f := range *res.Flavors {
|
||||
if f.Id == nil || f.Cpu == nil || f.Memory == nil {
|
||||
continue
|
||||
}
|
||||
if *f.Cpu == *cpu && *f.Memory == *ram {
|
||||
flavor.Id = types.StringValue(*f.Id)
|
||||
flavor.Description = types.StringValue(*f.Description)
|
||||
break
|
||||
}
|
||||
avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM", avl, *f.Cpu, *f.Memory)
|
||||
}
|
||||
if flavor.Id.ValueString() == "" {
|
||||
return fmt.Errorf("couldn't find flavor, available specs are:%s", avl)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,770 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"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/postgresflex"
|
||||
)
|
||||
|
||||
type postgresFlexClientMocked struct {
|
||||
returnError bool
|
||||
getFlavorsResp *postgresflex.ListFlavorsResponse
|
||||
}
|
||||
|
||||
func (c *postgresFlexClientMocked) ListFlavorsExecute(_ context.Context, _, _ string) (*postgresflex.ListFlavorsResponse, error) {
|
||||
if c.returnError {
|
||||
return nil, fmt.Errorf("get flavors failed")
|
||||
}
|
||||
|
||||
return c.getFlavorsResp, nil
|
||||
}
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
state Model
|
||||
input *postgresflex.InstanceResponse
|
||||
flavor *flavorModel
|
||||
storage *storageModel
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.Instance{},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringNull(),
|
||||
ACL: types.ListNull(types.StringType),
|
||||
BackupSchedule: types.StringNull(),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Null(),
|
||||
"ram": types.Int64Null(),
|
||||
}),
|
||||
Replicas: types.Int64Null(),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringNull(),
|
||||
"size": types.Int64Null(),
|
||||
}),
|
||||
Version: types.StringNull(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.Instance{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: &postgresflex.Flavor{
|
||||
Cpu: utils.Ptr(int64(12)),
|
||||
Description: utils.Ptr("description"),
|
||||
Id: utils.Ptr("flavor_id"),
|
||||
Memory: utils.Ptr(int64(34)),
|
||||
},
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: &postgresflex.Storage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int64(78)),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip1"),
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringValue("flavor_id"),
|
||||
"description": types.StringValue("description"),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values_no_flavor_and_storage",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.Instance{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: nil,
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: nil,
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(12),
|
||||
RAM: types.Int64Value(34),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(78),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip1"),
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"acl_unordered",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
types.StringValue("ip1"),
|
||||
}),
|
||||
},
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.Instance{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{
|
||||
"",
|
||||
"ip1",
|
||||
"ip2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: nil,
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: nil,
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(12),
|
||||
RAM: types.Int64Value(34),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(78),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
types.StringValue("ip1"),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&postgresflex.InstanceResponse{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
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.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(tt.state, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputAcl []string
|
||||
inputFlavor *flavorModel
|
||||
inputStorage *storageModel
|
||||
expected *postgresflex.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &postgresflex.Storage{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Name: types.StringValue("name"),
|
||||
Replicas: types.Int64Value(12),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("flavor_id"),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(34),
|
||||
},
|
||||
&postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(12)),
|
||||
Storage: &postgresflex.Storage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int64(34)),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
BackupSchedule: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Replicas: types.Int64Value(2123456789),
|
||||
Version: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringNull(),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringNull(),
|
||||
Size: types.Int64Null(),
|
||||
},
|
||||
&postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Replicas: utils.Ptr(int64(2123456789)),
|
||||
Storage: &postgresflex.Storage{
|
||||
Class: nil,
|
||||
Size: nil,
|
||||
},
|
||||
Version: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_acl",
|
||||
&Model{},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_flavor",
|
||||
&Model{},
|
||||
[]string{},
|
||||
nil,
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_storage",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputAcl, tt.inputFlavor, tt.inputStorage)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputAcl []string
|
||||
inputFlavor *flavorModel
|
||||
inputStorage *storageModel
|
||||
expected *postgresflex.PartialUpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&postgresflex.PartialUpdateInstancePayload{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &postgresflex.Storage{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Name: types.StringValue("name"),
|
||||
Replicas: types.Int64Value(12),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("flavor_id"),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(34),
|
||||
},
|
||||
&postgresflex.PartialUpdateInstancePayload{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(12)),
|
||||
Storage: &postgresflex.Storage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int64(34)),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
BackupSchedule: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Replicas: types.Int64Value(2123456789),
|
||||
Version: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringNull(),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringNull(),
|
||||
Size: types.Int64Null(),
|
||||
},
|
||||
&postgresflex.PartialUpdateInstancePayload{
|
||||
Acl: &postgresflex.ACL{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Replicas: utils.Ptr(int64(2123456789)),
|
||||
Storage: &postgresflex.Storage{
|
||||
Class: nil,
|
||||
Size: nil,
|
||||
},
|
||||
Version: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_acl",
|
||||
&Model{},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_flavor",
|
||||
&Model{},
|
||||
[]string{},
|
||||
nil,
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_storage",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputAcl, tt.inputFlavor, tt.inputStorage)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFlavorId(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
inputFlavor *flavorModel
|
||||
mockedResp *postgresflex.ListFlavorsResponse
|
||||
expected *flavorModel
|
||||
getFlavorsFails bool
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"ok_flavor",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&postgresflex.ListFlavorsResponse{
|
||||
Flavors: &[]postgresflex.Flavor{
|
||||
{
|
||||
Id: utils.Ptr("fid-1"),
|
||||
Cpu: utils.Ptr(int64(2)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(8)),
|
||||
},
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("fid-1"),
|
||||
Description: types.StringValue("description"),
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"ok_flavor_2",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&postgresflex.ListFlavorsResponse{
|
||||
Flavors: &[]postgresflex.Flavor{
|
||||
{
|
||||
Id: utils.Ptr("fid-1"),
|
||||
Cpu: utils.Ptr(int64(2)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(8)),
|
||||
},
|
||||
{
|
||||
Id: utils.Ptr("fid-2"),
|
||||
Cpu: utils.Ptr(int64(1)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(4)),
|
||||
},
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("fid-1"),
|
||||
Description: types.StringValue("description"),
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"no_matching_flavor",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&postgresflex.ListFlavorsResponse{
|
||||
Flavors: &[]postgresflex.Flavor{
|
||||
{
|
||||
Id: utils.Ptr("fid-1"),
|
||||
Cpu: utils.Ptr(int64(1)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(8)),
|
||||
},
|
||||
{
|
||||
Id: utils.Ptr("fid-2"),
|
||||
Cpu: utils.Ptr(int64(1)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(4)),
|
||||
},
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&postgresflex.ListFlavorsResponse{},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"error_response",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&postgresflex.ListFlavorsResponse{},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
true,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
client := &postgresFlexClientMocked{
|
||||
returnError: tt.getFlavorsFails,
|
||||
getFlavorsResp: tt.mockedResp,
|
||||
}
|
||||
model := &Model{
|
||||
ProjectId: types.StringValue("pid"),
|
||||
}
|
||||
flavorModel := &flavorModel{
|
||||
CPU: tt.inputFlavor.CPU,
|
||||
RAM: tt.inputFlavor.RAM,
|
||||
}
|
||||
err := loadFlavorId(context.Background(), client, model, flavorModel)
|
||||
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(flavorModel, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
)
|
||||
|
||||
type useStateForUnknownIfFlavorUnchangedModifier struct {
|
||||
Req resource.SchemaRequest
|
||||
}
|
||||
|
||||
// UseStateForUnknownIfFlavorUnchanged returns a plan modifier similar to UseStateForUnknown
|
||||
// if the RAM and CPU values are not changed in the plan. Otherwise, the plan modifier does nothing.
|
||||
func UseStateForUnknownIfFlavorUnchanged(req resource.SchemaRequest) planmodifier.String {
|
||||
return useStateForUnknownIfFlavorUnchangedModifier{
|
||||
Req: req,
|
||||
}
|
||||
}
|
||||
|
||||
func (m useStateForUnknownIfFlavorUnchangedModifier) Description(context.Context) string {
|
||||
return "UseStateForUnknownIfFlavorUnchanged returns a plan modifier similar to UseStateForUnknown if the RAM and CPU values are not changed in the plan. Otherwise, the plan modifier does nothing."
|
||||
}
|
||||
|
||||
func (m useStateForUnknownIfFlavorUnchangedModifier) MarkdownDescription(ctx context.Context) string {
|
||||
return m.Description(ctx)
|
||||
}
|
||||
|
||||
func (m useStateForUnknownIfFlavorUnchangedModifier) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Do nothing if there is no state value.
|
||||
if req.StateValue.IsNull() {
|
||||
return
|
||||
}
|
||||
|
||||
// Do nothing if there is a known planned value.
|
||||
if !req.PlanValue.IsUnknown() {
|
||||
return
|
||||
}
|
||||
|
||||
// Do nothing if there is an unknown configuration value, otherwise interpolation gets messed up.
|
||||
if req.ConfigValue.IsUnknown() {
|
||||
return
|
||||
}
|
||||
|
||||
// The above checks are taken from the UseStateForUnknown plan modifier implementation
|
||||
// (https://github.com/hashicorp/terraform-plugin-framework/blob/main/resource/schema/stringplanmodifier/use_state_for_unknown.go#L38)
|
||||
|
||||
var stateModel Model
|
||||
diags := req.State.Get(ctx, &stateModel)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
var stateFlavor = &flavorModel{}
|
||||
if !(stateModel.Flavor.IsNull() || stateModel.Flavor.IsUnknown()) {
|
||||
diags = stateModel.Flavor.As(ctx, stateFlavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var planModel Model
|
||||
diags = req.Plan.Get(ctx, &planModel)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
var planFlavor = &flavorModel{}
|
||||
if !(planModel.Flavor.IsNull() || planModel.Flavor.IsUnknown()) {
|
||||
diags = planModel.Flavor.As(ctx, planFlavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if planFlavor.CPU == stateFlavor.CPU && planFlavor.RAM == stateFlavor.RAM {
|
||||
resp.PlanValue = req.StateValue
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,369 @@
|
|||
package postgresflex_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex/wait"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": fmt.Sprintf("tf-acc-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlphaNum)),
|
||||
"acl": "192.168.0.0/16",
|
||||
"backup_schedule": "00 16 * * *",
|
||||
"backup_schedule_updated": "00 12 * * *",
|
||||
"flavor_cpu": "2",
|
||||
"flavor_ram": "4",
|
||||
"flavor_description": "Small, Compute optimized",
|
||||
"replicas": "1",
|
||||
"storage_class": "premium-perf12-stackit",
|
||||
"storage_size": "5",
|
||||
"version": "14",
|
||||
"flavor_id": "2.4",
|
||||
}
|
||||
|
||||
// User resource data
|
||||
var userResource = map[string]string{
|
||||
"username": fmt.Sprintf("tfaccuser%s", acctest.RandStringFromCharSet(4, acctest.CharSetAlpha)),
|
||||
"role": "createdb",
|
||||
"project_id": instanceResource["project_id"],
|
||||
}
|
||||
|
||||
// Database resource data
|
||||
var databaseResource = map[string]string{
|
||||
"name": fmt.Sprintf("tfaccdb%s", acctest.RandStringFromCharSet(4, acctest.CharSetAlphaNum)),
|
||||
}
|
||||
|
||||
func configResources(backupSchedule string, region *string) string {
|
||||
var regionConfig string
|
||||
if region != nil {
|
||||
regionConfig = fmt.Sprintf(`region = %q`, *region)
|
||||
}
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_postgresflex_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
acl = ["%s"]
|
||||
backup_schedule = "%s"
|
||||
flavor = {
|
||||
cpu = %s
|
||||
ram = %s
|
||||
}
|
||||
replicas = %s
|
||||
storage = {
|
||||
class = "%s"
|
||||
size = %s
|
||||
}
|
||||
version = "%s"
|
||||
%s
|
||||
}
|
||||
|
||||
resource "stackit_postgresflex_user" "user" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
username = "%s"
|
||||
roles = ["%s"]
|
||||
}
|
||||
|
||||
resource "stackit_postgresflex_database" "database" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
name = "%s"
|
||||
owner = stackit_postgresflex_user.user.username
|
||||
}
|
||||
`,
|
||||
testutil.PostgresFlexProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["acl"],
|
||||
backupSchedule,
|
||||
instanceResource["flavor_cpu"],
|
||||
instanceResource["flavor_ram"],
|
||||
instanceResource["replicas"],
|
||||
instanceResource["storage_class"],
|
||||
instanceResource["storage_size"],
|
||||
instanceResource["version"],
|
||||
regionConfig,
|
||||
userResource["username"],
|
||||
userResource["role"],
|
||||
databaseResource["name"],
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccPostgresFlexFlexResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckPostgresFlexDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: configResources(instanceResource["backup_schedule"], &testutil.Region),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.0", instanceResource["acl"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.description"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "backup_schedule", instanceResource["backup_schedule"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.cpu", instanceResource["flavor_cpu"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.ram", instanceResource["flavor_ram"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "replicas", instanceResource["replicas"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.class", instanceResource["storage_class"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.size", instanceResource["storage_size"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "region", testutil.Region),
|
||||
|
||||
// User
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_user.user", "project_id",
|
||||
"stackit_postgresflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_user.user", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_user.user", "password"),
|
||||
|
||||
// Database
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_database.database", "project_id",
|
||||
"stackit_postgresflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_database.database", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_database.database", "name", databaseResource["name"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_database.database", "owner",
|
||||
"stackit_postgresflex_user.user", "username",
|
||||
),
|
||||
),
|
||||
},
|
||||
// data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_postgresflex_instance" "instance" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_postgresflex_user" "user" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
user_id = stackit_postgresflex_user.user.user_id
|
||||
}
|
||||
|
||||
data "stackit_postgresflex_database" "database" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
database_id = stackit_postgresflex_database.database.database_id
|
||||
}
|
||||
`,
|
||||
configResources(instanceResource["backup_schedule"], nil),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_instance.instance", "project_id",
|
||||
"stackit_postgresflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_instance.instance", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_user.user", "instance_id",
|
||||
"stackit_postgresflex_user.user", "instance_id",
|
||||
),
|
||||
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "acl.0", instanceResource["acl"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "backup_schedule", instanceResource["backup_schedule"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.id", instanceResource["flavor_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.description", instanceResource["flavor_description"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.cpu", instanceResource["flavor_cpu"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.ram", instanceResource["flavor_ram"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "replicas", instanceResource["replicas"]),
|
||||
|
||||
// User data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "project_id", userResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "username", userResource["username"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "roles.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "roles.0", userResource["role"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "port"),
|
||||
|
||||
// Database data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_database.database", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_database.database", "name", databaseResource["name"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_database.database", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_database.database", "owner",
|
||||
"data.stackit_postgresflex_user.user", "username",
|
||||
),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_postgresflex_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresflex_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresflex_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, testutil.Region, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"password"},
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_postgresflex_user.user",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresflex_user.user"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresflex_user.user")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
userId, ok := r.Primary.Attributes["user_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute user_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s,%s", testutil.ProjectId, testutil.Region, instanceId, userId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"password", "uri"},
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_postgresflex_database.database",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresflex_database.database"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresflex_database.database")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
databaseId, ok := r.Primary.Attributes["database_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute database_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s,%s", testutil.ProjectId, testutil.Region, instanceId, databaseId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: configResources(instanceResource["backup_schedule_updated"], nil),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.0", instanceResource["acl"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "backup_schedule", instanceResource["backup_schedule_updated"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.description"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.cpu", instanceResource["flavor_cpu"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.ram", instanceResource["flavor_ram"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "replicas", instanceResource["replicas"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.class", instanceResource["storage_class"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.size", instanceResource["storage_size"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "version", instanceResource["version"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckPostgresFlexDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *postgresflex.APIClient
|
||||
var err error
|
||||
if testutil.PostgresFlexCustomEndpoint == "" {
|
||||
client, err = postgresflex.NewAPIClient()
|
||||
} else {
|
||||
client, err = postgresflex.NewAPIClient(
|
||||
config.WithEndpoint(testutil.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_postgresflex_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: = "[project_id],[region],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[2]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.ListInstances(ctx, testutil.ProjectId, testutil.Region).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
items := *instancesResp.Items
|
||||
for i := range items {
|
||||
if items[i].Id == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *items[i].Id) {
|
||||
err := client.ForceDeleteInstanceExecute(ctx, testutil.ProjectId, testutil.Region, *items[i].Id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("deleting instance %s during CheckDestroy: %w", *items[i].Id, err)
|
||||
}
|
||||
_, err = wait.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, testutil.Region, *items[i].Id).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("deleting instance %s during CheckDestroy: waiting for deletion %w", *items[i].Id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
230
stackit/internal/services/postgresflexalpha/user/datasource.go
Normal file
230
stackit/internal/services/postgresflexalpha/user/datasource.go
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
postgresflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"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"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &userDataSource{}
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
// NewUserDataSource is a helper function to simplify the provider implementation.
|
||||
func NewUserDataSource() datasource.DataSource {
|
||||
return &userDataSource{}
|
||||
}
|
||||
|
||||
// userDataSource is the data source implementation.
|
||||
type userDataSource struct {
|
||||
client *postgresflex.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 + "_postgresflex_user"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
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 {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex user client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres 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 PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Description: descriptions["user_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
// the region cannot be found automatically, so it has to be passed
|
||||
Optional: true,
|
||||
Description: descriptions["region"],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
var model DataSourceModel
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
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, 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),
|
||||
map[int]string{
|
||||
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
|
||||
},
|
||||
)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// 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))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex user read")
|
||||
}
|
||||
|
||||
func mapDataSourceFields(userResp *postgresflex.GetUserResponse, model *DataSourceModel, region string) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
var userId string
|
||||
if model.UserId.ValueString() != "" {
|
||||
userId = model.UserId.ValueString()
|
||||
} 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.UserId = types.StringValue(userId)
|
||||
model.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Region = types.StringValue(region)
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"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/postgresflex"
|
||||
)
|
||||
|
||||
func TestMapDataSourceFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.GetUserResponse
|
||||
region string
|
||||
expected DataSourceModel
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{},
|
||||
},
|
||||
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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Username: utils.Ptr("username"),
|
||||
Host: utils.Ptr("host"),
|
||||
Port: utils.Ptr(int64(1234)),
|
||||
},
|
||||
},
|
||||
testRegion,
|
||||
DataSourceModel{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int64(2123456789)),
|
||||
},
|
||||
},
|
||||
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.SetValueMust(types.StringType, []attr.Value{}),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
DataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
DataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{},
|
||||
},
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
577
stackit/internal/services/postgresflexalpha/user/resource.go
Normal file
577
stackit/internal/services/postgresflexalpha/user/resource.go
Normal file
|
|
@ -0,0 +1,577 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
postgresflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"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/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"
|
||||
"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/postgresflex"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex/wait"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &userResource{}
|
||||
_ resource.ResourceWithConfigure = &userResource{}
|
||||
_ resource.ResourceWithImportState = &userResource{}
|
||||
_ resource.ResourceWithModifyPlan = &userResource{}
|
||||
)
|
||||
|
||||
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"`
|
||||
Uri types.String `tfsdk:"uri"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
}
|
||||
|
||||
// NewUserResource is a helper function to simplify the provider implementation.
|
||||
func NewUserResource() resource.Resource {
|
||||
return &userResource{}
|
||||
}
|
||||
|
||||
// userResource is the resource implementation.
|
||||
type userResource struct {
|
||||
client *postgresflex.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// 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
|
||||
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.GetRegion(), resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *userResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_user"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := postgresflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex user client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
rolesOptions := []string{"login", "createdb"}
|
||||
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres 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 PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"roles": "Database access levels for the user. " + utils.FormatPossibleValues(rolesOptions...),
|
||||
"region": "The resource region. If not defined, the provider region is used.",
|
||||
}
|
||||
|
||||
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(),
|
||||
},
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Description: descriptions["user_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
Description: descriptions["roles"],
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
Validators: []validator.Set{
|
||||
setvalidator.ValueStringsAre(
|
||||
stringvalidator.OneOf("login", "createdb"),
|
||||
),
|
||||
},
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"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(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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 roles []string
|
||||
if !(model.Roles.IsNull() || model.Roles.IsUnknown()) {
|
||||
diags = model.Roles.ElementsAs(ctx, &roles, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, roles)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new user
|
||||
userResp, err := r.client.CreateUser(ctx, projectId, region, instanceId).CreateUserPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
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")
|
||||
return
|
||||
}
|
||||
userId := *userResp.Item.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))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex user created")
|
||||
}
|
||||
|
||||
// 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
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
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, 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
|
||||
if ok && oapiErr.StatusCode == http.StatusNotFound {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// 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))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex user read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *userResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
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)
|
||||
|
||||
// Retrieve values from state
|
||||
var stateModel Model
|
||||
diags = req.State.Get(ctx, &stateModel)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
var roles []string
|
||||
if !(model.Roles.IsNull() || model.Roles.IsUnknown()) {
|
||||
diags = model.Roles.ElementsAs(ctx, &roles, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, roles)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", fmt.Sprintf("Updating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Update existing instance
|
||||
err = r.client.UpdateUser(ctx, projectId, region, instanceId, userId).UpdateUserPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
userResp, err := r.client.GetUser(ctx, projectId, region, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(userResp, &stateModel, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, stateModel)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex user 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
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
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)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteUser(ctx, projectId, region, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
_, err = wait.DeleteUserWaitHandler(ctx, r.client, projectId, region, instanceId, userId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex user deleted")
|
||||
}
|
||||
|
||||
// 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) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
|
||||
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),
|
||||
)
|
||||
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])...)
|
||||
core.LogAndAddWarning(ctx, &resp.Diagnostics,
|
||||
"Postgresflex user imported with empty password and empty uri",
|
||||
"The user password and uri are not imported as they are only available upon creation of a new user. The password and uri fields will be empty.",
|
||||
)
|
||||
tflog.Info(ctx, "Postgresflex user state imported")
|
||||
}
|
||||
|
||||
func mapFieldsCreate(userResp *postgresflex.CreateUserResponse, model *Model, region string) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
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.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Password == nil {
|
||||
return fmt.Errorf("user password not present")
|
||||
}
|
||||
model.Password = types.StringValue(*user.Password)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Uri = types.StringPointerValue(user.Uri)
|
||||
model.Region = types.StringValue(region)
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapFields(userResp *postgresflex.GetUserResponse, model *Model, region string) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
var userId string
|
||||
if model.UserId.ValueString() != "" {
|
||||
userId = model.UserId.ValueString()
|
||||
} 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.UserId = types.StringValue(userId)
|
||||
model.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Region = types.StringValue(region)
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, roles []string) (*postgresflex.CreateUserPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if roles == nil {
|
||||
return nil, fmt.Errorf("nil roles")
|
||||
}
|
||||
|
||||
return &postgresflex.CreateUserPayload{
|
||||
Roles: &roles,
|
||||
Username: conversion.StringValueToPointer(model.Username),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, roles []string) (*postgresflex.UpdateUserPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if roles == nil {
|
||||
return nil, fmt.Errorf("nil roles")
|
||||
}
|
||||
|
||||
return &postgresflex.UpdateUserPayload{
|
||||
Roles: &roles,
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,470 @@
|
|||
package postgresflexa
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"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/postgresflex"
|
||||
)
|
||||
|
||||
func TestMapFieldsCreate(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.CreateUserResponse
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.User{
|
||||
Id: utils.Ptr("uid"),
|
||||
Password: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
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.SetNull(types.StringType),
|
||||
Password: types.StringValue(""),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Uri: types.StringNull(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.User{
|
||||
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)),
|
||||
Uri: utils.Ptr("uri"),
|
||||
},
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
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),
|
||||
Uri: types.StringValue("uri"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.User{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int64(2123456789)),
|
||||
Uri: nil,
|
||||
},
|
||||
},
|
||||
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),
|
||||
Uri: types.StringNull(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.CreateUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.User{},
|
||||
},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_password",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.User{
|
||||
Id: utils.Ptr("uid"),
|
||||
},
|
||||
},
|
||||
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,
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.GetUserResponse
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{},
|
||||
},
|
||||
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.SetNull(types.StringType),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{
|
||||
Roles: &[]string{
|
||||
"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"),
|
||||
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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
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{}),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.GetUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.GetUserResponse{
|
||||
Item: &postgresflex.UserResponse{},
|
||||
},
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputRoles []string
|
||||
expected *postgresflex.CreateUserPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&postgresflex.CreateUserPayload{
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&postgresflex.CreateUserPayload{
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&postgresflex.CreateUserPayload{
|
||||
Roles: &[]string{
|
||||
"",
|
||||
},
|
||||
Username: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&Model{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputRoles []string
|
||||
expected *postgresflex.UpdateUserPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&postgresflex.UpdateUserPayload{
|
||||
Roles: &[]string{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&postgresflex.UpdateUserPayload{
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&postgresflex.UpdateUserPayload{
|
||||
Roles: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&Model{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
32
stackit/internal/services/postgresflexalpha/utils/util.go
Normal file
32
stackit/internal/services/postgresflexalpha/utils/util.go
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
postgresflex "github.com/stackitcloud/terraform-provider-stackit/pkg/postgresflexalpha"
|
||||
|
||||
"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) *postgresflex.APIClient {
|
||||
apiClientConfigOptions := []config.ConfigurationOption{
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
utils.UserAgentConfigOption(providerData.Version),
|
||||
}
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClientConfigOptions = append(apiClientConfigOptions, config.WithEndpoint(providerData.PostgresFlexCustomEndpoint))
|
||||
} else {
|
||||
apiClientConfigOptions = append(apiClientConfigOptions, config.WithRegion(providerData.GetRegion()))
|
||||
}
|
||||
apiClient, err := postgresflex.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
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
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/postgresflex"
|
||||
"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://postgresflex-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 *postgresflex.APIClient
|
||||
}{
|
||||
{
|
||||
name: "default endpoint",
|
||||
args: args{
|
||||
providerData: &core.ProviderData{
|
||||
Version: testVersion,
|
||||
},
|
||||
},
|
||||
expected: func() *postgresflex.APIClient {
|
||||
apiClient, err := postgresflex.NewAPIClient(
|
||||
config.WithRegion("eu01"),
|
||||
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,
|
||||
PostgresFlexCustomEndpoint: testCustomEndpoint,
|
||||
},
|
||||
},
|
||||
expected: func() *postgresflex.APIClient {
|
||||
apiClient, err := postgresflex.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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,238 @@
|
|||
package sqlserverflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"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/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"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"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *sqlserverflex.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_sqlserverflex_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "SQLServer Flex instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
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`,`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{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"acl": schema.ListAttribute{
|
||||
Description: descriptions["acl"],
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"backup_schedule": schema.StringAttribute{
|
||||
Description: descriptions["backup_schedule"],
|
||||
Computed: true,
|
||||
},
|
||||
"flavor": schema.SingleNestedAttribute{
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"replicas": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"storage": schema.SingleNestedAttribute{
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"size": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"options": schema.SingleNestedAttribute{
|
||||
Description: descriptions["options"],
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"edition": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"retention_days": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
// the region cannot be found, so it has to be passed
|
||||
Optional: true,
|
||||
Description: descriptions["region"],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId, region).Execute()
|
||||
if err != nil {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading instance",
|
||||
fmt.Sprintf("Instance with ID %q does not exist in project %q.", instanceId, projectId),
|
||||
map[int]string{
|
||||
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
|
||||
},
|
||||
)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var options = &optionsModel{}
|
||||
if !(model.Options.IsNull() || model.Options.IsUnknown()) {
|
||||
diags = model.Options.As(ctx, options, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SQLServer Flex instance read")
|
||||
}
|
||||
|
|
@ -0,0 +1,899 @@
|
|||
package sqlserverflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
sqlserverflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/sqlserverflex/utils"
|
||||
|
||||
"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"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"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/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/objectplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
coreUtils "github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex/wait"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
_ resource.ResourceWithModifyPlan = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
ACL types.List `tfsdk:"acl"`
|
||||
BackupSchedule types.String `tfsdk:"backup_schedule"`
|
||||
Flavor types.Object `tfsdk:"flavor"`
|
||||
Storage types.Object `tfsdk:"storage"`
|
||||
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
|
||||
type flavorModel struct {
|
||||
Id types.String `tfsdk:"id"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
CPU types.Int64 `tfsdk:"cpu"`
|
||||
RAM types.Int64 `tfsdk:"ram"`
|
||||
}
|
||||
|
||||
// Types corresponding to flavorModel
|
||||
var flavorTypes = map[string]attr.Type{
|
||||
"id": basetypes.StringType{},
|
||||
"description": basetypes.StringType{},
|
||||
"cpu": basetypes.Int64Type{},
|
||||
"ram": basetypes.Int64Type{},
|
||||
}
|
||||
|
||||
// Struct corresponding to Model.Storage
|
||||
type storageModel struct {
|
||||
Class types.String `tfsdk:"class"`
|
||||
Size types.Int64 `tfsdk:"size"`
|
||||
}
|
||||
|
||||
// Types corresponding to storageModel
|
||||
var storageTypes = map[string]attr.Type{
|
||||
"class": basetypes.StringType{},
|
||||
"size": basetypes.Int64Type{},
|
||||
}
|
||||
|
||||
// Struct corresponding to Model.Options
|
||||
type optionsModel struct {
|
||||
Edition types.String `tfsdk:"edition"`
|
||||
RetentionDays types.Int64 `tfsdk:"retention_days"`
|
||||
}
|
||||
|
||||
// Types corresponding to optionsModel
|
||||
var optionsTypes = map[string]attr.Type{
|
||||
"edition": basetypes.StringType{},
|
||||
"retention_days": basetypes.Int64Type{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *sqlserverflex.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_sqlserverflex_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "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.GetRegion(), 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`,`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{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile("^[a-z]([-a-z0-9]*[a-z0-9])?$"),
|
||||
"must start with a letter, must have lower case letters, numbers or hyphens, and no hyphen at the end",
|
||||
),
|
||||
},
|
||||
},
|
||||
"acl": schema.ListAttribute{
|
||||
Description: descriptions["acl"],
|
||||
ElementType: types.StringType,
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.List{
|
||||
listplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"backup_schedule": schema.StringAttribute{
|
||||
Description: descriptions["backup_schedule"],
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"flavor": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"replicas": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"storage": schema.SingleNestedAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Object{
|
||||
objectplanmodifier.RequiresReplace(),
|
||||
objectplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"size": schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.RequiresReplace(),
|
||||
int64planmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"options": schema.SingleNestedAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Object{
|
||||
objectplanmodifier.RequiresReplace(),
|
||||
objectplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"edition": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"retention_days": schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.RequiresReplace(),
|
||||
int64planmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"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(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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()) {
|
||||
diags = model.ACL.ElementsAs(ctx, &acl, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
err := loadFlavorId(ctx, r.client, &model, flavor)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading flavor ID: %v", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var options = &optionsModel{}
|
||||
if !(model.Options.IsNull() || model.Options.IsUnknown()) {
|
||||
diags = model.Options.As(ctx, options, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, acl, flavor, storage, options)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
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
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
instanceId := *createResp.Id
|
||||
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, 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, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// After the instance creation, database might not be ready to accept connections immediately.
|
||||
// That is why we add a sleep
|
||||
time.Sleep(120 * time.Second)
|
||||
|
||||
tflog.Info(ctx, "SQLServer Flex instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) 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)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.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()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var options = &optionsModel{}
|
||||
if !(model.Options.IsNull() || model.Options.IsUnknown()) {
|
||||
diags = model.Options.As(ctx, options, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// Map response body to schema
|
||||
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
|
||||
}
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SQLServer Flex instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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()) {
|
||||
diags = model.ACL.ElementsAs(ctx, &acl, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
err := loadFlavorId(ctx, r.client, &model, flavor)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading flavor ID: %v", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var options = &optionsModel{}
|
||||
if !(model.Options.IsNull() || model.Options.IsUnknown()) {
|
||||
diags = model.Options.As(ctx, options, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, acl, flavor)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
_, 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
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(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, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", 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, "SQLServer Flex instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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, region).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(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
|
||||
}
|
||||
tflog.Info(ctx, "SQLServer Flex instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) 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,
|
||||
"Error importing instance",
|
||||
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("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, region string) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if resp.Item == nil {
|
||||
return fmt.Errorf("no instance provided")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
instance := resp.Item
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.Id != nil {
|
||||
instanceId = *instance.Id
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
var aclList basetypes.ListValue
|
||||
var diags diag.Diagnostics
|
||||
if instance.Acl == nil || instance.Acl.Items == nil {
|
||||
aclList = types.ListNull(types.StringType)
|
||||
} else {
|
||||
respACL := *instance.Acl.Items
|
||||
modelACL, err := utils.ListValuetoStringSlice(model.ACL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reconciledACL := utils.ReconcileStringSlices(modelACL, respACL)
|
||||
|
||||
aclList, diags = types.ListValueFrom(ctx, types.StringType, reconciledACL)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("mapping ACL: %w", core.DiagsToError(diags))
|
||||
}
|
||||
}
|
||||
|
||||
var flavorValues map[string]attr.Value
|
||||
if instance.Flavor == nil {
|
||||
flavorValues = map[string]attr.Value{
|
||||
"id": flavor.Id,
|
||||
"description": flavor.Description,
|
||||
"cpu": flavor.CPU,
|
||||
"ram": flavor.RAM,
|
||||
}
|
||||
} else {
|
||||
flavorValues = map[string]attr.Value{
|
||||
"id": types.StringValue(*instance.Flavor.Id),
|
||||
"description": types.StringValue(*instance.Flavor.Description),
|
||||
"cpu": types.Int64PointerValue(instance.Flavor.Cpu),
|
||||
"ram": types.Int64PointerValue(instance.Flavor.Memory),
|
||||
}
|
||||
}
|
||||
flavorObject, diags := types.ObjectValue(flavorTypes, flavorValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("creating flavor: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
var storageValues map[string]attr.Value
|
||||
if instance.Storage == nil {
|
||||
storageValues = map[string]attr.Value{
|
||||
"class": storage.Class,
|
||||
"size": storage.Size,
|
||||
}
|
||||
} else {
|
||||
storageValues = map[string]attr.Value{
|
||||
"class": types.StringValue(*instance.Storage.Class),
|
||||
"size": types.Int64PointerValue(instance.Storage.Size),
|
||||
}
|
||||
}
|
||||
storageObject, diags := types.ObjectValue(storageTypes, storageValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("creating storage: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
var optionsValues map[string]attr.Value
|
||||
if instance.Options == nil {
|
||||
optionsValues = map[string]attr.Value{
|
||||
"edition": options.Edition,
|
||||
"retention_days": options.RetentionDays,
|
||||
}
|
||||
} else {
|
||||
retentionDays := options.RetentionDays
|
||||
retentionDaysString, ok := (*instance.Options)["retentionDays"]
|
||||
if ok {
|
||||
retentionDaysValue, err := strconv.ParseInt(retentionDaysString, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse retentionDays to int64: %w", err)
|
||||
}
|
||||
retentionDays = types.Int64Value(retentionDaysValue)
|
||||
}
|
||||
|
||||
edition := options.Edition
|
||||
editionValue, ok := (*instance.Options)["edition"]
|
||||
if ok {
|
||||
edition = types.StringValue(editionValue)
|
||||
}
|
||||
|
||||
optionsValues = map[string]attr.Value{
|
||||
"edition": edition,
|
||||
"retention_days": retentionDays,
|
||||
}
|
||||
}
|
||||
optionsObject, diags := types.ObjectValue(optionsTypes, optionsValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("creating options: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
simplifiedModelBackupSchedule := utils.SimplifyBackupSchedule(model.BackupSchedule.ValueString())
|
||||
// If the value returned by the API is different from the one in the model after simplification,
|
||||
// we update the model so that it causes an error in Terraform
|
||||
if simplifiedModelBackupSchedule != types.StringPointerValue(instance.BackupSchedule).ValueString() {
|
||||
model.BackupSchedule = types.StringPointerValue(instance.BackupSchedule)
|
||||
}
|
||||
|
||||
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, instanceId)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.ACL = aclList
|
||||
model.Flavor = flavorObject
|
||||
model.Replicas = types.Int64PointerValue(instance.Replicas)
|
||||
model.Storage = storageObject
|
||||
model.Version = types.StringPointerValue(instance.Version)
|
||||
model.Options = optionsObject
|
||||
model.Region = types.StringValue(region)
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, acl []string, flavor *flavorModel, storage *storageModel, options *optionsModel) (*sqlserverflex.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
aclPayload := &sqlserverflex.CreateInstancePayloadAcl{}
|
||||
if acl != nil {
|
||||
aclPayload.Items = &acl
|
||||
}
|
||||
if flavor == nil {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
storagePayload := &sqlserverflex.CreateInstancePayloadStorage{}
|
||||
if storage != nil {
|
||||
storagePayload.Class = conversion.StringValueToPointer(storage.Class)
|
||||
storagePayload.Size = conversion.Int64ValueToPointer(storage.Size)
|
||||
}
|
||||
optionsPayload := &sqlserverflex.CreateInstancePayloadOptions{}
|
||||
if options != nil {
|
||||
optionsPayload.Edition = conversion.StringValueToPointer(options.Edition)
|
||||
retentionDaysInt := conversion.Int64ValueToPointer(options.RetentionDays)
|
||||
var retentionDays *string
|
||||
if retentionDaysInt != nil {
|
||||
retentionDays = coreUtils.Ptr(strconv.FormatInt(*retentionDaysInt, 10))
|
||||
}
|
||||
optionsPayload.RetentionDays = retentionDays
|
||||
}
|
||||
|
||||
return &sqlserverflex.CreateInstancePayload{
|
||||
Acl: aclPayload,
|
||||
BackupSchedule: conversion.StringValueToPointer(model.BackupSchedule),
|
||||
FlavorId: conversion.StringValueToPointer(flavor.Id),
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
Storage: storagePayload,
|
||||
Version: conversion.StringValueToPointer(model.Version),
|
||||
Options: optionsPayload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, acl []string, flavor *flavorModel) (*sqlserverflex.PartialUpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
aclPayload := &sqlserverflex.CreateInstancePayloadAcl{}
|
||||
if acl != nil {
|
||||
aclPayload.Items = &acl
|
||||
}
|
||||
if flavor == nil {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
|
||||
return &sqlserverflex.PartialUpdateInstancePayload{
|
||||
Acl: aclPayload,
|
||||
BackupSchedule: conversion.StringValueToPointer(model.BackupSchedule),
|
||||
FlavorId: conversion.StringValueToPointer(flavor.Id),
|
||||
Name: conversion.StringValueToPointer(model.Name),
|
||||
Version: conversion.StringValueToPointer(model.Version),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type sqlserverflexClient interface {
|
||||
ListFlavorsExecute(ctx context.Context, projectId, region string) (*sqlserverflex.ListFlavorsResponse, error)
|
||||
}
|
||||
|
||||
func loadFlavorId(ctx context.Context, client sqlserverflexClient, model *Model, flavor *flavorModel) error {
|
||||
if model == nil {
|
||||
return fmt.Errorf("nil model")
|
||||
}
|
||||
if flavor == nil {
|
||||
return fmt.Errorf("nil flavor")
|
||||
}
|
||||
cpu := conversion.Int64ValueToPointer(flavor.CPU)
|
||||
if cpu == nil {
|
||||
return fmt.Errorf("nil CPU")
|
||||
}
|
||||
ram := conversion.Int64ValueToPointer(flavor.RAM)
|
||||
if ram == nil {
|
||||
return fmt.Errorf("nil RAM")
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
res, err := client.ListFlavorsExecute(ctx, projectId, region)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listing sqlserverflex flavors: %w", err)
|
||||
}
|
||||
|
||||
avl := ""
|
||||
if res.Flavors == nil {
|
||||
return fmt.Errorf("finding flavors for project %s", projectId)
|
||||
}
|
||||
for _, f := range *res.Flavors {
|
||||
if f.Id == nil || f.Cpu == nil || f.Memory == nil {
|
||||
continue
|
||||
}
|
||||
if *f.Cpu == *cpu && *f.Memory == *ram {
|
||||
flavor.Id = types.StringValue(*f.Id)
|
||||
flavor.Description = types.StringValue(*f.Description)
|
||||
break
|
||||
}
|
||||
avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM", avl, *f.Cpu, *f.Memory)
|
||||
}
|
||||
if flavor.Id.ValueString() == "" {
|
||||
return fmt.Errorf("couldn't find flavor, available specs are:%s", avl)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,821 @@
|
|||
package sqlserverflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"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"
|
||||
)
|
||||
|
||||
type sqlserverflexClientMocked struct {
|
||||
returnError bool
|
||||
listFlavorsResp *sqlserverflex.ListFlavorsResponse
|
||||
}
|
||||
|
||||
func (c *sqlserverflexClientMocked) ListFlavorsExecute(_ context.Context, _, _ string) (*sqlserverflex.ListFlavorsResponse, error) {
|
||||
if c.returnError {
|
||||
return nil, fmt.Errorf("get flavors failed")
|
||||
}
|
||||
|
||||
return c.listFlavorsResp, nil
|
||||
}
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
state Model
|
||||
input *sqlserverflex.GetInstanceResponse
|
||||
flavor *flavorModel
|
||||
storage *storageModel
|
||||
options *optionsModel
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&sqlserverflex.GetInstanceResponse{
|
||||
Item: &sqlserverflex.Instance{},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&optionsModel{},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringNull(),
|
||||
ACL: types.ListNull(types.StringType),
|
||||
BackupSchedule: types.StringNull(),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Null(),
|
||||
"ram": types.Int64Null(),
|
||||
}),
|
||||
Replicas: types.Int64Null(),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringNull(),
|
||||
"size": types.Int64Null(),
|
||||
}),
|
||||
Options: types.ObjectValueMust(optionsTypes, map[string]attr.Value{
|
||||
"edition": types.StringNull(),
|
||||
"retention_days": types.Int64Null(),
|
||||
}),
|
||||
Version: types.StringNull(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&sqlserverflex.GetInstanceResponse{
|
||||
Item: &sqlserverflex.Instance{
|
||||
Acl: &sqlserverflex.ACL{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: &sqlserverflex.Flavor{
|
||||
Cpu: utils.Ptr(int64(12)),
|
||||
Description: utils.Ptr("description"),
|
||||
Id: utils.Ptr("flavor_id"),
|
||||
Memory: utils.Ptr(int64(34)),
|
||||
},
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: &sqlserverflex.Storage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int64(78)),
|
||||
},
|
||||
Options: &map[string]string{
|
||||
"edition": "edition",
|
||||
"retentionDays": "1",
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&optionsModel{},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip1"),
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringValue("flavor_id"),
|
||||
"description": types.StringValue("description"),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Options: types.ObjectValueMust(optionsTypes, map[string]attr.Value{
|
||||
"edition": types.StringValue("edition"),
|
||||
"retention_days": types.Int64Value(1),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values_no_flavor_and_storage",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&sqlserverflex.GetInstanceResponse{
|
||||
Item: &sqlserverflex.Instance{
|
||||
Acl: &sqlserverflex.ACL{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: nil,
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: nil,
|
||||
Options: &map[string]string{
|
||||
"edition": "edition",
|
||||
"retentionDays": "1",
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(12),
|
||||
RAM: types.Int64Value(34),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(78),
|
||||
},
|
||||
&optionsModel{
|
||||
Edition: types.StringValue("edition"),
|
||||
RetentionDays: types.Int64Value(1),
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip1"),
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Options: types.ObjectValueMust(optionsTypes, map[string]attr.Value{
|
||||
"edition": types.StringValue("edition"),
|
||||
"retention_days": types.Int64Value(1),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"acls_unordered",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
types.StringValue("ip1"),
|
||||
}),
|
||||
},
|
||||
&sqlserverflex.GetInstanceResponse{
|
||||
Item: &sqlserverflex.Instance{
|
||||
Acl: &sqlserverflex.ACL{
|
||||
Items: &[]string{
|
||||
"",
|
||||
"ip1",
|
||||
"ip2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: nil,
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int64(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: nil,
|
||||
Options: &map[string]string{
|
||||
"edition": "edition",
|
||||
"retentionDays": "1",
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(12),
|
||||
RAM: types.Int64Value(34),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(78),
|
||||
},
|
||||
&optionsModel{},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
types.StringValue("ip1"),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Options: types.ObjectValueMust(optionsTypes, map[string]attr.Value{
|
||||
"edition": types.StringValue("edition"),
|
||||
"retention_days": types.Int64Value(1),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&optionsModel{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
Model{
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
},
|
||||
&sqlserverflex.GetInstanceResponse{},
|
||||
&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, 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(tt.state, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputAcl []string
|
||||
inputFlavor *flavorModel
|
||||
inputStorage *storageModel
|
||||
inputOptions *optionsModel
|
||||
expected *sqlserverflex.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&optionsModel{},
|
||||
&sqlserverflex.CreateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &sqlserverflex.CreateInstancePayloadStorage{},
|
||||
Options: &sqlserverflex.CreateInstancePayloadOptions{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Name: types.StringValue("name"),
|
||||
Replicas: types.Int64Value(12),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("flavor_id"),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(34),
|
||||
},
|
||||
&optionsModel{
|
||||
Edition: types.StringValue("edition"),
|
||||
RetentionDays: types.Int64Value(1),
|
||||
},
|
||||
&sqlserverflex.CreateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Storage: &sqlserverflex.CreateInstancePayloadStorage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int64(34)),
|
||||
},
|
||||
Options: &sqlserverflex.CreateInstancePayloadOptions{
|
||||
Edition: utils.Ptr("edition"),
|
||||
RetentionDays: utils.Ptr("1"),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
BackupSchedule: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Replicas: types.Int64Value(2123456789),
|
||||
Version: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringNull(),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringNull(),
|
||||
Size: types.Int64Null(),
|
||||
},
|
||||
&optionsModel{
|
||||
Edition: types.StringNull(),
|
||||
RetentionDays: types.Int64Null(),
|
||||
},
|
||||
&sqlserverflex.CreateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Storage: &sqlserverflex.CreateInstancePayloadStorage{
|
||||
Class: nil,
|
||||
Size: nil,
|
||||
},
|
||||
Options: &sqlserverflex.CreateInstancePayloadOptions{},
|
||||
Version: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&optionsModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_acl",
|
||||
&Model{},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&optionsModel{},
|
||||
&sqlserverflex.CreateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{},
|
||||
Storage: &sqlserverflex.CreateInstancePayloadStorage{},
|
||||
Options: &sqlserverflex.CreateInstancePayloadOptions{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_flavor",
|
||||
&Model{},
|
||||
[]string{},
|
||||
nil,
|
||||
&storageModel{},
|
||||
&optionsModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_storage",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
nil,
|
||||
&optionsModel{},
|
||||
&sqlserverflex.CreateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &sqlserverflex.CreateInstancePayloadStorage{},
|
||||
Options: &sqlserverflex.CreateInstancePayloadOptions{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_options",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
&sqlserverflex.CreateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &sqlserverflex.CreateInstancePayloadStorage{},
|
||||
Options: &sqlserverflex.CreateInstancePayloadOptions{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputAcl, tt.inputFlavor, tt.inputStorage, tt.inputOptions)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputAcl []string
|
||||
inputFlavor *flavorModel
|
||||
expected *sqlserverflex.PartialUpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&sqlserverflex.PartialUpdateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Name: types.StringValue("name"),
|
||||
Replicas: types.Int64Value(12),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("flavor_id"),
|
||||
},
|
||||
&sqlserverflex.PartialUpdateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
BackupSchedule: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Replicas: types.Int64Value(2123456789),
|
||||
Version: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringNull(),
|
||||
},
|
||||
&sqlserverflex.PartialUpdateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Version: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_acl",
|
||||
&Model{},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&sqlserverflex.PartialUpdateInstancePayload{
|
||||
Acl: &sqlserverflex.CreateInstancePayloadAcl{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_flavor",
|
||||
&Model{},
|
||||
[]string{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputAcl, tt.inputFlavor)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFlavorId(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
inputFlavor *flavorModel
|
||||
mockedResp *sqlserverflex.ListFlavorsResponse
|
||||
expected *flavorModel
|
||||
getFlavorsFails bool
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"ok_flavor",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&sqlserverflex.ListFlavorsResponse{
|
||||
Flavors: &[]sqlserverflex.InstanceFlavorEntry{
|
||||
{
|
||||
Id: utils.Ptr("fid-1"),
|
||||
Cpu: utils.Ptr(int64(2)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(8)),
|
||||
},
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("fid-1"),
|
||||
Description: types.StringValue("description"),
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"ok_flavor_2",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&sqlserverflex.ListFlavorsResponse{
|
||||
Flavors: &[]sqlserverflex.InstanceFlavorEntry{
|
||||
{
|
||||
Id: utils.Ptr("fid-1"),
|
||||
Cpu: utils.Ptr(int64(2)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(8)),
|
||||
},
|
||||
{
|
||||
Id: utils.Ptr("fid-2"),
|
||||
Cpu: utils.Ptr(int64(1)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(4)),
|
||||
},
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("fid-1"),
|
||||
Description: types.StringValue("description"),
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"no_matching_flavor",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&sqlserverflex.ListFlavorsResponse{
|
||||
Flavors: &[]sqlserverflex.InstanceFlavorEntry{
|
||||
{
|
||||
Id: utils.Ptr("fid-1"),
|
||||
Cpu: utils.Ptr(int64(1)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(8)),
|
||||
},
|
||||
{
|
||||
Id: utils.Ptr("fid-2"),
|
||||
Cpu: utils.Ptr(int64(1)),
|
||||
Description: utils.Ptr("description"),
|
||||
Memory: utils.Ptr(int64(4)),
|
||||
},
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&sqlserverflex.ListFlavorsResponse{},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"error_response",
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
&sqlserverflex.ListFlavorsResponse{},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(2),
|
||||
RAM: types.Int64Value(8),
|
||||
},
|
||||
true,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
client := &sqlserverflexClientMocked{
|
||||
returnError: tt.getFlavorsFails,
|
||||
listFlavorsResp: tt.mockedResp,
|
||||
}
|
||||
model := &Model{
|
||||
ProjectId: types.StringValue("pid"),
|
||||
}
|
||||
flavorModel := &flavorModel{
|
||||
CPU: tt.inputFlavor.CPU,
|
||||
RAM: tt.inputFlavor.RAM,
|
||||
}
|
||||
err := loadFlavorId(context.Background(), client, model, flavorModel)
|
||||
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(flavorModel, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,480 @@
|
|||
package sqlserverflex_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/config"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
core_config "github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex/wait"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
var (
|
||||
//go:embed testdata/resource-max.tf
|
||||
resourceMaxConfig string
|
||||
//go:embed testdata/resource-min.tf
|
||||
resourceMinConfig string
|
||||
)
|
||||
var testConfigVarsMin = config.Variables{
|
||||
"project_id": config.StringVariable(testutil.ProjectId),
|
||||
"name": config.StringVariable(fmt.Sprintf("tf-acc-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlphaNum))),
|
||||
"flavor_cpu": config.IntegerVariable(4),
|
||||
"flavor_ram": config.IntegerVariable(16),
|
||||
"flavor_description": config.StringVariable("SQLServer-Flex-4.16-Standard-EU01"),
|
||||
"replicas": config.IntegerVariable(1),
|
||||
"flavor_id": config.StringVariable("4.16-Single"),
|
||||
"username": config.StringVariable(fmt.Sprintf("tf-acc-user-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlpha))),
|
||||
"role": config.StringVariable("##STACKIT_LoginManager##"),
|
||||
}
|
||||
|
||||
var testConfigVarsMax = config.Variables{
|
||||
"project_id": config.StringVariable(testutil.ProjectId),
|
||||
"name": config.StringVariable(fmt.Sprintf("tf-acc-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlphaNum))),
|
||||
"acl1": config.StringVariable("192.168.0.0/16"),
|
||||
"flavor_cpu": config.IntegerVariable(4),
|
||||
"flavor_ram": config.IntegerVariable(16),
|
||||
"flavor_description": config.StringVariable("SQLServer-Flex-4.16-Standard-EU01"),
|
||||
"storage_class": config.StringVariable("premium-perf2-stackit"),
|
||||
"storage_size": config.IntegerVariable(40),
|
||||
"server_version": config.StringVariable("2022"),
|
||||
"replicas": config.IntegerVariable(1),
|
||||
"options_retention_days": config.IntegerVariable(64),
|
||||
"flavor_id": config.StringVariable("4.16-Single"),
|
||||
"backup_schedule": config.StringVariable("00 6 * * *"),
|
||||
"username": config.StringVariable(fmt.Sprintf("tf-acc-user-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlpha))),
|
||||
"role": config.StringVariable("##STACKIT_LoginManager##"),
|
||||
"region": config.StringVariable(testutil.Region),
|
||||
}
|
||||
|
||||
func configVarsMinUpdated() config.Variables {
|
||||
temp := maps.Clone(testConfigVarsMax)
|
||||
temp["name"] = config.StringVariable(testutil.ConvertConfigVariable(temp["name"]) + "changed")
|
||||
return temp
|
||||
}
|
||||
|
||||
func configVarsMaxUpdated() config.Variables {
|
||||
temp := maps.Clone(testConfigVarsMax)
|
||||
temp["backup_schedule"] = config.StringVariable("00 12 * * *")
|
||||
return temp
|
||||
}
|
||||
|
||||
func TestAccSQLServerFlexMinResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccChecksqlserverflexDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMinConfig,
|
||||
ConfigVariables: testConfigVarsMin,
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(testConfigVarsMin["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(testConfigVarsMin["name"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.description", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_description"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "replicas", testutil.ConvertConfigVariable(testConfigVarsMin["replicas"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_ram"])),
|
||||
// User
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "project_id",
|
||||
"stackit_sqlserverflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "instance_id",
|
||||
"stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "password"),
|
||||
),
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMinConfig,
|
||||
ConfigVariables: testConfigVarsMin,
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(testConfigVarsMin["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(testConfigVarsMin["name"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.description", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_description"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_ram"])),
|
||||
// User
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "project_id",
|
||||
"stackit_sqlserverflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "instance_id",
|
||||
"stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "password"),
|
||||
),
|
||||
},
|
||||
// data source
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMinConfig,
|
||||
ConfigVariables: testConfigVarsMin,
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(testConfigVarsMin["project_id"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(testConfigVarsMin["name"])),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_sqlserverflex_instance.instance", "project_id",
|
||||
"stackit_sqlserverflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
"stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_sqlserverflex_user.user", "instance_id",
|
||||
"stackit_sqlserverflex_user.user", "instance_id",
|
||||
),
|
||||
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.id", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_id"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.description", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_description"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(testConfigVarsMin["flavor_ram"])),
|
||||
|
||||
// User data
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "project_id", testutil.ConvertConfigVariable(testConfigVarsMin["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_sqlserverflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "username", testutil.ConvertConfigVariable(testConfigVarsMin["username"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "roles.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "roles.0", testutil.ConvertConfigVariable(testConfigVarsMax["role"])),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ConfigVariables: testConfigVarsMin,
|
||||
ResourceName: "stackit_sqlserverflex_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_sqlserverflex_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_sqlserverflex_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, testutil.Region, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"backup_schedule"},
|
||||
ImportStateCheck: func(s []*terraform.InstanceState) error {
|
||||
if len(s) != 1 {
|
||||
return fmt.Errorf("expected 1 state, got %d", len(s))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_sqlserverflex_user.user",
|
||||
ConfigVariables: testConfigVarsMin,
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_sqlserverflex_user.user"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_sqlserverflex_user.user")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
userId, ok := r.Primary.Attributes["user_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute user_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s,%s", testutil.ProjectId, testutil.Region, instanceId, userId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"password"},
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMinConfig,
|
||||
ConfigVariables: configVarsMinUpdated(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(configVarsMinUpdated()["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(configVarsMinUpdated()["name"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.description"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(configVarsMinUpdated()["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(configVarsMinUpdated()["flavor_ram"])),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestAccSQLServerFlexMaxResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccChecksqlserverflexDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMaxConfig,
|
||||
ConfigVariables: testConfigVarsMax,
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(testConfigVarsMax["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(testConfigVarsMax["name"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.0", testutil.ConvertConfigVariable(testConfigVarsMax["acl1"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.description", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_description"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "replicas", testutil.ConvertConfigVariable(testConfigVarsMax["replicas"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_ram"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "storage.class", testutil.ConvertConfigVariable(testConfigVarsMax["storage_class"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "storage.size", testutil.ConvertConfigVariable(testConfigVarsMax["storage_size"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "version", testutil.ConvertConfigVariable(testConfigVarsMax["server_version"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "options.retention_days", testutil.ConvertConfigVariable(testConfigVarsMax["options_retention_days"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "backup_schedule", testutil.ConvertConfigVariable(testConfigVarsMax["backup_schedule"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "region", testutil.Region),
|
||||
// User
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "project_id",
|
||||
"stackit_sqlserverflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "instance_id",
|
||||
"stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "password"),
|
||||
),
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMaxConfig,
|
||||
ConfigVariables: testConfigVarsMax,
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(testConfigVarsMax["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(testConfigVarsMax["name"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.0", testutil.ConvertConfigVariable(testConfigVarsMax["acl1"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.description", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_description"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "replicas", testutil.ConvertConfigVariable(testConfigVarsMax["replicas"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_ram"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "storage.class", testutil.ConvertConfigVariable(testConfigVarsMax["storage_class"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "storage.size", testutil.ConvertConfigVariable(testConfigVarsMax["storage_size"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "version", testutil.ConvertConfigVariable(testConfigVarsMax["server_version"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "options.retention_days", testutil.ConvertConfigVariable(testConfigVarsMax["options_retention_days"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "backup_schedule", testutil.ConvertConfigVariable(testConfigVarsMax["backup_schedule"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "region", testutil.Region),
|
||||
// User
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "project_id",
|
||||
"stackit_sqlserverflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_sqlserverflex_user.user", "instance_id",
|
||||
"stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_user.user", "password"),
|
||||
),
|
||||
},
|
||||
// data source
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMaxConfig,
|
||||
ConfigVariables: testConfigVarsMax,
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(testConfigVarsMax["project_id"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(testConfigVarsMax["name"])),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_sqlserverflex_instance.instance", "project_id",
|
||||
"stackit_sqlserverflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
"stackit_sqlserverflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_sqlserverflex_user.user", "instance_id",
|
||||
"stackit_sqlserverflex_user.user", "instance_id",
|
||||
),
|
||||
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "acl.0", testutil.ConvertConfigVariable(testConfigVarsMax["acl1"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.id", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_id"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.description", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_description"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(testConfigVarsMax["flavor_ram"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "replicas", testutil.ConvertConfigVariable(testConfigVarsMax["replicas"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "options.retention_days", testutil.ConvertConfigVariable(testConfigVarsMax["options_retention_days"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_instance.instance", "backup_schedule", testutil.ConvertConfigVariable(testConfigVarsMax["backup_schedule"])),
|
||||
|
||||
// User data
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "project_id", testutil.ConvertConfigVariable(testConfigVarsMax["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_sqlserverflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "username", testutil.ConvertConfigVariable(testConfigVarsMax["username"])),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "roles.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_sqlserverflex_user.user", "roles.0", testutil.ConvertConfigVariable(testConfigVarsMax["role"])),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_sqlserverflex_user.user", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_sqlserverflex_user.user", "port"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ConfigVariables: testConfigVarsMax,
|
||||
ResourceName: "stackit_sqlserverflex_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_sqlserverflex_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_sqlserverflex_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, testutil.Region, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"backup_schedule"},
|
||||
ImportStateCheck: func(s []*terraform.InstanceState) error {
|
||||
if len(s) != 1 {
|
||||
return fmt.Errorf("expected 1 state, got %d", len(s))
|
||||
}
|
||||
if s[0].Attributes["backup_schedule"] != testutil.ConvertConfigVariable(testConfigVarsMax["backup_schedule"]) {
|
||||
return fmt.Errorf("expected backup_schedule %s, got %s", testConfigVarsMax["backup_schedule"], s[0].Attributes["backup_schedule"])
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_sqlserverflex_user.user",
|
||||
ConfigVariables: testConfigVarsMax,
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_sqlserverflex_user.user"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_sqlserverflex_user.user")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
userId, ok := r.Primary.Attributes["user_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute user_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s,%s", testutil.ProjectId, testutil.Region, instanceId, userId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"password"},
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: testutil.SQLServerFlexProviderConfig() + "\n" + resourceMaxConfig,
|
||||
ConfigVariables: configVarsMaxUpdated(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "project_id", testutil.ConvertConfigVariable(configVarsMaxUpdated()["project_id"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "name", testutil.ConvertConfigVariable(configVarsMaxUpdated()["name"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "acl.0", testutil.ConvertConfigVariable(configVarsMaxUpdated()["acl1"])),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_sqlserverflex_instance.instance", "flavor.description"),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.cpu", testutil.ConvertConfigVariable(configVarsMaxUpdated()["flavor_cpu"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "flavor.ram", testutil.ConvertConfigVariable(configVarsMaxUpdated()["flavor_ram"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "replicas", testutil.ConvertConfigVariable(configVarsMaxUpdated()["replicas"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "storage.class", testutil.ConvertConfigVariable(configVarsMaxUpdated()["storage_class"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "storage.size", testutil.ConvertConfigVariable(configVarsMaxUpdated()["storage_size"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "version", testutil.ConvertConfigVariable(configVarsMaxUpdated()["server_version"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "options.retention_days", testutil.ConvertConfigVariable(configVarsMaxUpdated()["options_retention_days"])),
|
||||
resource.TestCheckResourceAttr("stackit_sqlserverflex_instance.instance", "backup_schedule", testutil.ConvertConfigVariable(configVarsMaxUpdated()["backup_schedule"])),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccChecksqlserverflexDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *sqlserverflex.APIClient
|
||||
var err error
|
||||
if testutil.SQLServerFlexCustomEndpoint == "" {
|
||||
client, err = sqlserverflex.NewAPIClient()
|
||||
} else {
|
||||
client, err = sqlserverflex.NewAPIClient(
|
||||
core_config.WithEndpoint(testutil.SQLServerFlexCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_sqlserverflex_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: = "[project_id],[region],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[2]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.ListInstances(ctx, testutil.ProjectId, testutil.Region).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
items := *instancesResp.Items
|
||||
for i := range items {
|
||||
if items[i].Id == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *items[i].Id) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *items[i].Id, testutil.Region)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *items[i].Id, err)
|
||||
}
|
||||
_, err = wait.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *items[i].Id, testutil.Region).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *items[i].Id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
51
stackit/internal/services/sqlserverflexalpha/testdata/resource-max.tf
vendored
Normal file
51
stackit/internal/services/sqlserverflexalpha/testdata/resource-max.tf
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
variable "project_id" {}
|
||||
variable "name" {}
|
||||
variable "acl1" {}
|
||||
variable "flavor_cpu" {}
|
||||
variable "flavor_ram" {}
|
||||
variable "storage_class" {}
|
||||
variable "storage_size" {}
|
||||
variable "options_retention_days" {}
|
||||
variable "backup_schedule" {}
|
||||
variable "username" {}
|
||||
variable "role" {}
|
||||
variable "server_version" {}
|
||||
variable "region" {}
|
||||
|
||||
resource "stackit_sqlserverflex_instance" "instance" {
|
||||
project_id = var.project_id
|
||||
name = var.name
|
||||
acl = [var.acl1]
|
||||
flavor = {
|
||||
cpu = var.flavor_cpu
|
||||
ram = var.flavor_ram
|
||||
}
|
||||
storage = {
|
||||
class = var.storage_class
|
||||
size = var.storage_size
|
||||
}
|
||||
version = var.server_version
|
||||
options = {
|
||||
retention_days = var.options_retention_days
|
||||
}
|
||||
backup_schedule = var.backup_schedule
|
||||
region = var.region
|
||||
}
|
||||
|
||||
resource "stackit_sqlserverflex_user" "user" {
|
||||
project_id = stackit_sqlserverflex_instance.instance.project_id
|
||||
instance_id = stackit_sqlserverflex_instance.instance.instance_id
|
||||
username = var.username
|
||||
roles = [var.role]
|
||||
}
|
||||
|
||||
data "stackit_sqlserverflex_instance" "instance" {
|
||||
project_id = var.project_id
|
||||
instance_id = stackit_sqlserverflex_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_sqlserverflex_user" "user" {
|
||||
project_id = var.project_id
|
||||
instance_id = stackit_sqlserverflex_instance.instance.instance_id
|
||||
user_id = stackit_sqlserverflex_user.user.user_id
|
||||
}
|
||||
33
stackit/internal/services/sqlserverflexalpha/testdata/resource-min.tf
vendored
Normal file
33
stackit/internal/services/sqlserverflexalpha/testdata/resource-min.tf
vendored
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
variable "project_id" {}
|
||||
variable "name" {}
|
||||
variable "flavor_cpu" {}
|
||||
variable "flavor_ram" {}
|
||||
variable "username" {}
|
||||
variable "role" {}
|
||||
|
||||
resource "stackit_sqlserverflex_instance" "instance" {
|
||||
project_id = var.project_id
|
||||
name = var.name
|
||||
flavor = {
|
||||
cpu = var.flavor_cpu
|
||||
ram = var.flavor_ram
|
||||
}
|
||||
}
|
||||
|
||||
resource "stackit_sqlserverflex_user" "user" {
|
||||
project_id = stackit_sqlserverflex_instance.instance.project_id
|
||||
instance_id = stackit_sqlserverflex_instance.instance.instance_id
|
||||
username = var.username
|
||||
roles = [var.role]
|
||||
}
|
||||
|
||||
data "stackit_sqlserverflex_instance" "instance" {
|
||||
project_id = var.project_id
|
||||
instance_id = stackit_sqlserverflex_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_sqlserverflex_user" "user" {
|
||||
project_id = var.project_id
|
||||
instance_id = stackit_sqlserverflex_instance.instance.instance_id
|
||||
user_id = stackit_sqlserverflex_user.user.user_id
|
||||
}
|
||||
235
stackit/internal/services/sqlserverflexalpha/user/datasource.go
Normal file
235
stackit/internal/services/sqlserverflexalpha/user/datasource.go
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
package sqlserverflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"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/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"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"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &userDataSource{}
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
// NewUserDataSource is a helper function to simplify the provider implementation.
|
||||
func NewUserDataSource() datasource.DataSource {
|
||||
return &userDataSource{}
|
||||
}
|
||||
|
||||
// userDataSource is the data source implementation.
|
||||
type userDataSource struct {
|
||||
client *sqlserverflex.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"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
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 {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "SQLServer Flex user client configured")
|
||||
}
|
||||
|
||||
// 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.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Description: descriptions["user_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Description: descriptions["username"],
|
||||
Computed: true,
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
Description: descriptions["roles"],
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
// the region cannot be found automatically, so it has to be passed
|
||||
Optional: true,
|
||||
Description: descriptions["region"],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
var model DataSourceModel
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
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()
|
||||
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),
|
||||
map[int]string{
|
||||
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
|
||||
},
|
||||
)
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// 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))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SQLServer Flex user read")
|
||||
}
|
||||
|
||||
func mapDataSourceFields(userResp *sqlserverflex.GetUserResponse, model *DataSourceModel, region string) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
var userId string
|
||||
if model.UserId.ValueString() != "" {
|
||||
userId = model.UserId.ValueString()
|
||||
} 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.UserId = types.StringValue(userId)
|
||||
model.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Region = types.StringValue(region)
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
package sqlserverflex
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"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"
|
||||
)
|
||||
|
||||
func TestMapDataSourceFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *sqlserverflex.GetUserResponse
|
||||
region string
|
||||
expected DataSourceModel
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&sqlserverflex.GetUserResponse{
|
||||
Item: &sqlserverflex.UserResponseUser{},
|
||||
},
|
||||
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),
|
||||
},
|
||||
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)),
|
||||
},
|
||||
},
|
||||
testRegion,
|
||||
DataSourceModel{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
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),
|
||||
},
|
||||
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)),
|
||||
},
|
||||
},
|
||||
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.SetValueMust(types.StringType, []attr.Value{}),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
DataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&sqlserverflex.GetUserResponse{},
|
||||
testRegion,
|
||||
DataSourceModel{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&sqlserverflex.GetUserResponse{
|
||||
Item: &sqlserverflex.UserResponseUser{},
|
||||
},
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
487
stackit/internal/services/sqlserverflexalpha/user/resource.go
Normal file
487
stackit/internal/services/sqlserverflexalpha/user/resource.go
Normal file
|
|
@ -0,0 +1,487 @@
|
|||
package sqlserverflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
sqlserverflexUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/sqlserverflex/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"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/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"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/setplanmodifier"
|
||||
"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.
|
||||
var (
|
||||
_ resource.Resource = &userResource{}
|
||||
_ resource.ResourceWithConfigure = &userResource{}
|
||||
_ resource.ResourceWithImportState = &userResource{}
|
||||
_ resource.ResourceWithModifyPlan = &userResource{}
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
// NewUserResource is a helper function to simplify the provider implementation.
|
||||
func NewUserResource() resource.Resource {
|
||||
return &userResource{}
|
||||
}
|
||||
|
||||
// userResource is the resource implementation.
|
||||
type userResource struct {
|
||||
client *sqlserverflex.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"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
var ok bool
|
||||
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
apiClient := sqlserverflexUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "SQLServer 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
|
||||
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.GetRegion(), 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 *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.",
|
||||
}
|
||||
|
||||
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(),
|
||||
},
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Description: descriptions["user_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Description: descriptions["username"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
Description: descriptions["roles"],
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.Set{
|
||||
setplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Description: descriptions["password"],
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"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(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
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 roles []string
|
||||
if !(model.Roles.IsNull() || model.Roles.IsUnknown()) {
|
||||
diags = model.Roles.ElementsAs(ctx, &roles, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, roles)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new user
|
||||
userResp, err := r.client.CreateUser(ctx, projectId, instanceId, region).CreateUserPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
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")
|
||||
return
|
||||
}
|
||||
userId := *userResp.Item.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))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SQLServer Flex user created")
|
||||
}
|
||||
|
||||
// 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
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
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()
|
||||
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 {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
// 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))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SQLServer Flex user read")
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.InitProviderContext(ctx)
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
region := model.Region.ValueString()
|
||||
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)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteUser(ctx, projectId, instanceId, userId, region).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx = core.LogResponse(ctx)
|
||||
|
||||
tflog.Info(ctx, "SQLServer Flex user deleted")
|
||||
}
|
||||
|
||||
// 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) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
|
||||
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),
|
||||
)
|
||||
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])...)
|
||||
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 {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
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.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Password == nil {
|
||||
return fmt.Errorf("user password not present")
|
||||
}
|
||||
model.Password = types.StringValue(*user.Password)
|
||||
|
||||
if user.Roles != nil {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
|
||||
if model.Roles.IsNull() || model.Roles.IsUnknown() {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
}
|
||||
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Region = types.StringValue(region)
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapFields(userResp *sqlserverflex.GetUserResponse, model *Model, region string) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
var userId string
|
||||
if model.UserId.ValueString() != "" {
|
||||
userId = model.UserId.ValueString()
|
||||
} 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.UserId = types.StringValue(userId)
|
||||
model.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Roles != nil {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
|
||||
if model.Roles.IsNull() || model.Roles.IsUnknown() {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
}
|
||||
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = types.Int64PointerValue(user.Port)
|
||||
model.Region = types.StringValue(region)
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, roles []string) (*sqlserverflex.CreateUserPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
return &sqlserverflex.CreateUserPayload{
|
||||
Username: conversion.StringValueToPointer(model.Username),
|
||||
Roles: &roles,
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,387 @@
|
|||
package sqlserverflex
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"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"
|
||||
)
|
||||
|
||||
func TestMapFieldsCreate(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *sqlserverflex.CreateUserResponse
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&sqlserverflex.CreateUserResponse{
|
||||
Item: &sqlserverflex.SingleUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Password: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
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.SetNull(types.StringType),
|
||||
Password: types.StringValue(""),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"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)),
|
||||
},
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
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),
|
||||
},
|
||||
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)),
|
||||
},
|
||||
},
|
||||
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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&sqlserverflex.CreateUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&sqlserverflex.CreateUserResponse{
|
||||
Item: &sqlserverflex.SingleUser{},
|
||||
},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_password",
|
||||
&sqlserverflex.CreateUserResponse{
|
||||
Item: &sqlserverflex.SingleUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
},
|
||||
},
|
||||
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,
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
const testRegion = "region"
|
||||
tests := []struct {
|
||||
description string
|
||||
input *sqlserverflex.GetUserResponse
|
||||
region string
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&sqlserverflex.GetUserResponse{
|
||||
Item: &sqlserverflex.UserResponseUser{},
|
||||
},
|
||||
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.SetNull(types.StringType),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
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)),
|
||||
},
|
||||
},
|
||||
testRegion,
|
||||
Model{
|
||||
Id: types.StringValue("pid,region,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
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),
|
||||
},
|
||||
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)),
|
||||
},
|
||||
},
|
||||
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{}),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&sqlserverflex.GetUserResponse{},
|
||||
testRegion,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&sqlserverflex.GetUserResponse{
|
||||
Item: &sqlserverflex.UserResponseUser{},
|
||||
},
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputRoles []string
|
||||
expected *sqlserverflex.CreateUserPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&sqlserverflex.CreateUserPayload{
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&sqlserverflex.CreateUserPayload{
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&sqlserverflex.CreateUserPayload{
|
||||
Roles: &[]string{
|
||||
"",
|
||||
},
|
||||
Username: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&Model{
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
[]string{},
|
||||
&sqlserverflex.CreateUserPayload{
|
||||
Roles: &[]string{},
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
32
stackit/internal/services/sqlserverflexalpha/utils/util.go
Normal file
32
stackit/internal/services/sqlserverflexalpha/utils/util.go
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/sqlserverflex"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/utils"
|
||||
)
|
||||
|
||||
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))
|
||||
} 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))
|
||||
return nil
|
||||
}
|
||||
|
||||
return apiClient
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
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/sqlserverflex"
|
||||
"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://sqlserverflex-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 *sqlserverflex.APIClient
|
||||
}{
|
||||
{
|
||||
name: "default endpoint",
|
||||
args: args{
|
||||
providerData: &core.ProviderData{
|
||||
Version: testVersion,
|
||||
},
|
||||
},
|
||||
expected: func() *sqlserverflex.APIClient {
|
||||
apiClient, err := sqlserverflex.NewAPIClient(
|
||||
config.WithRegion("eu01"),
|
||||
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,
|
||||
SQLServerFlexCustomEndpoint: testCustomEndpoint,
|
||||
},
|
||||
},
|
||||
expected: func() *sqlserverflex.APIClient {
|
||||
apiClient, err := sqlserverflex.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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -75,7 +75,7 @@ import (
|
|||
postgresFlexDatabase "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/database"
|
||||
postgresFlexInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/instance"
|
||||
postgresFlexUser "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/user"
|
||||
postgresFlexAlphaInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflexa/instance"
|
||||
postgresFlexAlphaInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflexalpha/instance"
|
||||
rabbitMQCredential "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/rabbitmq/credential"
|
||||
rabbitMQInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/rabbitmq/instance"
|
||||
redisCredential "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/redis/credential"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue