Logging and error handling improvements, bug fixes (#21)

- Uniformed logs and diagnostics:
  - Logging and adding to diagnostics is done by the highest level function (Create/Read/Update/Delete/Import) using `LogAndAddError`
  - Lower-level routines' signature changed to return error instead of writing to diagnostics
  - Standardize summary and details across services
  - Removed manual adding of relevant variables to details (they're in the context, TF adds them to logs)
- Changed validators to be closer to official implementation
- Fix logging wrong output after wait
- Fix Argus checking wrong diagnostics
- Fix Resource Manager not updating state after project update
- Fix unnecessary pointer in LogAndAddError
This commit is contained in:
Henrique Santos 2023-09-21 14:52:52 +01:00 committed by GitHub
parent 29b8c91999
commit 4e8514df00
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
51 changed files with 1389 additions and 1092 deletions

View file

@ -33,7 +33,7 @@ data "stackit_logme_instance" "example" {
- `cf_organization_guid` (String) - `cf_organization_guid` (String)
- `cf_space_guid` (String) - `cf_space_guid` (String)
- `dashboard_url` (String) - `dashboard_url` (String)
- `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`zone_id`". - `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`instance_id`".
- `image_url` (String) - `image_url` (String)
- `name` (String) Instance name. - `name` (String) Instance name.
- `parameters` (Attributes) (see [below for nested schema](#nestedatt--parameters)) - `parameters` (Attributes) (see [below for nested schema](#nestedatt--parameters))

View file

@ -34,7 +34,7 @@ data "stackit_mariadb_credentials" "example" {
- `host` (String) - `host` (String)
- `hosts` (List of String) - `hosts` (List of String)
- `http_api_uri` (String) - `http_api_uri` (String)
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`instance_id`,`credentials_id`". - `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`instance_id`,`credentials_id`".
- `name` (String) - `name` (String)
- `password` (String, Sensitive) - `password` (String, Sensitive)
- `port` (Number) - `port` (Number)

View file

@ -33,7 +33,7 @@ data "stackit_mariadb_instance" "example" {
- `cf_organization_guid` (String) - `cf_organization_guid` (String)
- `cf_space_guid` (String) - `cf_space_guid` (String)
- `dashboard_url` (String) - `dashboard_url` (String)
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`instance_id`". - `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`instance_id`".
- `image_url` (String) - `image_url` (String)
- `name` (String) Instance name. - `name` (String) Instance name.
- `parameters` (Attributes) (see [below for nested schema](#nestedatt--parameters)) - `parameters` (Attributes) (see [below for nested schema](#nestedatt--parameters))

View file

@ -33,7 +33,7 @@ resource "stackit_mariadb_credentials" "example" {
- `host` (String) - `host` (String)
- `hosts` (List of String) - `hosts` (List of String)
- `http_api_uri` (String) - `http_api_uri` (String)
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`instance_id`,`credentials_id`". - `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`instance_id`,`credentials_id`".
- `name` (String) - `name` (String)
- `password` (String, Sensitive) - `password` (String, Sensitive)
- `port` (Number) - `port` (Number)

View file

@ -52,5 +52,5 @@ func DiagsToError(diags diag.Diagnostics) error {
// LogAndAddError Logs the error and adds it to the diags // LogAndAddError Logs the error and adds it to the diags
func LogAndAddError(ctx context.Context, diags *diag.Diagnostics, summary, detail string) { func LogAndAddError(ctx context.Context, diags *diag.Diagnostics, summary, detail string) {
tflog.Error(ctx, summary) tflog.Error(ctx, summary)
(*diags).AddError(summary, detail) diags.AddError(summary, detail)
} }

View file

@ -2,6 +2,7 @@ package stackit
import ( import (
"context" "context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/provider" "github.com/hashicorp/terraform-plugin-framework/provider"
@ -225,10 +226,7 @@ func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest,
} }
roundTripper, err := sdkauth.SetupAuth(sdkConfig) roundTripper, err := sdkauth.SetupAuth(sdkConfig)
if err != nil { if err != nil {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring provider", fmt.Sprintf("Setting up authentication: %v", err))
"Unable to Setup SDK",
err.Error(),
)
return return
} }
@ -274,7 +272,7 @@ func (p *Provider) Resources(_ context.Context) []func() resource.Resource {
postgresInstance.NewInstanceResource, postgresInstance.NewInstanceResource,
postgresCredentials.NewCredentialsResource, postgresCredentials.NewCredentialsResource,
logMeInstance.NewInstanceResource, logMeInstance.NewInstanceResource,
logMeCredentials.NewlogmeCredentialsResource, logMeCredentials.NewCredentialsResource,
mariaDBInstance.NewInstanceResource, mariaDBInstance.NewInstanceResource,
mariaDBCredentials.NewCredentialsResource, mariaDBCredentials.NewCredentialsResource,
openSearchInstance.NewInstanceResource, openSearchInstance.NewInstanceResource,

View file

@ -49,7 +49,7 @@ func (r *credentialResource) Metadata(_ context.Context, req resource.MetadataRe
} }
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *credentialResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *credentialResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -57,7 +57,7 @@ func (r *credentialResource) Configure(_ context.Context, req resource.Configure
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -76,10 +76,12 @@ func (r *credentialResource) Configure(_ context.Context, req resource.Configure
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", err.Error())
return return
} }
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "Argus credential client configured")
} }
func (r *credentialResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { func (r *credentialResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
@ -148,17 +150,20 @@ func (r *credentialResource) Create(ctx context.Context, req resource.CreateRequ
got, err := r.client.CreateCredential(ctx, instanceId, projectId).Execute() got, err := r.client.CreateCredential(ctx, instanceId, projectId).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating credential", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credential", fmt.Sprintf("Calling API: %v", err))
return return
} }
err = mapFields(got.Credentials, &model) err = mapFields(got.Credentials, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credential", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, &model) diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "ARGUS credential created") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus credential created")
} }
func mapFields(r *argus.Credential, model *Model) error { func mapFields(r *argus.Credential, model *Model) error {
@ -202,17 +207,20 @@ func (r *credentialResource) Read(ctx context.Context, req resource.ReadRequest,
userName := model.Username.ValueString() userName := model.Username.ValueString()
_, err := r.client.GetCredential(ctx, instanceId, projectId, userName).Execute() _, err := r.client.GetCredential(ctx, instanceId, projectId, userName).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error reading credential", fmt.Sprintf("Project id = %s, instance id = %s, username = %s: %v", projectId, instanceId, userName, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credential", fmt.Sprintf("Calling API: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "ARGUS credential read") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus credential read")
} }
func (r *credentialResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Update shouldn't be called // Update shouldn't be called
resp.Diagnostics.AddError("Error updating credentials", "credentials can't be updated") core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credential", "Credential can't be updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
@ -229,8 +237,8 @@ func (r *credentialResource) Delete(ctx context.Context, req resource.DeleteRequ
userName := model.Username.ValueString() userName := model.Username.ValueString()
_, err := r.client.DeleteCredential(ctx, instanceId, projectId, userName).Execute() _, err := r.client.DeleteCredential(ctx, instanceId, projectId, userName).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error deleting credential", "project id = "+projectId+", instance id = "+instanceId+", username = "+userName+", "+err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credential", fmt.Sprintf("Calling API: %v", err))
return return
} }
tflog.Info(ctx, "ARGUS credential deleted") tflog.Info(ctx, "Argus credential deleted")
} }

View file

@ -9,6 +9,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator" "github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/config" "github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/argus" "github.com/stackitcloud/stackit-sdk-go/services/argus"
"github.com/stackitcloud/terraform-provider-stackit/stackit/core" "github.com/stackitcloud/terraform-provider-stackit/stackit/core"
@ -35,7 +36,7 @@ func (d *instanceDataSource) Metadata(_ context.Context, req datasource.Metadata
resp.TypeName = req.ProviderTypeName + "_argus_instance" resp.TypeName = req.ProviderTypeName + "_argus_instance"
} }
func (d *instanceDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { func (d *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -46,7 +47,7 @@ func (d *instanceDataSource) Configure(_ context.Context, req datasource.Configu
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -62,13 +63,11 @@ func (d *instanceDataSource) Configure(_ context.Context, req datasource.Configu
) )
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
"Could not Configure API Client",
err.Error(),
)
return return
} }
d.client = apiClient d.client = apiClient
tflog.Info(ctx, "Argus instance client configured")
} }
// Schema defines the schema for the data source. // Schema defines the schema for the data source.
@ -202,28 +201,29 @@ func (d *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaReques
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (d *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (d *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state Model var model Model
diags := req.Config.Get(ctx, &state) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := state.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
instanceId := state.InstanceId.ValueString() instanceId := model.InstanceId.ValueString()
instanceResponse, err := d.client.GetInstance(ctx, instanceId, projectId).Execute() instanceResponse, err := d.client.GetInstance(ctx, instanceId, projectId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &diags, "Unable to read instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
err = mapFields(ctx, instanceResponse, &state) err = mapFields(ctx, instanceResponse, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &diags, "Mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, state) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
tflog.Info(ctx, "Argus instance read")
} }

View file

@ -8,7 +8,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema"
@ -17,6 +16,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator" "github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/config" "github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/argus" "github.com/stackitcloud/stackit-sdk-go/services/argus"
"github.com/stackitcloud/terraform-provider-stackit/stackit/core" "github.com/stackitcloud/terraform-provider-stackit/stackit/core"
@ -75,7 +75,7 @@ func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequ
} }
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *instanceResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -83,7 +83,7 @@ func (r *instanceResource) Configure(_ context.Context, req resource.ConfigureRe
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -102,10 +102,12 @@ func (r *instanceResource) Configure(_ context.Context, req resource.ConfigureRe
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "Argus instance client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -264,48 +266,50 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
r.loadPlanId(ctx, &resp.Diagnostics, &model) err := r.loadPlanId(ctx, &model)
if diags.HasError() { if err != nil {
core.LogAndAddError(ctx, &diags, "Failed to load argus service plan", "plan "+model.PlanName.ValueString()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
return return
} }
// Generate API request body from model // Generate API request body from model
payload, err := toCreatePayload(&model) payload, err := toCreatePayload(&model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Creating API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute() createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
instanceId := createResp.InstanceId instanceId := createResp.InstanceId
if instanceId == nil || *instanceId == "" { ctx = tflog.SetField(ctx, "instance_id", instanceId)
resp.Diagnostics.AddError("Error creating instance", "API didn't return an instance id")
return
}
wr, err := argus.CreateInstanceWaitHandler(ctx, r.client, *instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx) wr, err := argus.CreateInstanceWaitHandler(ctx, r.client, *instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
return return
} }
got, ok := wr.(*argus.InstanceResponse) got, ok := wr.(*argus.InstanceResponse)
if !ok { if !ok {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(ctx, got, &model) err = mapFields(ctx, got, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id %s, instance id %s: %v", projectId, *instanceId, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set state to fully populated data // Set state to fully populated data
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus instance created")
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
@ -318,22 +322,28 @@ func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, r
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString() instanceId := model.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, instanceId, projectId).Execute() instanceResp, err := r.client.GetInstance(ctx, instanceId, projectId).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error reading instance", fmt.Sprintf("Project id = %s, instance id = %s: %v", projectId, instanceId, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(ctx, instanceResp, &model) err = mapFields(ctx, instanceResp, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id %s, instance id %s: %v", projectId, instanceId, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed model // Set refreshed model
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus instance created")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
@ -348,42 +358,46 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString() instanceId := model.InstanceId.ValueString()
r.loadPlanId(ctx, &resp.Diagnostics, &model) err := r.loadPlanId(ctx, &model)
if diags.HasError() { if err != nil {
core.LogAndAddError(ctx, &diags, "Failed to load argus service plan", "plan "+model.PlanName.ValueString()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
return return
} }
// Generate API request body from model // Generate API request body from model
payload, err := toUpdatePayload(&model) payload, err := toUpdatePayload(&model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error updating instance", fmt.Sprintf("Could not create API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
// Update existing instance // Update existing instance
_, err = r.client.UpdateInstance(ctx, instanceId, projectId).UpdateInstancePayload(*payload).Execute() _, err = r.client.UpdateInstance(ctx, instanceId, projectId).UpdateInstancePayload(*payload).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error updating instance", "project id = "+projectId+", instance Id = "+instanceId+", "+err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
wr, err := argus.UpdateInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx) wr, err := argus.UpdateInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error updating instance", fmt.Sprintf("Instance update waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
return return
} }
got, ok := wr.(*argus.InstanceResponse) got, ok := wr.(*argus.InstanceResponse)
if !ok { if !ok {
resp.Diagnostics.AddError("Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
err = mapFields(ctx, got, &model) err = mapFields(ctx, got, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error mapping fields in update", "project id = "+projectId+", instance Id = "+instanceId+", "+err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus instance updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
@ -402,14 +416,16 @@ func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteReques
// Delete existing instance // Delete existing instance
_, err := r.client.DeleteInstance(ctx, instanceId, projectId).Execute() _, err := r.client.DeleteInstance(ctx, instanceId, projectId).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error deleting instance", "project id = "+projectId+", instance Id = "+instanceId+", "+err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
_, err = argus.DeleteInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(10 * time.Minute).WaitWithContext(ctx) _, err = argus.DeleteInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
return return
} }
tflog.Info(ctx, "Argus instance deleted")
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
@ -418,8 +434,8 @@ func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportS
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing instance",
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID), fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
) )
return return
@ -427,6 +443,7 @@ func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportS
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) 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("instance_id"), idParts[1])...)
tflog.Info(ctx, "Argus instance state imported")
} }
func mapFields(ctx context.Context, r *argus.InstanceResponse, model *Model) error { func mapFields(ctx context.Context, r *argus.InstanceResponse, model *Model) error {
@ -529,12 +546,11 @@ func toUpdatePayload(model *Model) (*argus.UpdateInstancePayload, error) {
}, nil }, nil
} }
func (r *instanceResource) loadPlanId(ctx context.Context, diags *diag.Diagnostics, model *Model) { func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
res, err := r.client.GetPlans(ctx, projectId).Execute() res, err := r.client.GetPlans(ctx, projectId).Execute()
if err != nil { if err != nil {
diags.AddError("Failed to list argus plans", err.Error()) return err
return
} }
planName := model.PlanName.ValueString() planName := model.PlanName.ValueString()
@ -552,7 +568,7 @@ func (r *instanceResource) loadPlanId(ctx context.Context, diags *diag.Diagnosti
avl = fmt.Sprintf("%s\n- %s", avl, *p.Name) avl = fmt.Sprintf("%s\n- %s", avl, *p.Name)
} }
if model.PlanId.ValueString() == "" { if model.PlanId.ValueString() == "" {
diags.AddError("Invalid plan_name", fmt.Sprintf("Couldn't find plan_name '%s', available names are:%s", planName, avl)) return fmt.Errorf("couldn't find plan_name '%s', available names are: %s", planName, avl)
return
} }
return nil
} }

View file

@ -37,7 +37,7 @@ func (d *scrapeConfigDataSource) Metadata(_ context.Context, req datasource.Meta
resp.TypeName = req.ProviderTypeName + "_argus_scrapeconfig" resp.TypeName = req.ProviderTypeName + "_argus_scrapeconfig"
} }
func (d *scrapeConfigDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { func (d *scrapeConfigDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -48,7 +48,7 @@ func (d *scrapeConfigDataSource) Configure(_ context.Context, req datasource.Con
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -64,10 +64,7 @@ func (d *scrapeConfigDataSource) Configure(_ context.Context, req datasource.Con
) )
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
"Could not Configure API Client",
err.Error(),
)
return return
} }
d.client = apiClient d.client = apiClient
@ -204,13 +201,13 @@ func (d *scrapeConfigDataSource) Read(ctx context.Context, req datasource.ReadRe
scResp, err := d.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute() scResp, err := d.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &diags, "Unable to read scrape config", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to read scrape config", err.Error())
return return
} }
err = mapFields(scResp.Data, &model) err = mapFields(scResp.Data, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &diags, "Mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error())
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)

View file

@ -86,7 +86,7 @@ func (r *scrapeConfigResource) Metadata(_ context.Context, req resource.Metadata
} }
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *scrapeConfigResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *scrapeConfigResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -94,7 +94,7 @@ func (r *scrapeConfigResource) Configure(_ context.Context, req resource.Configu
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -113,10 +113,11 @@ func (r *scrapeConfigResource) Configure(_ context.Context, req resource.Configu
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", err.Error())
return return
} }
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "Argus scrape config client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -277,33 +278,36 @@ func (r *scrapeConfigResource) Create(ctx context.Context, req resource.CreateRe
// Generate API request body from model // Generate API request body from model
payload, err := toCreatePayload(ctx, &model) payload, err := toCreatePayload(ctx, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating scrape config", fmt.Sprintf("Creating API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
_, err = r.client.CreateScrapeConfig(ctx, instanceId, projectId).CreateScrapeConfigPayload(*payload).Execute() _, err = r.client.CreateScrapeConfig(ctx, instanceId, projectId).CreateScrapeConfigPayload(*payload).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating scrape config", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Calling API: %v", err))
return return
} }
_, err = argus.CreateScrapeConfigWaitHandler(ctx, r.client, instanceId, scName, projectId).SetTimeout(3 * time.Minute).WaitWithContext(ctx) _, err = argus.CreateScrapeConfigWaitHandler(ctx, r.client, instanceId, scName, projectId).SetTimeout(3 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating scrape config", fmt.Sprintf("ScrapeConfig creation waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Scrape config creation waiting: %v", err))
return return
} }
got, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute() got, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error creating scrape config", fmt.Sprintf("ScrapeConfig creation waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Calling API for updated data: %v", err))
return return
} }
err = mapFields(got.Data, &model) err = mapFields(got.Data, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id %s, ScrapeConfig id %s: %v", projectId, scName, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set state to fully populated data // Set state to fully populated data
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "ARGUS scrape config created") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus scrape config created")
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
@ -320,20 +324,23 @@ func (r *scrapeConfigResource) Read(ctx context.Context, req resource.ReadReques
scResp, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute() scResp, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error reading scrape config", fmt.Sprintf("Project id = %s, instance id = %s, scrape config name = %s: %v", projectId, instanceId, scName, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading scrape config", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(scResp.Data, &model) err = mapFields(scResp.Data, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id = %s, instance id = %s, sc name = %s: %v", projectId, instanceId, scName, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading scrape config", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed model // Set refreshed model
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "ARGUS scrape config read") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus scrape config read")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
@ -352,12 +359,12 @@ func (r *scrapeConfigResource) Update(ctx context.Context, req resource.UpdateRe
// Generate API request body from model // Generate API request body from model
payload, err := toUpdatePayload(ctx, &model) payload, err := toUpdatePayload(ctx, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error updating scrape config", fmt.Sprintf("Could not create API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
_, err = r.client.UpdateScrapeConfig(ctx, instanceId, scName, projectId).UpdateScrapeConfigPayload(*payload).Execute() _, err = r.client.UpdateScrapeConfig(ctx, instanceId, scName, projectId).UpdateScrapeConfigPayload(*payload).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error updating scrape config", fmt.Sprintf("Project id = %s, instance id = %s, scrape config name = %s: %v", projectId, instanceId, scName, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Calling API: %v", err))
return return
} }
// We do not have an update status provided by the argus scrape config api, so we cannot use a waiter here, hence a simple sleep is used. // We do not have an update status provided by the argus scrape config api, so we cannot use a waiter here, hence a simple sleep is used.
@ -366,17 +373,20 @@ func (r *scrapeConfigResource) Update(ctx context.Context, req resource.UpdateRe
// Fetch updated ScrapeConfig // Fetch updated ScrapeConfig
scResp, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute() scResp, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error reading updated data", fmt.Sprintf("Project id %s, instance id %s, jo name %s: %v", projectId, instanceId, scName, err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Calling API for updated data: %v", err))
return return
} }
err = mapFields(scResp.Data, &model) err = mapFields(scResp.Data, &model)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error mapping fields in update", "project id = "+projectId+", instance id = "+instanceId+", scrape config name = "+scName+", "+err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "ARGUS scrape config updated") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Argus scrape config updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
@ -396,15 +406,16 @@ func (r *scrapeConfigResource) Delete(ctx context.Context, req resource.DeleteRe
// Delete existing ScrapeConfig // Delete existing ScrapeConfig
_, err := r.client.DeleteScrapeConfig(ctx, instanceId, scName, projectId).Execute() _, err := r.client.DeleteScrapeConfig(ctx, instanceId, scName, projectId).Execute()
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error deleting scrape config", "project id = "+projectId+", instance id = "+instanceId+", scrape config name = "+scName+", "+err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting scrape config", fmt.Sprintf("Calling API: %v", err))
return return
} }
_, err = argus.DeleteScrapeConfigWaitHandler(ctx, r.client, instanceId, scName, projectId).SetTimeout(1 * time.Minute).WaitWithContext(ctx) _, err = argus.DeleteScrapeConfigWaitHandler(ctx, r.client, instanceId, scName, projectId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
resp.Diagnostics.AddError("Error deleting scrape config", fmt.Sprintf("ScrapeConfig deletion waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting scrape config", fmt.Sprintf("Scrape config deletion waiting: %v", err))
return return
} }
tflog.Info(ctx, "ARGUS scrape config deleted")
tflog.Info(ctx, "Argus scrape config deleted")
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
@ -413,8 +424,8 @@ func (r *scrapeConfigResource) ImportState(ctx context.Context, req resource.Imp
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing scrape config",
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id],[name] Got: %q", req.ID), fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id],[name] Got: %q", req.ID),
) )
return return
@ -423,7 +434,7 @@ func (r *scrapeConfigResource) ImportState(ctx context.Context, req resource.Imp
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) 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("instance_id"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), idParts[2])...) resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), idParts[2])...)
tflog.Info(ctx, "ARGUS scrape config state imported") tflog.Info(ctx, "Argus scrape config state imported")
} }
func mapFields(sc *argus.Job, model *Model) error { func mapFields(sc *argus.Job, model *Model) error {

View file

@ -44,7 +44,7 @@ func (d *recordSetDataSource) Configure(ctx context.Context, req datasource.Conf
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -62,12 +62,12 @@ func (d *recordSetDataSource) Configure(ctx context.Context, req datasource.Conf
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "DNS record set client configured")
d.client = apiClient d.client = apiClient
tflog.Info(ctx, "DNS record set client configured")
} }
// Schema defines the schema for the data source. // Schema defines the schema for the data source.
@ -142,33 +142,33 @@ func (d *recordSetDataSource) Schema(_ context.Context, _ datasource.SchemaReque
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (d *recordSetDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (d *recordSetDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state Model var model Model
diags := req.Config.Get(ctx, &state) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := state.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
zoneId := state.ZoneId.ValueString() zoneId := model.ZoneId.ValueString()
recordSetId := state.RecordSetId.ValueString() recordSetId := model.RecordSetId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "zone_id", zoneId) ctx = tflog.SetField(ctx, "zone_id", zoneId)
ctx = tflog.SetField(ctx, "record_set_id", recordSetId) ctx = tflog.SetField(ctx, "record_set_id", recordSetId)
zoneResp, err := d.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute() zoneResp, err := d.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to Read record set", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Calling API: %v", err))
return return
} }
err = mapFields(zoneResp, &state) err = mapFields(zoneResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, state) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
tflog.Info(ctx, "DNS record set created") tflog.Info(ctx, "DNS record set read")
} }

View file

@ -72,7 +72,7 @@ func (r *recordSetResource) Configure(ctx context.Context, req resource.Configur
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -90,12 +90,12 @@ func (r *recordSetResource) Configure(ctx context.Context, req resource.Configur
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Debug(ctx, "DNS record set client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "DNS record set client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -225,37 +225,40 @@ func (r *recordSetResource) Create(ctx context.Context, req resource.CreateReque
// Generate API request body from model // Generate API request body from model
payload, err := toCreatePayload(&model) payload, err := toCreatePayload(&model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating recordset", fmt.Sprintf("Creating API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
// Create new recordset // Create new recordset
recordSetResp, err := r.client.CreateRecordSet(ctx, projectId, zoneId).CreateRecordSetPayload(*payload).Execute() recordSetResp, err := r.client.CreateRecordSet(ctx, projectId, zoneId).CreateRecordSetPayload(*payload).Execute()
if err != nil || recordSetResp.Rrset == nil || recordSetResp.Rrset.Id == nil { if err != nil || recordSetResp.Rrset == nil || recordSetResp.Rrset.Id == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating recordset", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Calling API: %v", err))
return return
} }
ctx = tflog.SetField(ctx, "record_set_id", *recordSetResp.Rrset.Id) ctx = tflog.SetField(ctx, "record_set_id", *recordSetResp.Rrset.Id)
wr, err := dns.CreateRecordSetWaitHandler(ctx, r.client, projectId, zoneId, *recordSetResp.Rrset.Id).SetTimeout(1 * time.Minute).WaitWithContext(ctx) wr, err := dns.CreateRecordSetWaitHandler(ctx, r.client, projectId, zoneId, *recordSetResp.Rrset.Id).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating recordset", fmt.Sprintf("Instance creation waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Instance creation waiting: %v", err))
return return
} }
got, ok := wr.(*dns.RecordSetResponse) got, ok := wr.(*dns.RecordSetResponse)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating recordset", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set state to fully populated data // Set state to fully populated data
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "DNS record set created") tflog.Info(ctx, "DNS record set created")
} }
@ -276,20 +279,23 @@ func (r *recordSetResource) Read(ctx context.Context, req resource.ReadRequest,
recordSetResp, err := r.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute() recordSetResp, err := r.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zones", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "DNS record set read") tflog.Info(ctx, "DNS record set read")
} }
@ -313,39 +319,42 @@ func (r *recordSetResource) Update(ctx context.Context, req resource.UpdateReque
// Generate API request body from model // Generate API request body from model
payload, err := toUpdatePayload(&model) payload, err := toUpdatePayload(&model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating recordset", fmt.Sprintf("Could not create API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
// Update recordset // Update recordset
_, err = r.client.UpdateRecordSet(ctx, projectId, zoneId, recordSetId).UpdateRecordSetPayload(*payload).Execute() _, err = r.client.UpdateRecordSet(ctx, projectId, zoneId, recordSetId).UpdateRecordSetPayload(*payload).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating recordset", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", err.Error())
return return
} }
wr, err := dns.UpdateRecordSetWaitHandler(ctx, r.client, projectId, zoneId, recordSetId).SetTimeout(1 * time.Minute).WaitWithContext(ctx) wr, err := dns.UpdateRecordSetWaitHandler(ctx, r.client, projectId, zoneId, recordSetId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating recordset", fmt.Sprintf("Instance update waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Instance update waiting: %v", err))
return return
} }
got, ok := wr.(*dns.RecordSetResponse) _, ok := wr.(*dns.RecordSetResponse)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating recordset", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Fetch updated record set // Fetch updated record set
recordSetResp, err := r.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute() recordSetResp, err := r.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading updated data", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Calling API for updated data: %v", err))
return return
} }
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields in update", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "DNS record set updated") tflog.Info(ctx, "DNS record set updated")
} }
@ -369,7 +378,7 @@ func (r *recordSetResource) Delete(ctx context.Context, req resource.DeleteReque
// Delete existing record set // Delete existing record set
_, err := r.client.DeleteRecordSet(ctx, projectId, zoneId, recordSetId).Execute() _, err := r.client.DeleteRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting recordset", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting record set", fmt.Sprintf("Calling API: %v", err))
} }
_, err = dns.DeleteRecordSetWaitHandler(ctx, r.client, projectId, zoneId, recordSetId).SetTimeout(1 * time.Minute).WaitWithContext(ctx) _, err = dns.DeleteRecordSetWaitHandler(ctx, r.client, projectId, zoneId, recordSetId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
@ -384,8 +393,8 @@ func (r *recordSetResource) Delete(ctx context.Context, req resource.DeleteReque
func (r *recordSetResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { func (r *recordSetResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing record set",
fmt.Sprintf("Expected import identifier with format [project_id],[zone_id],[record_set_id], got %q", req.ID), fmt.Sprintf("Expected import identifier with format [project_id],[zone_id],[record_set_id], got %q", req.ID),
) )
return return

View file

@ -46,7 +46,7 @@ func (d *zoneDataSource) Configure(ctx context.Context, req datasource.Configure
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -61,15 +61,12 @@ func (d *zoneDataSource) Configure(ctx context.Context, req datasource.Configure
) )
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
"Could not Configure API Client",
err.Error(),
)
return return
} }
tflog.Info(ctx, "DNS zone client configured")
d.client = apiClient d.client = apiClient
tflog.Info(ctx, "DNS zone client configured")
} }
// Schema defines the schema for the data source. // Schema defines the schema for the data source.
@ -180,29 +177,29 @@ func (d *zoneDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, r
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (d *zoneDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (d *zoneDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state Model var model Model
diags := req.Config.Get(ctx, &state) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := state.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
zoneId := state.ZoneId.ValueString() zoneId := model.ZoneId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "zone_id", zoneId) ctx = tflog.SetField(ctx, "zone_id", zoneId)
zoneResp, err := d.client.GetZone(ctx, projectId, zoneId).Execute() zoneResp, err := d.client.GetZone(ctx, projectId, zoneId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to Read Zone", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Calling API: %v", err))
return return
} }
err = mapFields(zoneResp, &state) err = mapFields(zoneResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, state) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return

View file

@ -85,7 +85,7 @@ func (r *zoneResource) Configure(ctx context.Context, req resource.ConfigureRequ
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -104,12 +104,12 @@ func (r *zoneResource) Configure(ctx context.Context, req resource.ConfigureRequ
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "DNS zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "DNS zone client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -318,64 +318,66 @@ func (r *zoneResource) Create(ctx context.Context, req resource.CreateRequest, r
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Calling API: %v", err))
return return
} }
if createResp.Zone.Id == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", "API didn't return zone id")
return
}
zoneId := *createResp.Zone.Id zoneId := *createResp.Zone.Id
ctx = tflog.SetField(ctx, "zone_id", zoneId) ctx = tflog.SetField(ctx, "zone_id", zoneId)
wr, err := dns.CreateZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx) wr, err := dns.CreateZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Instance creation waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Zone creation waiting: %v", err))
return return
} }
got, ok := wr.(*dns.ZoneResponse) got, ok := wr.(*dns.ZoneResponse)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set state to fully populated data // Set state to fully populated data
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "DNS zone created") tflog.Info(ctx, "DNS zone created")
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *zoneResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (r *zoneResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state Model var model Model
diags := req.State.Get(ctx, &state) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := state.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
zoneId := state.ZoneId.ValueString() zoneId := model.ZoneId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "zone_id", zoneId) ctx = tflog.SetField(ctx, "zone_id", zoneId)
zoneResp, err := r.client.GetZone(ctx, projectId, zoneId).Execute() zoneResp, err := r.client.GetZone(ctx, projectId, zoneId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zones", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(zoneResp, &state) err = mapFields(zoneResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, state) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "DNS zone read") tflog.Info(ctx, "DNS zone read")
} }
@ -396,39 +398,42 @@ func (r *zoneResource) Update(ctx context.Context, req resource.UpdateRequest, r
// Generate API request body from model // Generate API request body from model
payload, err := toUpdatePayload(&model) payload, err := toUpdatePayload(&model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Could not create API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
// Update existing zone // Update existing zone
_, err = r.client.UpdateZone(ctx, projectId, zoneId).UpdateZonePayload(*payload).Execute() _, err = r.client.UpdateZone(ctx, projectId, zoneId).UpdateZonePayload(*payload).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Calling API: %v", err))
return return
} }
wr, err := dns.UpdateZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx) wr, err := dns.UpdateZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Instance update waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Zone update waiting: %v", err))
return return
} }
got, ok := wr.(*dns.ZoneResponse) _, ok := wr.(*dns.ZoneResponse)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Fetch updated zone // Fetch updated zone
zoneResp, err := r.client.GetZone(ctx, projectId, zoneId).Execute() zoneResp, err := r.client.GetZone(ctx, projectId, zoneId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading updated data", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Calling API for updated data: %v", err))
return return
} }
err = mapFields(zoneResp, &model) err = mapFields(zoneResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields in update", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "DNS zone updated") tflog.Info(ctx, "DNS zone updated")
} }
@ -450,12 +455,12 @@ func (r *zoneResource) Delete(ctx context.Context, req resource.DeleteRequest, r
// Delete existing zone // Delete existing zone
_, err := r.client.DeleteZone(ctx, projectId, zoneId).Execute() _, err := r.client.DeleteZone(ctx, projectId, zoneId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting zone", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting zone", fmt.Sprintf("Calling API: %v", err))
return return
} }
_, err = dns.DeleteZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx) _, err = dns.DeleteZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting zone", fmt.Sprintf("Instance deletion waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting zone", fmt.Sprintf("Zone deletion waiting: %v", err))
return return
} }
@ -468,8 +473,8 @@ func (r *zoneResource) ImportState(ctx context.Context, req resource.ImportState
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing zone",
fmt.Sprintf("Expected import identifier with format: [project_id],[zone_id] Got: %q", req.ID), fmt.Sprintf("Expected import identifier with format: [project_id],[zone_id] Got: %q", req.ID),
) )
return return

View file

@ -45,7 +45,7 @@ func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.Co
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -64,12 +64,12 @@ func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.Co
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "LogMe zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "LogMe credentials client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -160,19 +160,22 @@ func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadReq
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute() recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "LogMe credentials read") tflog.Info(ctx, "LogMe credentials read")
} }

View file

@ -25,9 +25,9 @@ import (
// Ensure the implementation satisfies the expected interfaces. // Ensure the implementation satisfies the expected interfaces.
var ( var (
_ resource.Resource = &logmeCredentialsResource{} _ resource.Resource = &credentialsResource{}
_ resource.ResourceWithConfigure = &logmeCredentialsResource{} _ resource.ResourceWithConfigure = &credentialsResource{}
_ resource.ResourceWithImportState = &logmeCredentialsResource{} _ resource.ResourceWithImportState = &credentialsResource{}
) )
type Model struct { type Model struct {
@ -45,23 +45,23 @@ type Model struct {
Username types.String `tfsdk:"username"` Username types.String `tfsdk:"username"`
} }
// NewlogmeCredentialsResource is a helper function to simplify the provider implementation. // NewCredentialsResource is a helper function to simplify the provider implementation.
func NewlogmeCredentialsResource() resource.Resource { func NewCredentialsResource() resource.Resource {
return &logmeCredentialsResource{} return &credentialsResource{}
} }
// credentialsResource is the resource implementation. // credentialsResource is the resource implementation.
type logmeCredentialsResource struct { type credentialsResource struct {
client *logme.APIClient client *logme.APIClient
} }
// Metadata returns the resource type name. // Metadata returns the resource type name.
func (r *logmeCredentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_logme_credentials" resp.TypeName = req.ProviderTypeName + "_logme_credentials"
} }
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *logmeCredentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -69,7 +69,7 @@ func (r *logmeCredentialsResource) Configure(ctx context.Context, req resource.C
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -88,16 +88,16 @@ func (r *logmeCredentialsResource) Configure(ctx context.Context, req resource.C
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "logme zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "LogMe credentials client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
func (r *logmeCredentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{ descriptions := map[string]string{
"main": "LogMe credentials resource schema.", "main": "LogMe credentials resource schema.",
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".", "id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
@ -182,7 +182,7 @@ func (r *logmeCredentialsResource) Schema(_ context.Context, _ resource.SchemaRe
} }
// Create creates the resource and sets the initial Terraform state. // Create creates the resource and sets the initial Terraform state.
func (r *logmeCredentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.Plan.Get(ctx, &model) diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -214,23 +214,26 @@ func (r *logmeCredentialsResource) Create(ctx context.Context, req resource.Crea
} }
got, ok := wr.(*logme.CredentialsResponse) got, ok := wr.(*logme.CredentialsResponse)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "LogMe credentials created") tflog.Info(ctx, "LogMe credentials created")
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *logmeCredentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -246,31 +249,34 @@ func (r *logmeCredentialsResource) Read(ctx context.Context, req resource.ReadRe
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute() recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "LogMe credentials read") tflog.Info(ctx, "LogMe credentials read")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
func (r *logmeCredentialsResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Update shouldn't be called // Update shouldn't be called
resp.Diagnostics.AddError("Error updating credentials", "credentials can't be updated") core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
func (r *logmeCredentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -288,7 +294,7 @@ func (r *logmeCredentialsResource) Delete(ctx context.Context, req resource.Dele
// Delete existing record set // Delete existing record set
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute() err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
} }
_, err = logme.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx) _, err = logme.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
@ -300,11 +306,11 @@ func (r *logmeCredentialsResource) Delete(ctx context.Context, req resource.Dele
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id // The expected format of the resource import identifier is: project_id,instance_id,credentials_id
func (r *logmeCredentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing credentials",
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID), fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
) )
return return

View file

@ -44,7 +44,7 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -63,19 +63,19 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "LogMe zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "LogMe zone client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{ descriptions := map[string]string{
"main": "LogMe instance data source schema.", "main": "LogMe instance data source schema.",
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`zone_id`\".", "id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
"instance_id": "ID of the LogMe instance.", "instance_id": "ID of the LogMe instance.",
"project_id": "STACKIT Project ID to which the instance is associated.", "project_id": "STACKIT Project ID to which the instance is associated.",
"name": "Instance name.", "name": "Instance name.",
@ -152,37 +152,41 @@ func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaReques
// Read refreshes the Terraform state with the latest data. // 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 func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state Model var model Model
diags := req.Config.Get(ctx, &state) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := model.ProjectId.ValueString()
projectId := state.ProjectId.ValueString() instanceId := model.InstanceId.ValueString()
instanceId := state.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute() instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to read instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
err = mapFields(instanceResp, &state) err = mapFields(instanceResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Compute and store values not present in the API response // Compute and store values not present in the API response
loadPlanNameAndVersion(ctx, r.client, &resp.Diagnostics, &state) err = loadPlanNameAndVersion(ctx, r.client, &model)
if resp.Diagnostics.HasError() { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, &state) diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "LogMe instance read") tflog.Info(ctx, "LogMe instance read")
} }

View file

@ -8,7 +8,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr" "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/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tflog"
@ -82,7 +81,7 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -101,12 +100,12 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "logme zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "LogMe instance client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -233,11 +232,6 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if resp.Diagnostics.HasError() {
return
}
var parameters = &parametersModel{} var parameters = &parametersModel{}
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) { if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{}) diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
@ -247,6 +241,12 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
} }
} }
err := r.loadPlanId(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
return
}
// Generate API request body from model // Generate API request body from model
payload, err := toCreatePayload(&model, parameters) payload, err := toCreatePayload(&model, parameters)
if err != nil { if err != nil {
@ -268,58 +268,66 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
} }
got, ok := wr.(*logme.Instance) got, ok := wr.(*logme.Instance)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set state to fully populated data // Set state to fully populated data
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "logme 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() { if resp.Diagnostics.HasError() {
return return
} }
projectId := state.ProjectId.ValueString() tflog.Info(ctx, "LogMe instance created")
instanceId := state.InstanceId.ValueString() }
// Read refreshes the Terraform state with the latest data.
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute() instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instances", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(instanceResp, &state) err = mapFields(instanceResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Compute and store values not present in the API response // Compute and store values not present in the API response
loadPlanNameAndVersion(ctx, r.client, &resp.Diagnostics, &state) err = loadPlanNameAndVersion(ctx, r.client, &model)
if resp.Diagnostics.HasError() { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, state) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "logme instance read") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "LogMe instance read")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
@ -335,11 +343,6 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if resp.Diagnostics.HasError() {
return
}
var parameters = &parametersModel{} var parameters = &parametersModel{}
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) { if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{}) diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
@ -349,16 +352,22 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
} }
} }
err := r.loadPlanId(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
return
}
// Generate API request body from model // Generate API request body from model
payload, err := toUpdatePayload(&model, parameters) payload, err := toUpdatePayload(&model, parameters)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Could not create API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
// Update existing instance // Update existing instance
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute() err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
wr, err := logme.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx) wr, err := logme.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
@ -368,19 +377,23 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
} }
got, ok := wr.(*logme.Instance) got, ok := wr.(*logme.Instance)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields in update", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "logme instance updated") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "LogMe instance updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
@ -400,7 +413,7 @@ func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteReques
// Delete existing instance // Delete existing instance
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute() err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
_, err = logme.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx) _, err = logme.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
@ -408,7 +421,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)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
return return
} }
tflog.Info(ctx, "logme instance deleted") tflog.Info(ctx, "LogMe instance deleted")
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
@ -417,8 +430,8 @@ func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportS
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing instance",
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID), fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
) )
return return
@ -608,12 +621,11 @@ func toUpdatePayload(model *Model, parameters *parametersModel) (*logme.UpdateIn
}, nil }, nil
} }
func (r *instanceResource) loadPlanId(ctx context.Context, diags *diag.Diagnostics, model *Model) { func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
res, err := r.client.GetOfferings(ctx, projectId).Execute() res, err := r.client.GetOfferings(ctx, projectId).Execute()
if err != nil { if err != nil {
diags.AddError("Failed to list LogMe offerings", err.Error()) return fmt.Errorf("getting LogMe offerings: %w", err)
return
} }
version := model.Version.ValueString() version := model.Version.ValueString()
@ -634,26 +646,24 @@ func (r *instanceResource) loadPlanId(ctx context.Context, diags *diag.Diagnosti
} }
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil { if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
model.PlanId = types.StringPointerValue(plan.Id) model.PlanId = types.StringPointerValue(plan.Id)
return return nil
} }
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name) availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
} }
} }
if !isValidVersion { if !isValidVersion {
diags.AddError("Invalid version", fmt.Sprintf("Couldn't find version '%s', available versions are:%s", version, availableVersions)) return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
return
} }
diags.AddError("Invalid plan_name", fmt.Sprintf("Couldn't find plan_name '%s' for version %s, available names are:%s", planName, version, availablePlanNames)) return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
} }
func loadPlanNameAndVersion(ctx context.Context, client *logme.APIClient, diags *diag.Diagnostics, model *Model) { func loadPlanNameAndVersion(ctx context.Context, client *logme.APIClient, model *Model) error {
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
planId := model.PlanId.ValueString() planId := model.PlanId.ValueString()
res, err := client.GetOfferings(ctx, projectId).Execute() res, err := client.GetOfferings(ctx, projectId).Execute()
if err != nil { if err != nil {
diags.AddError("Failed to list LogMe offerings", err.Error()) return fmt.Errorf("getting LogMe offerings: %w", err)
return
} }
for _, offer := range *res.Offerings { for _, offer := range *res.Offerings {
@ -661,10 +671,10 @@ func loadPlanNameAndVersion(ctx context.Context, client *logme.APIClient, diags
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil { if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
model.PlanName = types.StringPointerValue(plan.Name) model.PlanName = types.StringPointerValue(plan.Name)
model.Version = types.StringPointerValue(offer.Version) model.Version = types.StringPointerValue(offer.Version)
return return nil
} }
} }
} }
diags.AddWarning("Failed to get plan_name and version", fmt.Sprintf("Couldn't find plan_name and version for plan_id = %s", planId)) return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
} }

View file

@ -45,7 +45,7 @@ func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.Co
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -64,19 +64,19 @@ func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.Co
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "Postgresql zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "mariadb credentials client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{ descriptions := map[string]string{
"main": "MariaDB credentials data source schema.", "main": "MariaDB credentials data source schema.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".", "id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
"credentials_id": "The credentials ID.", "credentials_id": "The credentials ID.",
"instance_id": "ID of the MariaDB instance.", "instance_id": "ID of the MariaDB instance.",
"project_id": "STACKIT project ID to which the instance is associated.", "project_id": "STACKIT project ID to which the instance is associated.",
@ -160,19 +160,22 @@ func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadReq
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute() recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "MariaDB credentials read") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "mariadb credentials read")
} }

View file

@ -25,9 +25,9 @@ import (
// Ensure the implementation satisfies the expected interfaces. // Ensure the implementation satisfies the expected interfaces.
var ( var (
_ resource.Resource = &mariaDBCredentialsResource{} _ resource.Resource = &credentialsResource{}
_ resource.ResourceWithConfigure = &mariaDBCredentialsResource{} _ resource.ResourceWithConfigure = &credentialsResource{}
_ resource.ResourceWithImportState = &mariaDBCredentialsResource{} _ resource.ResourceWithImportState = &credentialsResource{}
) )
type Model struct { type Model struct {
@ -45,23 +45,23 @@ type Model struct {
Username types.String `tfsdk:"username"` Username types.String `tfsdk:"username"`
} }
// NewPostgreSQLCredentialsResource is a helper function to simplify the provider implementation. // NewCredentialsResource is a helper function to simplify the provider implementation.
func NewCredentialsResource() resource.Resource { func NewCredentialsResource() resource.Resource {
return &mariaDBCredentialsResource{} return &credentialsResource{}
} }
// credentialsResource is the resource implementation. // credentialsResource is the resource implementation.
type mariaDBCredentialsResource struct { type credentialsResource struct {
client *mariadb.APIClient client *mariadb.APIClient
} }
// Metadata returns the resource type name. // Metadata returns the resource type name.
func (r *mariaDBCredentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_mariadb_credentials" resp.TypeName = req.ProviderTypeName + "_mariadb_credentials"
} }
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *mariaDBCredentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -69,7 +69,7 @@ func (r *mariaDBCredentialsResource) Configure(ctx context.Context, req resource
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -88,19 +88,19 @@ func (r *mariaDBCredentialsResource) Configure(ctx context.Context, req resource
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "MariaDB client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "MariaDB credentials client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
func (r *mariaDBCredentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{ descriptions := map[string]string{
"main": "MariaDB credentials resource schema.", "main": "MariaDB credentials resource schema.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".", "id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
"credentials_id": "The credentials ID.", "credentials_id": "The credentials ID.",
"instance_id": "ID of the MariaDB instance.", "instance_id": "ID of the MariaDB instance.",
"project_id": "STACKIT Project ID to which the instance is associated.", "project_id": "STACKIT Project ID to which the instance is associated.",
@ -182,7 +182,7 @@ func (r *mariaDBCredentialsResource) Schema(_ context.Context, _ resource.Schema
} }
// Create creates the resource and sets the initial Terraform state. // Create creates the resource and sets the initial Terraform state.
func (r *mariaDBCredentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.Plan.Get(ctx, &model) diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -214,23 +214,26 @@ func (r *mariaDBCredentialsResource) Create(ctx context.Context, req resource.Cr
} }
got, ok := wr.(*mariadb.CredentialsResponse) got, ok := wr.(*mariadb.CredentialsResponse)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "MariaDB credentials created") tflog.Info(ctx, "MariaDB credentials created")
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *mariaDBCredentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -246,31 +249,34 @@ func (r *mariaDBCredentialsResource) Read(ctx context.Context, req resource.Read
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute() recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "MariaDB credentials read") tflog.Info(ctx, "MariaDB credentials read")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
func (r *mariaDBCredentialsResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Update shouldn't be called // Update shouldn't be called
resp.Diagnostics.AddError("Error updating credentials", "credentials can't be updated") core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
func (r *mariaDBCredentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -288,7 +294,7 @@ func (r *mariaDBCredentialsResource) Delete(ctx context.Context, req resource.De
// Delete existing record set // Delete existing record set
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute() err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
} }
_, err = mariadb.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx) _, err = mariadb.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
@ -299,12 +305,12 @@ func (r *mariaDBCredentialsResource) Delete(ctx context.Context, req resource.De
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id // The expected format of the resource import identifier is: project_id,instance_id,credentials_id
func (r *mariaDBCredentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing credentials",
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID), fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
) )
return return
@ -313,7 +319,7 @@ func (r *mariaDBCredentialsResource) ImportState(ctx context.Context, req resour
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...) 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("instance_id"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...) resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...)
tflog.Info(ctx, "Postgresql credentials state imported") tflog.Info(ctx, "MariaDB credentials state imported")
} }
func mapFields(credentialsResp *mariadb.CredentialsResponse, model *Model) error { func mapFields(credentialsResp *mariadb.CredentialsResponse, model *Model) error {

View file

@ -44,7 +44,7 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -63,19 +63,19 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "MariaDB zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "MariaDB zone client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{ descriptions := map[string]string{
"main": "MariaDB instance data source schema.", "main": "MariaDB instance data source schema.",
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".", "id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
"instance_id": "ID of the MariaDB instance.", "instance_id": "ID of the MariaDB instance.",
"project_id": "STACKIT Project ID to which the instance is associated.", "project_id": "STACKIT Project ID to which the instance is associated.",
"name": "Instance name.", "name": "Instance name.",
@ -152,37 +152,41 @@ func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaReques
// Read refreshes the Terraform state with the latest data. // 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 func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state Model var model Model
diags := req.Config.Get(ctx, &state) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := model.ProjectId.ValueString()
projectId := state.ProjectId.ValueString() instanceId := model.InstanceId.ValueString()
instanceId := state.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute() instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to read instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
err = mapFields(instanceResp, &state) err = mapFields(instanceResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Compute and store values not present in the API response // Compute and store values not present in the API response
loadPlanNameAndVersion(ctx, r.client, &resp.Diagnostics, &state) err = loadPlanNameAndVersion(ctx, r.client, &model)
if resp.Diagnostics.HasError() { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, &state) diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "MariaDB instance read") tflog.Info(ctx, "MariaDB instance read")
} }

View file

@ -8,7 +8,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr" "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/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tflog"
@ -82,7 +81,7 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -101,12 +100,12 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "mariadb zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "MariaDB instance client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -128,6 +127,9 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: descriptions["id"], Description: descriptions["id"],
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"instance_id": schema.StringAttribute{ "instance_id": schema.StringAttribute{
Description: descriptions["instance_id"], Description: descriptions["instance_id"],
@ -187,18 +189,33 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
}, },
"cf_guid": schema.StringAttribute{ "cf_guid": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"cf_space_guid": schema.StringAttribute{ "cf_space_guid": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"dashboard_url": schema.StringAttribute{ "dashboard_url": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"image_url": schema.StringAttribute{ "image_url": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"cf_organization_guid": schema.StringAttribute{ "cf_organization_guid": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
}, },
} }
@ -215,11 +232,6 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if resp.Diagnostics.HasError() {
return
}
var parameters = &parametersModel{} var parameters = &parametersModel{}
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) { if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{}) diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
@ -229,6 +241,12 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
} }
} }
err := r.loadPlanId(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
return
}
// Generate API request body from model // Generate API request body from model
payload, err := toCreatePayload(&model, parameters) payload, err := toCreatePayload(&model, parameters)
if err != nil { if err != nil {
@ -250,58 +268,66 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
} }
got, ok := wr.(*mariadb.Instance) got, ok := wr.(*mariadb.Instance)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set state to fully populated data // Set state to fully populated data
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "mariadb 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() { if resp.Diagnostics.HasError() {
return return
} }
projectId := state.ProjectId.ValueString() tflog.Info(ctx, "MariaDB instance created")
instanceId := state.InstanceId.ValueString() }
// Read refreshes the Terraform state with the latest data.
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute() instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instances", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(instanceResp, &state) err = mapFields(instanceResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Compute and store values not present in the API response // Compute and store values not present in the API response
loadPlanNameAndVersion(ctx, r.client, &resp.Diagnostics, &state) err = loadPlanNameAndVersion(ctx, r.client, &model)
if resp.Diagnostics.HasError() { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, state) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "mariadb instance read") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "MariaDB instance read")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
@ -317,11 +343,6 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if resp.Diagnostics.HasError() {
return
}
var parameters = &parametersModel{} var parameters = &parametersModel{}
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) { if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{}) diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
@ -331,16 +352,22 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
} }
} }
err := r.loadPlanId(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
return
}
// Generate API request body from model // Generate API request body from model
payload, err := toUpdatePayload(&model, parameters) payload, err := toUpdatePayload(&model, parameters)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Could not create API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
// Update existing instance // Update existing instance
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute() err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
wr, err := mariadb.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx) wr, err := mariadb.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
@ -350,23 +377,28 @@ func (r *instanceResource) Update(ctx context.Context, req resource.UpdateReques
} }
got, ok := wr.(*mariadb.Instance) got, ok := wr.(*mariadb.Instance)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields in update", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "mariadb instance updated") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "MariaDB instance updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // 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 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 var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -381,7 +413,7 @@ func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteReques
// Delete existing instance // Delete existing instance
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute() err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
_, err = mariadb.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx) _, err = mariadb.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
@ -389,7 +421,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)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
return return
} }
tflog.Info(ctx, "mariadb instance deleted") tflog.Info(ctx, "MariaDB instance deleted")
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
@ -398,8 +430,8 @@ func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportS
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
resp.Diagnostics.AddError( core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing instance",
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID), fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
) )
return return
@ -589,12 +621,11 @@ func toUpdatePayload(model *Model, parameters *parametersModel) (*mariadb.Update
}, nil }, nil
} }
func (r *instanceResource) loadPlanId(ctx context.Context, diags *diag.Diagnostics, model *Model) { func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
res, err := r.client.GetOfferings(ctx, projectId).Execute() res, err := r.client.GetOfferings(ctx, projectId).Execute()
if err != nil { if err != nil {
diags.AddError("Failed to list MariaDB offerings", err.Error()) return fmt.Errorf("getting MariaDB offerings: %w", err)
return
} }
version := model.Version.ValueString() version := model.Version.ValueString()
@ -615,26 +646,24 @@ func (r *instanceResource) loadPlanId(ctx context.Context, diags *diag.Diagnosti
} }
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil { if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
model.PlanId = types.StringPointerValue(plan.Id) model.PlanId = types.StringPointerValue(plan.Id)
return return nil
} }
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name) availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
} }
} }
if !isValidVersion { if !isValidVersion {
diags.AddError("Invalid version", fmt.Sprintf("Couldn't find version '%s', available versions are:%s", version, availableVersions)) return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
return
} }
diags.AddError("Invalid plan_name", fmt.Sprintf("Couldn't find plan_name '%s' for version %s, available names are:%s", planName, version, availablePlanNames)) return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
} }
func loadPlanNameAndVersion(ctx context.Context, client *mariadb.APIClient, diags *diag.Diagnostics, model *Model) { func loadPlanNameAndVersion(ctx context.Context, client *mariadb.APIClient, model *Model) error {
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
planId := model.PlanId.ValueString() planId := model.PlanId.ValueString()
res, err := client.GetOfferings(ctx, projectId).Execute() res, err := client.GetOfferings(ctx, projectId).Execute()
if err != nil { if err != nil {
diags.AddError("Failed to list MariaDB offerings", err.Error()) return fmt.Errorf("getting MariaDB offerings: %w", err)
return
} }
for _, offer := range *res.Offerings { for _, offer := range *res.Offerings {
@ -642,10 +671,10 @@ func loadPlanNameAndVersion(ctx context.Context, client *mariadb.APIClient, diag
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil { if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
model.PlanName = types.StringPointerValue(plan.Name) model.PlanName = types.StringPointerValue(plan.Name)
model.Version = types.StringPointerValue(offer.Version) model.Version = types.StringPointerValue(offer.Version)
return return nil
} }
} }
} }
diags.AddWarning("Failed to get plan_name and version", fmt.Sprintf("Couldn't find plan_name and version for plan_id = %s", planId)) return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
} }

View file

@ -45,7 +45,7 @@ func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.Co
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -64,12 +64,12 @@ func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.Co
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "Postgresql zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "OpenSearch credentials client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -160,19 +160,22 @@ func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadReq
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute() recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "Postgresql credentials read") if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "OpenSearch credentials read")
} }

View file

@ -25,9 +25,9 @@ import (
// Ensure the implementation satisfies the expected interfaces. // Ensure the implementation satisfies the expected interfaces.
var ( var (
_ resource.Resource = &openSearchCredentialsResource{} _ resource.Resource = &credentialsResource{}
_ resource.ResourceWithConfigure = &openSearchCredentialsResource{} _ resource.ResourceWithConfigure = &credentialsResource{}
_ resource.ResourceWithImportState = &openSearchCredentialsResource{} _ resource.ResourceWithImportState = &credentialsResource{}
) )
type Model struct { type Model struct {
@ -47,21 +47,21 @@ type Model struct {
// NewCredentialsResource is a helper function to simplify the provider implementation. // NewCredentialsResource is a helper function to simplify the provider implementation.
func NewCredentialsResource() resource.Resource { func NewCredentialsResource() resource.Resource {
return &openSearchCredentialsResource{} return &credentialsResource{}
} }
// credentialsResource is the resource implementation. // credentialsResource is the resource implementation.
type openSearchCredentialsResource struct { type credentialsResource struct {
client *opensearch.APIClient client *opensearch.APIClient
} }
// Metadata returns the resource type name. // Metadata returns the resource type name.
func (r *openSearchCredentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_opensearch_credentials" resp.TypeName = req.ProviderTypeName + "_opensearch_credentials"
} }
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *openSearchCredentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured. // Prevent panic if the provider has not been configured.
if req.ProviderData == nil { if req.ProviderData == nil {
return return
@ -69,7 +69,7 @@ func (r *openSearchCredentialsResource) Configure(ctx context.Context, req resou
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -88,16 +88,16 @@ func (r *openSearchCredentialsResource) Configure(ctx context.Context, req resou
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "OpenSearch zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "OpenSearch credentials client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
func (r *openSearchCredentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{ descriptions := map[string]string{
"main": "OpenSearch credentials resource schema.", "main": "OpenSearch credentials resource schema.",
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".", "id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
@ -182,7 +182,7 @@ func (r *openSearchCredentialsResource) Schema(_ context.Context, _ resource.Sch
} }
// Create creates the resource and sets the initial Terraform state. // Create creates the resource and sets the initial Terraform state.
func (r *openSearchCredentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.Plan.Get(ctx, &model) diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -214,23 +214,26 @@ func (r *openSearchCredentialsResource) Create(ctx context.Context, req resource
} }
got, ok := wr.(*opensearch.CredentialsResponse) got, ok := wr.(*opensearch.CredentialsResponse)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "OpenSearch credentials created") tflog.Info(ctx, "OpenSearch credentials created")
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *openSearchCredentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -246,31 +249,34 @@ func (r *openSearchCredentialsResource) Read(ctx context.Context, req resource.R
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute() recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(recordSetResp, &model) err = mapFields(recordSetResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "OpenSearch credentials read") tflog.Info(ctx, "OpenSearch credentials read")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
func (r *openSearchCredentialsResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Update shouldn't be called // Update shouldn't be called
resp.Diagnostics.AddError("Error updating credentials", "credentials can't be updated") core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
func (r *openSearchCredentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -288,7 +294,7 @@ func (r *openSearchCredentialsResource) Delete(ctx context.Context, req resource
// Delete existing record set // Delete existing record set
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute() err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
} }
_, err = opensearch.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx) _, err = opensearch.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil { if err != nil {
@ -300,11 +306,11 @@ func (r *openSearchCredentialsResource) Delete(ctx context.Context, req resource
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id // The expected format of the resource import identifier is: project_id,instance_id,credentials_id
func (r *openSearchCredentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, core.LogAndAddError(ctx, &resp.Diagnostics,
"Unexpected Import Identifier", "Error importing credentials",
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID), fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
) )
return return

View file

@ -44,7 +44,7 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -63,12 +63,12 @@ func (r *instanceDataSource) Configure(ctx context.Context, req datasource.Confi
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "OpenSearch zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "OpenSearch zone client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -152,37 +152,41 @@ func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaReques
// Read refreshes the Terraform state with the latest data. // 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 func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state Model var model Model
diags := req.Config.Get(ctx, &state) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := model.ProjectId.ValueString()
projectId := state.ProjectId.ValueString() instanceId := model.InstanceId.ValueString()
instanceId := state.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute() instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to read instance", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
err = mapFields(instanceResp, &state) err = mapFields(instanceResp, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Compute and store values not present in the API response // Compute and store values not present in the API response
loadPlanNameAndVersion(ctx, r.client, &resp.Diagnostics, &state) err = loadPlanNameAndVersion(ctx, r.client, &model)
if resp.Diagnostics.HasError() { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
return return
} }
// Set refreshed state // Set refreshed state
diags = resp.State.Set(ctx, &state) diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "OpenSearch instance read") tflog.Info(ctx, "OpenSearch instance read")
} }

View file

@ -8,7 +8,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr" "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/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tflog"
@ -82,7 +81,7 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
providerData, ok := req.ProviderData.(core.ProviderData) providerData, ok := req.ProviderData.(core.ProviderData)
if !ok { if !ok {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", req.ProviderData)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return return
} }
@ -101,12 +100,12 @@ func (r *instanceResource) Configure(ctx context.Context, req resource.Configure
} }
if err != nil { if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
return return
} }
tflog.Info(ctx, "opensearch zone client configured")
r.client = apiClient r.client = apiClient
tflog.Info(ctx, "OpenSearch instance client configured")
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
@ -128,6 +127,9 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: descriptions["id"], Description: descriptions["id"],
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"instance_id": schema.StringAttribute{ "instance_id": schema.StringAttribute{
Description: descriptions["instance_id"], Description: descriptions["instance_id"],
@ -187,18 +189,33 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
}, },
"cf_guid": schema.StringAttribute{ "cf_guid": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"cf_space_guid": schema.StringAttribute{ "cf_space_guid": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"dashboard_url": schema.StringAttribute{ "dashboard_url": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"image_url": schema.StringAttribute{ "image_url": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
"cf_organization_guid": schema.StringAttribute{ "cf_organization_guid": schema.StringAttribute{
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
}, },
}, },
} }
@ -215,11 +232,6 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if resp.Diagnostics.HasError() {
return
}
var parameters = &parametersModel{} var parameters = &parametersModel{}
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) { if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{}) diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
@ -229,6 +241,12 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
} }
} }
err := r.loadPlanId(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
return
}
// Generate API request body from model // Generate API request body from model
payload, err := toCreatePayload(&model, parameters) payload, err := toCreatePayload(&model, parameters)
if err != nil { if err != nil {
@ -250,58 +268,66 @@ func (r *instanceResource) Create(ctx context.Context, req resource.CreateReques
} }
got, ok := wr.(*opensearch.Instance) got, ok := wr.(*opensearch.Instance)
if !ok { if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", got)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
return return
} }
// Map response body to schema and populate Computed attribute values // Map response body to schema
err = mapFields(got, &model) err = mapFields(got, &model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
return return
} }
// Set state to fully populated data // Set state to fully populated data
diags = resp.State.Set(ctx, model) diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "opensearch 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() { if resp.Diagnostics.HasError() {
return return
} }
projectId := state.ProjectId.ValueString() tflog.Info(ctx, "OpenSearch instance created")
instanceId := state.InstanceId.ValueString() }
// Read refreshes the Terraform state with the latest data.
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
instanceId := model.InstanceId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "instance_id", instanceId) ctx = tflog.SetField(ctx, "instance_id", instanceId)
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute() instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instances", err.Error()) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema and populate Computed attribute values