Initial commit
This commit is contained in:
commit
e4c8a6fbf4
186 changed files with 29501 additions and 0 deletions
205
stackit/services/postgresflex/instance/datasource.go
Normal file
205
stackit/services/postgresflex/instance/datasource.go
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"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/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// 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 *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Postgresflex instance client configured")
|
||||
r.client = apiClient
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex instance data source schema.",
|
||||
"id": "Terraform's internal resource 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.",
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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 state Model
|
||||
diags := req.Config.Get(ctx, &state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := state.ProjectId.ValueString()
|
||||
instanceId := state.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to read instance", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if !(state.Flavor.IsNull() || state.Flavor.IsUnknown()) {
|
||||
diags = state.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(state.Storage.IsNull() || state.Storage.IsUnknown()) {
|
||||
diags = state.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &state, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error())
|
||||
return
|
||||
}
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
tflog.Info(ctx, "Postgresql instance read")
|
||||
}
|
||||
703
stackit/services/postgresflex/instance/resource.go
Normal file
703
stackit/services/postgresflex/instance/resource.go
Normal file
|
|
@ -0,0 +1,703 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/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/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &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"`
|
||||
}
|
||||
|
||||
// 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 DataSourceModel.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 *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Postgresflex instance client configured")
|
||||
r.client = apiClient
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex instance resource schema.",
|
||||
"id": "Terraform's internal resource 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.",
|
||||
}
|
||||
|
||||
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{
|
||||
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{
|
||||
Required: true,
|
||||
},
|
||||
"storage": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Required: true,
|
||||
},
|
||||
"size": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
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
|
||||
}
|
||||
r.loadFlavorId(ctx, &resp.Diagnostics, &model, flavor)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, acl, flavor, storage)
|
||||
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).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if createResp == nil || createResp.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", "Didn't get ID of created instance. An instance might have been created")
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.Id
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := postgresflex.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*postgresflex.InstanceResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", got))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(got, &model, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
tflog.Info(ctx, "Postgresflex 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 state Model
|
||||
diags := req.State.Get(ctx, &state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := state.ProjectId.ValueString()
|
||||
instanceId := state.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if !(state.Flavor.IsNull() || state.Flavor.IsUnknown()) {
|
||||
diags = state.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(state.Storage.IsNull() || state.Storage.IsUnknown()) {
|
||||
diags = state.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(instanceResp, &state, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
|
||||
return
|
||||
}
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
tflog.Info(ctx, "Postgresflex 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
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
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
|
||||
}
|
||||
r.loadFlavorId(ctx, &resp.Diagnostics, &model, flavor)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// 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("Could not create API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
_, err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", err.Error())
|
||||
return
|
||||
}
|
||||
wr, err := postgresflex.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*postgresflex.InstanceResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", got))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(got, &model, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields in update", err.Error())
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
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
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", err.Error())
|
||||
return
|
||||
}
|
||||
_, err = postgresflex.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * 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, "Postgresflex 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) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
resp.Diagnostics.AddError(
|
||||
"Unexpected Import Identifier",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "Postgresql instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(resp *postgresflex.InstanceResponse, model *Model, flavor *flavorModel, storage *storageModel) 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 {
|
||||
acl := []attr.Value{}
|
||||
for _, ip := range *instance.Acl.Items {
|
||||
acl = append(acl, types.StringValue(ip))
|
||||
}
|
||||
aclList, diags = types.ListValue(types.StringType, acl)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map ACL: %w", core.DiagsToError(diags))
|
||||
}
|
||||
}
|
||||
|
||||
var flavorValues map[string]attr.Value
|
||||
if instance.Flavor == nil {
|
||||
flavorValues = map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"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.Int64Value(int64(*instance.Flavor.Cpu)),
|
||||
"ram": types.Int64Value(int64(*instance.Flavor.Memory)),
|
||||
}
|
||||
}
|
||||
flavorObject, diags := types.ObjectValue(flavorTypes, flavorValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to create 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.Int64Value(int64(*instance.Storage.Size)),
|
||||
}
|
||||
}
|
||||
storageObject, diags := types.ObjectValue(storageTypes, storageValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to create storage: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
if instance.Name == nil {
|
||||
model.Name = types.StringNull()
|
||||
} else {
|
||||
model.Name = types.StringValue(*instance.Name)
|
||||
}
|
||||
model.ACL = aclList
|
||||
if instance.BackupSchedule == nil {
|
||||
model.BackupSchedule = types.StringNull()
|
||||
} else {
|
||||
model.BackupSchedule = types.StringValue(*instance.BackupSchedule)
|
||||
}
|
||||
model.Flavor = flavorObject
|
||||
if instance.Replicas == nil {
|
||||
model.Replicas = types.Int64Null()
|
||||
} else {
|
||||
model.Replicas = types.Int64Value(int64(*instance.Replicas))
|
||||
}
|
||||
model.Storage = storageObject
|
||||
if instance.Version == nil {
|
||||
model.Version = types.StringNull()
|
||||
} else {
|
||||
model.Version = types.StringValue(*instance.Version)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, acl []string, flavor *flavorModel, storage *storageModel) (*postgresflex.CreateInstancePayload, 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 &postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &acl,
|
||||
},
|
||||
BackupSchedule: model.BackupSchedule.ValueStringPointer(),
|
||||
FlavorId: flavor.Id.ValueStringPointer(),
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Replicas: conversion.ToPtrInt32(model.Replicas),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: storage.Class.ValueStringPointer(),
|
||||
Size: conversion.ToPtrInt32(storage.Size),
|
||||
},
|
||||
Version: model.Version.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, acl []string, flavor *flavorModel, storage *storageModel) (*postgresflex.UpdateInstancePayload, 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 &postgresflex.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &acl,
|
||||
},
|
||||
BackupSchedule: model.BackupSchedule.ValueStringPointer(),
|
||||
FlavorId: flavor.Id.ValueStringPointer(),
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Replicas: conversion.ToPtrInt32(model.Replicas),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: storage.Class.ValueStringPointer(),
|
||||
Size: conversion.ToPtrInt32(storage.Size),
|
||||
},
|
||||
Version: model.Version.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadFlavorId(ctx context.Context, diags *diag.Diagnostics, model *Model, flavor *flavorModel) {
|
||||
if model == nil {
|
||||
diags.AddError("invalid model", "nil model")
|
||||
return
|
||||
}
|
||||
if flavor == nil {
|
||||
diags.AddError("invalid flavor", "nil flavor")
|
||||
return
|
||||
}
|
||||
cpu := conversion.ToPtrInt32(flavor.CPU)
|
||||
if cpu == nil {
|
||||
diags.AddError("invalid flavor", "nil CPU")
|
||||
return
|
||||
}
|
||||
ram := conversion.ToPtrInt32(flavor.RAM)
|
||||
if ram == nil {
|
||||
diags.AddError("invalid flavor", "nil RAM")
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetFlavors(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
diags.AddError("failed to list postgresflex flavors", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
avl := ""
|
||||
if res.Flavors == nil {
|
||||
diags.AddError("no flavors", fmt.Sprintf("couldn't find flavors for id %s", flavor.Id.ValueString()))
|
||||
return
|
||||
}
|
||||
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)
|
||||
break
|
||||
}
|
||||
avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM", avl, *f.Cpu, *f.Cpu)
|
||||
}
|
||||
if flavor.Id.ValueString() == "" {
|
||||
diags.AddError("invalid flavor", fmt.Sprintf("couldn't find flavor.\navailable specs are:%s", avl))
|
||||
return
|
||||
}
|
||||
}
|
||||
509
stackit/services/postgresflex/instance/resource_test.go
Normal file
509
stackit/services/postgresflex/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,509 @@
|
|||
package postgresflex
|
||||
|
||||
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 TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.InstanceResponse
|
||||
flavor *flavorModel
|
||||
storage *storageModel
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.InstanceSingleInstance{},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.InstanceSingleInstance{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: &postgresflex.InstanceFlavor{
|
||||
Cpu: utils.Ptr(int32(12)),
|
||||
Description: utils.Ptr("description"),
|
||||
Id: utils.Ptr("flavor_id"),
|
||||
Memory: utils.Ptr(int32(34)),
|
||||
},
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int32(78)),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values_no_flavor_and_storage",
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.InstanceSingleInstance{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: nil,
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(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),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.InstanceResponse{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
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.flavor, tt.storage)
|
||||
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
|
||||
inputAcl []string
|
||||
inputFlavor *flavorModel
|
||||
inputStorage *storageModel
|
||||
expected *postgresflex.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &postgresflex.InstanceStorage{},
|
||||
},
|
||||
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.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(12)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int32(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.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Replicas: utils.Ptr(int32(2123456789)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
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.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&postgresflex.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &postgresflex.InstanceStorage{},
|
||||
},
|
||||
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.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(12)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int32(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.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Replicas: utils.Ptr(int32(2123456789)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
324
stackit/services/postgresflex/postgresflex_acc_test.go
Normal file
324
stackit/services/postgresflex/postgresflex_acc_test.go
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
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/terraform-provider-stackit/stackit/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/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_update": "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("tf-acc-user-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlpha)),
|
||||
"role": "login",
|
||||
"project_id": instanceResource["project_id"],
|
||||
}
|
||||
|
||||
func configResources() string {
|
||||
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"
|
||||
}
|
||||
|
||||
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"]
|
||||
}
|
||||
`,
|
||||
testutil.PostgresFlexProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["acl"],
|
||||
instanceResource["backup_schedule"],
|
||||
instanceResource["flavor_cpu"],
|
||||
instanceResource["flavor_ram"],
|
||||
instanceResource["replicas"],
|
||||
instanceResource["storage_class"],
|
||||
instanceResource["storage_size"],
|
||||
instanceResource["version"],
|
||||
userResource["username"],
|
||||
userResource["role"],
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccPostgresFlexFlexResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckPostgresFlexDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: configResources(),
|
||||
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"]),
|
||||
|
||||
// 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"),
|
||||
),
|
||||
},
|
||||
// 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
|
||||
}
|
||||
`,
|
||||
configResources(),
|
||||
),
|
||||
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"),
|
||||
),
|
||||
},
|
||||
// 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", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
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", testutil.ProjectId, instanceId, userId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"password"},
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: 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"
|
||||
}
|
||||
`,
|
||||
testutil.PostgresFlexProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["acl"],
|
||||
instanceResource["backup_schedule_update"],
|
||||
instanceResource["flavor_cpu"],
|
||||
instanceResource["flavor_ram"],
|
||||
instanceResource["replicas"],
|
||||
instanceResource["storage_class"],
|
||||
instanceResource["storage_size"],
|
||||
instanceResource["version"],
|
||||
),
|
||||
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_update"]),
|
||||
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_postgresql_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: = "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).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)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *items[i].Id, err)
|
||||
}
|
||||
_, err = postgresflex.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *items[i].Id).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *items[i].Id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
168
stackit/services/postgresflex/user/datasource.go
Normal file
168
stackit/services/postgresflex/user/datasource.go
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"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/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &userDataSource{}
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Metadata returns the resource 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 resource.
|
||||
func (r *userDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Postgresflex user client configured")
|
||||
r.client = apiClient
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex user data source schema.",
|
||||
"id": "Terraform's internal resource ID.",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
tflog.Info(ctx, "Postgresql user read")
|
||||
}
|
||||
431
stackit/services/postgresflex/user/resource.go
Normal file
431
stackit/services/postgresflex/user/resource.go
Normal file
|
|
@ -0,0 +1,431 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/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/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &userResource{}
|
||||
_ resource.ResourceWithConfigure = &userResource{}
|
||||
_ resource.ResourceWithImportState = &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"`
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Postgresflex user client configured")
|
||||
r.client = apiClient
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex user resource schema.",
|
||||
"id": "Terraform's internal resource ID.",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
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{
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.Set{
|
||||
setplanmodifier.RequiresReplace(),
|
||||
},
|
||||
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,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
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).CreateUserPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if userResp == nil || userResp.Item == nil || userResp.Item.Id == nil || *userResp.Item.Id == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", "Didn't get ID of created user. A user might have been created")
|
||||
return
|
||||
}
|
||||
userId := *userResp.Item.Id
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFieldsCreate(userResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
tflog.Info(ctx, "Postgresflex 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
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
tflog.Info(ctx, "Postgresflex user read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *userResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
resp.Diagnostics.AddError("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
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteUser(ctx, projectId, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", err.Error())
|
||||
}
|
||||
_, err = postgresflex.DeleteUserWaitHandler(ctx, r.client, projectId, instanceId, userId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgresflex 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) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Unexpected Import Identifier",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[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("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "Postgresflex user state imported")
|
||||
}
|
||||
|
||||
func mapFieldsCreate(userResp *postgresflex.CreateUserResponse, model *Model) 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
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
userId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
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 = conversion.ToTypeInt64(user.Port)
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapFields(userResp *postgresflex.UserResponse, model *Model) 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")
|
||||
}
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
userId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
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 = conversion.ToTypeInt64(user.Port)
|
||||
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: model.Username.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
359
stackit/services/postgresflex/user/resource_test.go
Normal file
359
stackit/services/postgresflex/user/resource_test.go
Normal file
|
|
@ -0,0 +1,359 @@
|
|||
package postgresflex
|
||||
|
||||
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) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.CreateUserResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Password: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
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(int32(1234)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.CreateUserResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_password",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
},
|
||||
},
|
||||
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)
|
||||
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 TestMapCreate(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.UserResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Username: utils.Ptr("username"),
|
||||
Host: utils.Ptr("host"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,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),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.UserResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{},
|
||||
},
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue