feat(iaas): add experimental support for routing tables and routes (#896)

* Merged PR 788126: feat(iaas): Onboard routing tables

feat(iaas): Onboard routing tables

Signed-off-by: Alexander Dahmen <alexander.dahmen@inovex.de>

* Merged PR 793350: fix(routingtable): region attribute is missing in scheme

fix(routingtable): region attribute is missing in scheme

Signed-off-by: Alexander Dahmen <alexander.dahmen@inovex.de>

* Merged PR 797968: feat(iaas): onboarding of routing table routes

relates to STACKITTPR-241

* use iaasalpha sdk from github

* resolve todos

* remove routes from routing table model

* restructure packages

* acc tests routing tables

* add acc tests for routes

* chore(iaas): mark routing table resources as experimental

* chore(deps): use iaasalpha sdk v0.1.19-alpha

* Review feedback

Signed-off-by: Alexander Dahmen <alexander.dahmen@inovex.de>

---------

Signed-off-by: Alexander Dahmen <alexander.dahmen@inovex.de>
Co-authored-by: Alexander Dahmen (EXT) <Alexander.Dahmen_ext@external.mail.schwarz>
Co-authored-by: Alexander Dahmen <alexander.dahmen@inovex.de>
This commit is contained in:
Ruben Hönle 2025-07-02 10:30:50 +02:00 committed by GitHub
parent d2c51afbe5
commit 9ff9b8f610
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
65 changed files with 5160 additions and 53 deletions

View file

@ -0,0 +1,156 @@
package table
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/routingtable/shared"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
iaasalphaUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &routingTableDataSource{}
)
// NewRoutingTableDataSource is a helper function to simplify the provider implementation.
func NewRoutingTableDataSource() datasource.DataSource {
return &routingTableDataSource{}
}
// routingTableDataSource is the data source implementation.
type routingTableDataSource struct {
client *iaasalpha.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
func (d *routingTableDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_routing_table"
}
func (d *routingTableDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
features.CheckExperimentEnabled(ctx, &d.providerData, features.RoutingTablesExperiment, "stackit_routing_table", core.Datasource, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
apiClient := iaasalphaUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
d.client = apiClient
tflog.Info(ctx, "IaaS client configured")
}
// Schema defines the schema for the data source.
func (d *routingTableDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
description := "Routing table datasource schema. Must have a `region` specified in the provider configuration."
resp.Schema = schema.Schema{
Description: description,
MarkdownDescription: features.AddExperimentDescription(description, features.RoutingTablesExperiment, core.Datasource),
Attributes: shared.GetDatasourceGetAttributes(),
}
}
// Read refreshes the Terraform state with the latest data.
func (d *routingTableDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model shared.RoutingTableDataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
organizationId := model.OrganizationId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
routingTableId := model.RoutingTableId.ValueString()
networkAreaId := model.NetworkAreaId.ValueString()
ctx = tflog.SetField(ctx, "organization_id", organizationId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
routingTableResp, err := d.client.GetRoutingTableOfArea(ctx, organizationId, networkAreaId, region, routingTableId).Execute()
if err != nil {
utils.LogError(
ctx,
&resp.Diagnostics,
err,
"Reading routing table",
fmt.Sprintf("Routing table with ID %q or network area with ID %q does not exist in organization %q.", routingTableId, networkAreaId, organizationId),
map[int]string{
http.StatusForbidden: fmt.Sprintf("Organization with ID %q not found or forbidden access", organizationId),
},
)
resp.State.RemoveResource(ctx)
return
}
err = mapDatasourceFields(ctx, routingTableResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading routing table", fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Routing table read")
}
func mapDatasourceFields(ctx context.Context, routingTable *iaasalpha.RoutingTable, model *shared.RoutingTableDataSourceModel, region string) error {
if routingTable == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var routingTableId string
if model.RoutingTableId.ValueString() != "" {
routingTableId = model.RoutingTableId.ValueString()
} else if routingTable.Id != nil {
routingTableId = *routingTable.Id
} else {
return fmt.Errorf("routing table id not present")
}
idParts := []string{
model.OrganizationId.ValueString(),
region,
model.NetworkAreaId.ValueString(),
routingTableId,
}
model.Id = types.StringValue(
strings.Join(idParts, core.Separator),
)
err := shared.MapRoutingTableReadModel(ctx, routingTable, &model.RoutingTableReadModel)
if err != nil {
return err
}
model.Region = types.StringValue(region)
return nil
}

View file

@ -0,0 +1,136 @@
package table
import (
"context"
"fmt"
"testing"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/routingtable/shared"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha"
)
const (
testRegion = "eu01"
)
var (
organizationId = uuid.New()
networkAreaId = uuid.New()
routingTableId = uuid.New()
)
func Test_mapDatasourceFields(t *testing.T) {
id := fmt.Sprintf("%s,%s,%s,%s", organizationId.String(), testRegion, networkAreaId.String(), routingTableId.String())
tests := []struct {
description string
state shared.RoutingTableDataSourceModel
input *iaasalpha.RoutingTable
expected shared.RoutingTableDataSourceModel
isValid bool
}{
{
"default_values",
shared.RoutingTableDataSourceModel{
OrganizationId: types.StringValue(organizationId.String()),
NetworkAreaId: types.StringValue(networkAreaId.String()),
},
&iaasalpha.RoutingTable{
Id: utils.Ptr(routingTableId.String()),
Name: utils.Ptr("default_values"),
},
shared.RoutingTableDataSourceModel{
Id: types.StringValue(id),
OrganizationId: types.StringValue(organizationId.String()),
NetworkAreaId: types.StringValue(networkAreaId.String()),
Region: types.StringValue(testRegion),
RoutingTableReadModel: shared.RoutingTableReadModel{
RoutingTableId: types.StringValue(routingTableId.String()),
Name: types.StringValue("default_values"),
Labels: types.MapNull(types.StringType),
},
},
true,
},
{
"values_ok",
shared.RoutingTableDataSourceModel{
OrganizationId: types.StringValue(organizationId.String()),
NetworkAreaId: types.StringValue(networkAreaId.String()),
RoutingTableReadModel: shared.RoutingTableReadModel{},
},
&iaasalpha.RoutingTable{
Id: utils.Ptr(routingTableId.String()),
Name: utils.Ptr("values_ok"),
Description: utils.Ptr("Description"),
Labels: &map[string]interface{}{
"key": "value",
},
},
shared.RoutingTableDataSourceModel{
Id: types.StringValue(id),
OrganizationId: types.StringValue(organizationId.String()),
NetworkAreaId: types.StringValue(networkAreaId.String()),
Region: types.StringValue(testRegion),
RoutingTableReadModel: shared.RoutingTableReadModel{
RoutingTableId: types.StringValue(routingTableId.String()),
Name: types.StringValue("values_ok"),
Description: types.StringValue("Description"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
},
},
true,
},
{
"response_fields_nil_fail",
shared.RoutingTableDataSourceModel{},
&iaasalpha.RoutingTable{
Id: nil,
},
shared.RoutingTableDataSourceModel{},
false,
},
{
"response_nil_fail",
shared.RoutingTableDataSourceModel{},
nil,
shared.RoutingTableDataSourceModel{},
false,
},
{
"no_resource_id",
shared.RoutingTableDataSourceModel{
OrganizationId: types.StringValue("oid"),
NetworkAreaId: types.StringValue("naid"),
},
&iaasalpha.RoutingTable{},
shared.RoutingTableDataSourceModel{},
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
err := mapDatasourceFields(context.Background(), tt.input, &tt.state, testRegion)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}

View file

@ -0,0 +1,479 @@
package table
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
iaasalphaUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &routingTableResource{}
_ resource.ResourceWithConfigure = &routingTableResource{}
_ resource.ResourceWithImportState = &routingTableResource{}
)
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
OrganizationId types.String `tfsdk:"organization_id"`
RoutingTableId types.String `tfsdk:"routing_table_id"`
Name types.String `tfsdk:"name"`
NetworkAreaId types.String `tfsdk:"network_area_id"`
Description types.String `tfsdk:"description"`
Labels types.Map `tfsdk:"labels"`
Region types.String `tfsdk:"region"`
SystemRoutes types.Bool `tfsdk:"system_routes"`
CreatedAt types.String `tfsdk:"created_at"`
UpdatedAt types.String `tfsdk:"updated_at"`
}
// NewRoutingTableResource is a helper function to simplify the provider implementation.
func NewRoutingTableResource() resource.Resource {
return &routingTableResource{}
}
// routingTableResource is the resource implementation.
type routingTableResource struct {
client *iaasalpha.APIClient
providerData core.ProviderData
}
// Metadata returns the resource type name.
func (r *routingTableResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_routing_table"
}
// Configure adds the provider configured client to the resource.
func (r *routingTableResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
features.CheckExperimentEnabled(ctx, &r.providerData, features.RoutingTablesExperiment, "stackit_routing_table", core.Resource, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
apiClient := iaasalphaUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "IaaS alpha client configured")
}
func (r *routingTableResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
description := "Routing table resource schema. Must have a `region` specified in the provider configuration."
resp.Schema = schema.Schema{
Description: description,
MarkdownDescription: features.AddExperimentDescription(description, features.RoutingTablesExperiment, core.Resource),
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`organization_id`,`region`,`network_area_id`,`routing_table_id`\".",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"organization_id": schema.StringAttribute{
Description: "STACKIT organization ID to which the routing table is associated.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"routing_table_id": schema.StringAttribute{
Description: "The routing tables ID.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"name": schema.StringAttribute{
Description: "The name of the routing table.",
Required: true,
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(63),
},
},
"network_area_id": schema.StringAttribute{
Description: "The network area ID to which the routing table is associated.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"description": schema.StringAttribute{
Description: "Description of the routing table.",
Optional: true,
Computed: true,
Validators: []validator.String{
stringvalidator.LengthAtMost(127),
},
},
"labels": schema.MapAttribute{
Description: "Labels are key-value string pairs which can be attached to a resource container",
ElementType: types.StringType,
Optional: true,
},
"region": schema.StringAttribute{
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
Description: "The resource region. If not defined, the provider region is used.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"system_routes": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.RequiresReplace(),
},
},
"created_at": schema.StringAttribute{
Description: "Date-time when the routing table was created",
Computed: true,
},
"updated_at": schema.StringAttribute{
Description: "Date-time when the routing table was updated",
Computed: true,
},
},
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *routingTableResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
organizationId := model.OrganizationId.ValueString()
networkAreaId := model.NetworkAreaId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "organization_id", organizationId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
// Generate API request body from model
payload, err := toCreatePayload(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating routing table", fmt.Sprintf("Creating API payload: %v", err))
return
}
routingTable, err := r.client.AddRoutingTableToArea(ctx, organizationId, networkAreaId, region).AddRoutingTableToAreaPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating routing table", fmt.Sprintf("Calling API: %v", err))
return
}
// Map response body to schema
err = mapFields(ctx, routingTable, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating routing table.", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Routing table created")
}
// Read refreshes the Terraform state with the latest data.
func (r *routingTableResource) 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
}
organizationId := model.OrganizationId.ValueString()
routingTableId := model.RoutingTableId.ValueString()
networkAreaId := model.NetworkAreaId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "organization_id", organizationId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
routingTableResp, err := r.client.GetRoutingTableOfArea(ctx, organizationId, networkAreaId, region, routingTableId).Execute()
if err != nil {
utils.LogError(
ctx,
&resp.Diagnostics,
err,
"Reading routing table",
fmt.Sprintf("routing table with ID %q does not exist in organization %q.", routingTableId, organizationId),
map[int]string{
http.StatusForbidden: fmt.Sprintf("Organization with ID %q not found or forbidden access", organizationId),
},
)
resp.State.RemoveResource(ctx)
return
}
// Map response body to schema
err = mapFields(ctx, routingTableResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading routing table", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Routing table read")
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *routingTableResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
organizationId := model.OrganizationId.ValueString()
routingTableId := model.RoutingTableId.ValueString()
networkAreaId := model.NetworkAreaId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "organization_id", organizationId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
// Retrieve values from state
var stateModel Model
diags = req.State.Get(ctx, &stateModel)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Generate API request body from model
payload, err := toUpdatePayload(ctx, &model, stateModel.Labels)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating routing table", fmt.Sprintf("Creating API payload: %v", err))
return
}
routingTable, err := r.client.UpdateRoutingTableOfArea(ctx, organizationId, networkAreaId, region, routingTableId).UpdateRoutingTableOfAreaPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating routing table", fmt.Sprintf("Calling API: %v", err))
return
}
// Map response body to schema
err = mapFields(ctx, routingTable, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating routing table", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Routing table updated")
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *routingTableResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from state
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
organizationId := model.OrganizationId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
routingTableId := model.RoutingTableId.ValueString()
networkAreaId := model.NetworkAreaId.ValueString()
ctx = tflog.SetField(ctx, "organization_id", organizationId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
// Delete existing routing table
err := r.client.DeleteRoutingTableFromArea(ctx, organizationId, networkAreaId, region, routingTableId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting routing table", fmt.Sprintf("Calling API: %v", err))
return
}
tflog.Info(ctx, "Routing table deleted")
}
// ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: organization_id,region,network_area_id,routing_table_id
func (r *routingTableResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing routing table",
fmt.Sprintf("Expected import identifier with format: [organization_id],[region],[network_area_id],[routing_table_id] Got: %q", req.ID),
)
return
}
organizationId := idParts[0]
region := idParts[1]
networkAreaId := idParts[2]
routingTableId := idParts[3]
ctx = tflog.SetField(ctx, "organization_id", organizationId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("organization_id"), organizationId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("network_area_id"), networkAreaId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("routing_table_id"), routingTableId)...)
tflog.Info(ctx, "Routing table state imported")
}
func mapFields(ctx context.Context, routingTable *iaasalpha.RoutingTable, model *Model, region string) error {
if routingTable == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var routingTableId string
if model.RoutingTableId.ValueString() != "" {
routingTableId = model.RoutingTableId.ValueString()
} else if routingTable.Id != nil {
routingTableId = *routingTable.Id
} else {
return fmt.Errorf("routing table id not present")
}
model.Id = utils.BuildInternalTerraformId(model.OrganizationId.ValueString(), region, model.NetworkAreaId.ValueString(), routingTableId)
labels, err := iaasUtils.MapLabels(ctx, routingTable.Labels, model.Labels)
if err != nil {
return err
}
// created at and updated at
createdAtTF, updatedAtTF := types.StringNull(), types.StringNull()
if routingTable.CreatedAt != nil {
createdAtValue := *routingTable.CreatedAt
createdAtTF = types.StringValue(createdAtValue.Format(time.RFC3339))
}
if routingTable.UpdatedAt != nil {
updatedAtValue := *routingTable.UpdatedAt
updatedAtTF = types.StringValue(updatedAtValue.Format(time.RFC3339))
}
model.RoutingTableId = types.StringValue(routingTableId)
model.Name = types.StringPointerValue(routingTable.Name)
model.Description = types.StringPointerValue(routingTable.Description)
model.Labels = labels
model.Region = types.StringValue(region)
model.SystemRoutes = types.BoolPointerValue(routingTable.SystemRoutes)
model.CreatedAt = createdAtTF
model.UpdatedAt = updatedAtTF
return nil
}
func toCreatePayload(ctx context.Context, model *Model) (*iaasalpha.AddRoutingTableToAreaPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
labels, err := conversion.ToStringInterfaceMap(ctx, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
return &iaasalpha.AddRoutingTableToAreaPayload{
Description: conversion.StringValueToPointer(model.Description),
Name: conversion.StringValueToPointer(model.Name),
Labels: &labels,
SystemRoutes: conversion.BoolValueToPointer(model.SystemRoutes),
}, nil
}
func toUpdatePayload(ctx context.Context, model *Model, currentLabels types.Map) (*iaasalpha.UpdateRoutingTableOfAreaPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
labels, err := conversion.ToJSONMapPartialUpdatePayload(ctx, currentLabels, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
return &iaasalpha.UpdateRoutingTableOfAreaPayload{
Description: conversion.StringValueToPointer(model.Description),
Name: conversion.StringValueToPointer(model.Name),
Labels: &labels,
}, nil
}

View file

@ -0,0 +1,212 @@
package table
import (
"context"
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha"
)
func TestMapFields(t *testing.T) {
const testRegion = "eu01"
id := fmt.Sprintf("%s,%s,%s,%s", "oid", testRegion, "aid", "rtid")
tests := []struct {
description string
state Model
input *iaasalpha.RoutingTable
expected Model
isValid bool
}{
{
"default_values",
Model{
OrganizationId: types.StringValue("oid"),
NetworkAreaId: types.StringValue("aid"),
},
&iaasalpha.RoutingTable{
Id: utils.Ptr("rtid"),
Name: utils.Ptr("default_values"),
},
Model{
Id: types.StringValue(id),
OrganizationId: types.StringValue("oid"),
RoutingTableId: types.StringValue("rtid"),
Name: types.StringValue("default_values"),
NetworkAreaId: types.StringValue("aid"),
Labels: types.MapNull(types.StringType),
Region: types.StringValue(testRegion),
},
true,
},
{
"values_ok",
Model{
OrganizationId: types.StringValue("oid"),
NetworkAreaId: types.StringValue("aid"),
},
&iaasalpha.RoutingTable{
Id: utils.Ptr("rtid"),
Name: utils.Ptr("values_ok"),
Description: utils.Ptr("Description"),
Labels: &map[string]interface{}{
"key": "value",
},
},
Model{
Id: types.StringValue(id),
OrganizationId: types.StringValue("oid"),
RoutingTableId: types.StringValue("rtid"),
Name: types.StringValue("values_ok"),
Description: types.StringValue("Description"),
NetworkAreaId: types.StringValue("aid"),
Region: types.StringValue(testRegion),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
},
true,
},
{
"response_fields_nil_fail",
Model{},
&iaasalpha.RoutingTable{
Id: nil,
},
Model{},
false,
},
{
"response_nil_fail",
Model{},
nil,
Model{},
false,
},
{
"no_resource_id",
Model{
OrganizationId: types.StringValue("oid"),
NetworkAreaId: types.StringValue("naid"),
},
&iaasalpha.RoutingTable{},
Model{},
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
err := mapFields(context.Background(), tt.input, &tt.state, testRegion)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}
func TestToCreatePayload(t *testing.T) {
tests := []struct {
description string
input *Model
expected *iaasalpha.AddRoutingTableToAreaPayload
isValid bool
}{
{
description: "default_ok",
input: &Model{
Description: types.StringValue("Description"),
Name: types.StringValue("default_ok"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
SystemRoutes: types.BoolValue(true),
},
expected: &iaasalpha.AddRoutingTableToAreaPayload{
Description: utils.Ptr("Description"),
Name: utils.Ptr("default_ok"),
Labels: &map[string]interface{}{
"key": "value",
},
SystemRoutes: utils.Ptr(true),
},
isValid: true,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
output, err := toCreatePayload(context.Background(), tt.input)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(output, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}
func TestToUpdatePayload(t *testing.T) {
tests := []struct {
description string
input *Model
expected *iaasalpha.UpdateRoutingTableOfAreaPayload
isValid bool
}{
{
"default_ok",
&Model{
Description: types.StringValue("Description"),
Name: types.StringValue("default_ok"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key1": types.StringValue("value1"),
"key2": types.StringValue("value2"),
}),
},
&iaasalpha.UpdateRoutingTableOfAreaPayload{
Description: utils.Ptr("Description"),
Name: utils.Ptr("default_ok"),
Labels: &map[string]interface{}{
"key1": "value1",
"key2": "value2",
},
},
true,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
output, err := toUpdatePayload(context.Background(), tt.input, types.MapNull(types.StringType))
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(output, tt.expected, cmp.AllowUnexported(iaasalpha.NullableString{}))
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}