Implement PostgreSQL Flex database resource and data source (#453)
* Implement db resource * Implement db data source * Extend acc test * Improve logs in other resources * Add examples * Generate docs * Fix linter
This commit is contained in:
parent
3fb28d1248
commit
34388eb361
17 changed files with 923 additions and 29 deletions
36
docs/data-sources/postgresflex_database.md
Normal file
36
docs/data-sources/postgresflex_database.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "stackit_postgresflex_database Data Source - stackit"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Postgres Flex database resource schema. Must have a region specified in the provider configuration.
|
||||
---
|
||||
|
||||
# stackit_postgresflex_database (Data Source)
|
||||
|
||||
Postgres Flex database resource schema. Must have a `region` specified in the provider configuration.
|
||||
|
||||
## Example Usage
|
||||
|
||||
```terraform
|
||||
data "stackit_postgresflex_database" "example" {
|
||||
project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
instance_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
}
|
||||
```
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `database_id` (String) Database ID.
|
||||
- `instance_id` (String) ID of the Postgres Flex instance.
|
||||
- `project_id` (String) STACKIT project ID to which the instance is associated.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`instance_id`,`database_id`".
|
||||
- `name` (String) Database name.
|
||||
- `owner` (String) Username of the database owner.
|
||||
|
|
@ -3,12 +3,12 @@
|
|||
page_title: "stackit_postgresflex_instance Data Source - stackit"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
PostgresFlex instance data source schema. Must have a region specified in the provider configuration.
|
||||
Postgres Flex instance data source schema. Must have a region specified in the provider configuration.
|
||||
---
|
||||
|
||||
# stackit_postgresflex_instance (Data Source)
|
||||
|
||||
PostgresFlex instance data source schema. Must have a `region` specified in the provider configuration.
|
||||
Postgres Flex instance data source schema. Must have a `region` specified in the provider configuration.
|
||||
|
||||
## Example Usage
|
||||
|
||||
|
|
|
|||
|
|
@ -3,12 +3,12 @@
|
|||
page_title: "stackit_postgresflex_user Data Source - stackit"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
PostgresFlex user data source schema. Must have a region specified in the provider configuration.
|
||||
Postgres Flex user data source schema. Must have a region specified in the provider configuration.
|
||||
---
|
||||
|
||||
# stackit_postgresflex_user (Data Source)
|
||||
|
||||
PostgresFlex user data source schema. Must have a `region` specified in the provider configuration.
|
||||
Postgres Flex user data source schema. Must have a `region` specified in the provider configuration.
|
||||
|
||||
## Example Usage
|
||||
|
||||
|
|
|
|||
37
docs/resources/postgresflex_database.md
Normal file
37
docs/resources/postgresflex_database.md
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "stackit_postgresflex_database Resource - stackit"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Postgres Flex database resource schema. Must have a region specified in the provider configuration.
|
||||
---
|
||||
|
||||
# stackit_postgresflex_database (Resource)
|
||||
|
||||
Postgres Flex database resource schema. Must have a `region` specified in the provider configuration.
|
||||
|
||||
## Example Usage
|
||||
|
||||
```terraform
|
||||
resource "stackit_postgresflex_database" "example" {
|
||||
project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
instance_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
name = "mydb"
|
||||
owner = "myusername"
|
||||
}
|
||||
```
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `instance_id` (String) ID of the Postgres Flex instance.
|
||||
- `name` (String) Database name.
|
||||
- `owner` (String) Username of the database owner.
|
||||
- `project_id` (String) STACKIT project ID to which the instance is associated.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `database_id` (String) Database ID.
|
||||
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`instance_id`,`database_id`".
|
||||
|
|
@ -3,12 +3,12 @@
|
|||
page_title: "stackit_postgresflex_instance Resource - stackit"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
PostgresFlex instance resource schema. Must have a region specified in the provider configuration.
|
||||
Postgres Flex instance resource schema. Must have a region specified in the provider configuration.
|
||||
---
|
||||
|
||||
# stackit_postgresflex_instance (Resource)
|
||||
|
||||
PostgresFlex instance resource schema. Must have a `region` specified in the provider configuration.
|
||||
Postgres Flex instance resource schema. Must have a `region` specified in the provider configuration.
|
||||
|
||||
## Example Usage
|
||||
|
||||
|
|
|
|||
|
|
@ -3,12 +3,12 @@
|
|||
page_title: "stackit_postgresflex_user Resource - stackit"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
PostgresFlex user resource schema. Must have a region specified in the provider configuration.
|
||||
Postgres Flex user resource schema. Must have a region specified in the provider configuration.
|
||||
---
|
||||
|
||||
# stackit_postgresflex_user (Resource)
|
||||
|
||||
PostgresFlex user resource schema. Must have a `region` specified in the provider configuration.
|
||||
Postgres Flex user resource schema. Must have a `region` specified in the provider configuration.
|
||||
|
||||
## Example Usage
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
data "stackit_postgresflex_database" "example" {
|
||||
project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
instance_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
resource "stackit_postgresflex_database" "example" {
|
||||
project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
instance_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
name = "mydb"
|
||||
owner = "myusername"
|
||||
}
|
||||
169
stackit/internal/services/postgresflex/database/datasource.go
Normal file
169
stackit/internal/services/postgresflex/database/datasource.go
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &databaseDataSource{}
|
||||
)
|
||||
|
||||
// NewDatabaseDataSource is a helper function to simplify the provider implementation.
|
||||
func NewDatabaseDataSource() datasource.DataSource {
|
||||
return &databaseDataSource{}
|
||||
}
|
||||
|
||||
// databaseDataSource is the data source implementation.
|
||||
type databaseDataSource struct {
|
||||
client *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (r *databaseDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_database"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the data source.
|
||||
func (r *databaseDataSource) 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 {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type 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 {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v. This is an error related to the provider configuration, not to the data source configuration", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex database client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *databaseDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex database resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`database_id`\".",
|
||||
"database_id": "Database ID.",
|
||||
"instance_id": "ID of the Postgres Flex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Database name.",
|
||||
"owner": "Username of the database owner.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"database_id": schema.StringAttribute{
|
||||
Description: descriptions["database_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"owner": schema.StringAttribute{
|
||||
Description: descriptions["owner"],
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *databaseDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
databaseResp, err := getDatabase(ctx, r.client, projectId, instanceId, databaseId)
|
||||
if err != nil {
|
||||
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
|
||||
if ok && oapiErr.StatusCode == http.StatusNotFound {
|
||||
resp.State.RemoveResource(ctx)
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapFields(databaseResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex database read")
|
||||
}
|
||||
386
stackit/internal/services/postgresflex/database/resource.go
Normal file
386
stackit/internal/services/postgresflex/database/resource.go
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/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/core/oapierror"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &databaseResource{}
|
||||
_ resource.ResourceWithConfigure = &databaseResource{}
|
||||
_ resource.ResourceWithImportState = &databaseResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
DatabaseId types.String `tfsdk:"database_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Owner types.String `tfsdk:"owner"`
|
||||
}
|
||||
|
||||
// NewDatabaseResource is a helper function to simplify the provider implementation.
|
||||
func NewDatabaseResource() resource.Resource {
|
||||
return &databaseResource{}
|
||||
}
|
||||
|
||||
// databaseResource is the resource implementation.
|
||||
type databaseResource struct {
|
||||
client *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *databaseResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_database"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *databaseResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
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 {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v. This is an error related to the provider configuration, not to the resource configuration", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Postgres Flex database client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *databaseResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Postgres Flex database resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`database_id`\".",
|
||||
"database_id": "Database ID.",
|
||||
"instance_id": "ID of the Postgres Flex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Database name.",
|
||||
"owner": "Username of the database owner.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"database_id": schema.StringAttribute{
|
||||
Description: descriptions["database_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"owner": schema.StringAttribute{
|
||||
Description: descriptions["owner"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *databaseResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new database
|
||||
databaseResp, err := r.client.CreateDatabase(ctx, projectId, instanceId).CreateDatabasePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if databaseResp == nil || databaseResp.Id == nil || *databaseResp.Id == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", "API didn't return database Id. A database might have been created")
|
||||
return
|
||||
}
|
||||
databaseId := *databaseResp.Id
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
database, err := getDatabase(ctx, r.client, projectId, instanceId, databaseId)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Getting database details after creation: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(database, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating database", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex database created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *databaseResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
databaseResp, err := getDatabase(ctx, r.client, projectId, instanceId, databaseId)
|
||||
if err != nil {
|
||||
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
|
||||
if ok && oapiErr.StatusCode == http.StatusNotFound {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(databaseResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading database", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex database read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *databaseResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating database", "Database can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *databaseResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
databaseId := model.DatabaseId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "database_id", databaseId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteDatabase(ctx, projectId, instanceId, databaseId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting database", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
tflog.Info(ctx, "Postgres Flex database deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
|
||||
func (r *databaseResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing database",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[database_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database_id"), idParts[2])...)
|
||||
core.LogAndAddWarning(ctx, &resp.Diagnostics,
|
||||
"Postgresflex database imported with empty password",
|
||||
"The database password is not imported as it is only available upon creation of a new database. The password field will be empty.",
|
||||
)
|
||||
tflog.Info(ctx, "Postgres Flex database state imported")
|
||||
}
|
||||
|
||||
func mapFields(databaseResp *postgresflex.InstanceDatabase, model *Model) error {
|
||||
if databaseResp == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if databaseResp.Id == nil || *databaseResp.Id == "" {
|
||||
return fmt.Errorf("id not present")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var databaseId string
|
||||
if model.DatabaseId.ValueString() != "" {
|
||||
databaseId = model.DatabaseId.ValueString()
|
||||
} else if databaseResp.Id != nil {
|
||||
databaseId = *databaseResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("database id not present")
|
||||
}
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
databaseId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.DatabaseId = types.StringValue(databaseId)
|
||||
model.Name = types.StringPointerValue(databaseResp.Name)
|
||||
|
||||
if databaseResp.Options != nil {
|
||||
owner, ok := (*databaseResp.Options)["owner"]
|
||||
if ok {
|
||||
ownerStr, ok := owner.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("owner is not a string")
|
||||
}
|
||||
model.Owner = types.StringValue(ownerStr)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model) (*postgresflex.CreateDatabasePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
return &postgresflex.CreateDatabasePayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Options: &map[string]string{
|
||||
"owner": model.Owner.ValueString(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// The API does not have a GetDatabase endpoint, only ListDatabases
|
||||
func getDatabase(ctx context.Context, client *postgresflex.APIClient, projectId, instanceId, databaseId string) (*postgresflex.InstanceDatabase, error) {
|
||||
resp, err := client.ListDatabases(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil || resp.Databases == nil {
|
||||
return nil, fmt.Errorf("response is nil")
|
||||
}
|
||||
for _, database := range *resp.Databases {
|
||||
if database.Id != nil && *database.Id == databaseId {
|
||||
return &database, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("database not found")
|
||||
}
|
||||
179
stackit/internal/services/postgresflex/database/resource_test.go
Normal file
179
stackit/internal/services/postgresflex/database/resource_test.go
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.InstanceDatabase
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr("uid"),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
DatabaseId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringNull(),
|
||||
Owner: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr("uid"),
|
||||
Name: utils.Ptr("dbname"),
|
||||
Options: &map[string]interface{}{
|
||||
"owner": "username",
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
DatabaseId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("dbname"),
|
||||
Owner: types.StringValue("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr("uid"),
|
||||
Name: utils.Ptr(""),
|
||||
Options: &map[string]interface{}{
|
||||
"owner": "",
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
DatabaseId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue(""),
|
||||
Owner: types.StringValue(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"empty_response",
|
||||
&postgresflex.InstanceDatabase{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.InstanceDatabase{
|
||||
Id: utils.Ptr(""),
|
||||
Name: utils.Ptr("dbname"),
|
||||
Options: &map[string]interface{}{
|
||||
"owner": "username",
|
||||
},
|
||||
},
|
||||
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)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *postgresflex.CreateDatabasePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Name: types.StringValue("dbname"),
|
||||
Owner: types.StringValue("username"),
|
||||
},
|
||||
&postgresflex.CreateDatabasePayload{
|
||||
Name: utils.Ptr("dbname"),
|
||||
Options: &map[string]string{
|
||||
"owner": "username",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields",
|
||||
&Model{
|
||||
Name: types.StringNull(),
|
||||
Owner: types.StringNull(),
|
||||
},
|
||||
&postgresflex.CreateDatabasePayload{
|
||||
Name: nil,
|
||||
Options: &map[string]string{
|
||||
"owner": "",
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -73,13 +73,13 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
|
|||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex instance client configured")
|
||||
tflog.Info(ctx, "Postgres Flex instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex instance data source schema. Must have a `region` specified in the provider configuration.",
|
||||
"main": "Postgres Flex instance data source schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
|
|
@ -216,5 +216,5 @@ func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadReques
|
|||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance read")
|
||||
tflog.Info(ctx, "Postgres Flex instance read")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -127,13 +127,13 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
|
|||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex instance client configured")
|
||||
tflog.Info(ctx, "Postgres Flex instance client configured")
|
||||
}
|
||||
|
||||
// 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. Must have a `region` specified in the provider configuration.",
|
||||
"main": "Postgres Flex instance resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
|
|
@ -314,7 +314,7 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
|
|||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance created")
|
||||
tflog.Info(ctx, "Postgres Flex instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
|
|
@ -374,7 +374,7 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
|
|||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance read")
|
||||
tflog.Info(ctx, "Postgres Flex instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
|
|
@ -478,7 +478,7 @@ func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteReques
|
|||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance deleted")
|
||||
tflog.Info(ctx, "Postgres Flex instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
|
|
|
|||
|
|
@ -37,11 +37,16 @@ var instanceResource = map[string]string{
|
|||
|
||||
// User resource data
|
||||
var userResource = map[string]string{
|
||||
"username": fmt.Sprintf("tf-acc-user-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlpha)),
|
||||
"role": "login",
|
||||
"username": fmt.Sprintf("tfaccuser%s", acctest.RandStringFromCharSet(4, acctest.CharSetAlpha)),
|
||||
"role": "createdb",
|
||||
"project_id": instanceResource["project_id"],
|
||||
}
|
||||
|
||||
// Database resource data
|
||||
var databaseResource = map[string]string{
|
||||
"name": fmt.Sprintf("tfaccdb%s", acctest.RandStringFromCharSet(4, acctest.CharSetAlphaNum)),
|
||||
}
|
||||
|
||||
func configResources(backupSchedule string) string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
|
@ -69,6 +74,13 @@ func configResources(backupSchedule string) string {
|
|||
username = "%s"
|
||||
roles = ["%s"]
|
||||
}
|
||||
|
||||
resource "stackit_postgresflex_database" "database" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
name = "%s"
|
||||
owner = stackit_postgresflex_user.user.username
|
||||
}
|
||||
`,
|
||||
testutil.PostgresFlexProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
|
|
@ -83,6 +95,7 @@ func configResources(backupSchedule string) string {
|
|||
instanceResource["version"],
|
||||
userResource["username"],
|
||||
userResource["role"],
|
||||
databaseResource["name"],
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -122,6 +135,21 @@ func TestAccPostgresFlexFlexResource(t *testing.T) {
|
|||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_user.user", "password"),
|
||||
|
||||
// Database
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_database.database", "project_id",
|
||||
"stackit_postgresflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_database.database", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_database.database", "name", databaseResource["name"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_database.database", "owner",
|
||||
"stackit_postgresflex_user.user", "username",
|
||||
),
|
||||
),
|
||||
},
|
||||
// data source
|
||||
|
|
@ -139,6 +167,12 @@ func TestAccPostgresFlexFlexResource(t *testing.T) {
|
|||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
user_id = stackit_postgresflex_user.user.user_id
|
||||
}
|
||||
|
||||
data "stackit_postgresflex_database" "database" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
database_id = stackit_postgresflex_database.database.database_id
|
||||
}
|
||||
`,
|
||||
configResources(instanceResource["backup_schedule"]),
|
||||
),
|
||||
|
|
@ -176,6 +210,18 @@ func TestAccPostgresFlexFlexResource(t *testing.T) {
|
|||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "roles.0", userResource["role"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "port"),
|
||||
|
||||
// Database data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_database.database", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_database.database", "name", databaseResource["name"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_database.database", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_database.database", "owner",
|
||||
"data.stackit_postgresflex_user.user", "username",
|
||||
),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
|
|
@ -218,6 +264,27 @@ func TestAccPostgresFlexFlexResource(t *testing.T) {
|
|||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"password"},
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_postgresflex_database.database",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresflex_database.database"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresflex_database.database")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
databaseId, ok := r.Primary.Attributes["database_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute database_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, databaseId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: configResources(instanceResource["backup_schedule_updated"]),
|
||||
|
|
@ -249,7 +316,9 @@ func testAccCheckPostgresFlexDestroy(s *terraform.State) error {
|
|||
var client *postgresflex.APIClient
|
||||
var err error
|
||||
if testutil.PostgresFlexCustomEndpoint == "" {
|
||||
client, err = postgresflex.NewAPIClient()
|
||||
client, err = postgresflex.NewAPIClient(
|
||||
config.WithRegion("eu01"),
|
||||
)
|
||||
} else {
|
||||
client, err = postgresflex.NewAPIClient(
|
||||
config.WithEndpoint(testutil.PostgresFlexCustomEndpoint),
|
||||
|
|
@ -282,11 +351,15 @@ func testAccCheckPostgresFlexDestroy(s *terraform.State) error {
|
|||
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)
|
||||
return fmt.Errorf("deleting instance %s during CheckDestroy: %w", *items[i].Id, err)
|
||||
}
|
||||
_, err = wait.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 fmt.Errorf("deleting instance %s during CheckDestroy: waiting for deletion %w", *items[i].Id, err)
|
||||
}
|
||||
err = client.ForceDeleteInstanceExecute(ctx, testutil.ProjectId, *items[i].Id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("force deleting instance %s during CheckDestroy: %w", *items[i].Id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,13 +84,13 @@ func (r *userDataSource) Configure(ctx context.Context, req datasource.Configure
|
|||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex user client configured")
|
||||
tflog.Info(ctx, "Postgres Flex user client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex user data source schema. Must have a `region` specified in the provider configuration.",
|
||||
"main": "Postgres Flex user data source schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal data source. ID. It is structured as \"`project_id`,`instance_id`,`user_id`\".",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
|
|
@ -182,7 +182,7 @@ func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
|
|||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user read")
|
||||
tflog.Info(ctx, "Postgres Flex user read")
|
||||
}
|
||||
|
||||
func mapDataSourceFields(userResp *postgresflex.GetUserResponse, model *DataSourceModel) error {
|
||||
|
|
|
|||
|
|
@ -96,7 +96,7 @@ func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequ
|
|||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex user client configured")
|
||||
tflog.Info(ctx, "Postgres Flex user client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
|
|
@ -104,7 +104,7 @@ func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp
|
|||
rolesOptions := []string{"login", "createdb"}
|
||||
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex user resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"main": "Postgres Flex user resource schema. Must have a `region` specified in the provider configuration.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`user_id`\".",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
|
|
@ -242,7 +242,7 @@ func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, r
|
|||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user created")
|
||||
tflog.Info(ctx, "Postgres Flex user created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
|
|
@ -284,7 +284,7 @@ func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp
|
|||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user read")
|
||||
tflog.Info(ctx, "Postgres Flex user read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
|
|
@ -320,7 +320,7 @@ func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, r
|
|||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user deleted")
|
||||
tflog.Info(ctx, "Postgres Flex user deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ import (
|
|||
objecStorageCredentialsGroup "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/objectstorage/credentialsgroup"
|
||||
openSearchCredential "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/opensearch/credential"
|
||||
openSearchInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/opensearch/instance"
|
||||
postgresFlexDatabase "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/database"
|
||||
postgresFlexInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/instance"
|
||||
postgresFlexUser "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresflex/user"
|
||||
postgresCredential "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/postgresql/credential"
|
||||
|
|
@ -394,6 +395,7 @@ func (p *Provider) DataSources(_ context.Context) []func() datasource.DataSource
|
|||
objecStorageCredential.NewCredentialDataSource,
|
||||
openSearchInstance.NewInstanceDataSource,
|
||||
openSearchCredential.NewCredentialDataSource,
|
||||
postgresFlexDatabase.NewDatabaseDataSource,
|
||||
postgresFlexInstance.NewInstanceDataSource,
|
||||
postgresFlexUser.NewUserDataSource,
|
||||
postgresInstance.NewInstanceDataSource,
|
||||
|
|
@ -437,6 +439,7 @@ func (p *Provider) Resources(_ context.Context) []func() resource.Resource {
|
|||
objecStorageCredential.NewCredentialResource,
|
||||
openSearchInstance.NewInstanceResource,
|
||||
openSearchCredential.NewCredentialResource,
|
||||
postgresFlexDatabase.NewDatabaseResource,
|
||||
postgresFlexInstance.NewInstanceResource,
|
||||
postgresFlexUser.NewUserResource,
|
||||
postgresInstance.NewInstanceResource,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue