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:
parent
d2c51afbe5
commit
9ff9b8f610
65 changed files with 5160 additions and 53 deletions
|
|
@ -0,0 +1,120 @@
|
|||
package route
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
shared "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 = &routingTableRouteDataSource{}
|
||||
)
|
||||
|
||||
// NewRoutingTableRouteDataSource is a helper function to simplify the provider implementation.
|
||||
func NewRoutingTableRouteDataSource() datasource.DataSource {
|
||||
return &routingTableRouteDataSource{}
|
||||
}
|
||||
|
||||
// routingTableRouteDataSource is the data source implementation.
|
||||
type routingTableRouteDataSource struct {
|
||||
client *iaasalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *routingTableRouteDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_routing_table_route"
|
||||
}
|
||||
|
||||
func (d *routingTableRouteDataSource) 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_route", 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 *routingTableRouteDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
description := "Routing table route 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.GetRouteDataSourceAttributes(),
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *routingTableRouteDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model shared.RouteModel
|
||||
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()
|
||||
routeId := model.RouteId.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)
|
||||
ctx = tflog.SetField(ctx, "route_id", routeId)
|
||||
|
||||
routeResp, err := d.client.GetRouteOfRoutingTable(ctx, organizationId, networkAreaId, region, routingTableId, routeId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, err.Error(), err.Error())
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading routing table route",
|
||||
fmt.Sprintf("Routing table route with ID %q, routing table with ID %q or network area with ID %q does not exist in organization %q.", routeId, 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 = shared.MapRouteModel(ctx, routeResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading routing table route", 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 route read")
|
||||
}
|
||||
|
|
@ -0,0 +1,516 @@
|
|||
package route
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/routingtable/shared"
|
||||
|
||||
"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-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
sdkUtils "github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"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 = &routeResource{}
|
||||
_ resource.ResourceWithConfigure = &routeResource{}
|
||||
_ resource.ResourceWithImportState = &routeResource{}
|
||||
)
|
||||
|
||||
// NewRoutingTableRouteResource is a helper function to simplify the provider implementation.
|
||||
func NewRoutingTableRouteResource() resource.Resource {
|
||||
return &routeResource{}
|
||||
}
|
||||
|
||||
// routeResource is the resource implementation.
|
||||
type routeResource struct {
|
||||
client *iaasalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *routeResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_routing_table_route"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *routeResource) 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_route", 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")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *routeResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
description := "Routing table route 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`,`route_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.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Description: "The resource region. If not defined, the provider region is used.",
|
||||
Optional: true,
|
||||
// must be computed to allow for storing the override value from the provider
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"route_id": schema.StringAttribute{
|
||||
Description: "The ID of the route.",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"destination": schema.SingleNestedAttribute{
|
||||
Description: "Destination of the route.",
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"type": schema.StringAttribute{
|
||||
Description: fmt.Sprintf("CIDRV type. %s %s", utils.FormatPossibleValues("cidrv4", "cidrv6"), "Only `cidrv4` is supported during experimental stage."),
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"value": schema.StringAttribute{
|
||||
Description: "An CIDR string.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"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(),
|
||||
},
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: "Labels are key-value string pairs which can be attached to a resource container",
|
||||
ElementType: types.StringType,
|
||||
Optional: true,
|
||||
},
|
||||
"next_hop": schema.SingleNestedAttribute{
|
||||
Description: "Next hop destination.",
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"type": schema.StringAttribute{
|
||||
Description: fmt.Sprintf("%s %s.", utils.FormatPossibleValues("blackhole", "internet", "ipv4", "ipv6"), "Only `cidrv4` is supported during experimental stage."),
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"value": schema.StringAttribute{
|
||||
Description: "Either IPv4 or IPv6 (not set for blackhole and internet). Only IPv4 supported during experimental stage.",
|
||||
Optional: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"created_at": schema.StringAttribute{
|
||||
Description: "Date-time when the route was created.",
|
||||
Computed: true,
|
||||
},
|
||||
"updated_at": schema.StringAttribute{
|
||||
Description: "Date-time when the route was updated.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *routeResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model shared.RouteModel
|
||||
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, "routing_table_id", routingTableId)
|
||||
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
// Create new routing table route
|
||||
payload, err := toCreatePayload(ctx, &model.RouteReadModel)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating routing table route", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
routeResp, err := r.client.AddRoutesToRoutingTable(ctx, organizationId, networkAreaId, region, routingTableId).AddRoutesToRoutingTablePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating routing table route", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFieldsFromList(ctx, routeResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating routing table route", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
ctx = tflog.SetField(ctx, "route_id", model.RouteId.ValueString())
|
||||
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Routing table route created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *routeResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model shared.RouteModel
|
||||
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()
|
||||
routeId := model.RouteId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
|
||||
ctx = tflog.SetField(ctx, "organization_id", organizationId)
|
||||
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
|
||||
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "route_id", routeId)
|
||||
|
||||
routeResp, err := r.client.GetRouteOfRoutingTable(ctx, organizationId, networkAreaId, region, routingTableId, routeId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading routing table route", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = shared.MapRouteModel(ctx, routeResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading routing table route", 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 route read.")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *routeResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model shared.RouteModel
|
||||
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()
|
||||
routeId := model.RouteId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
|
||||
ctx = tflog.SetField(ctx, "organization_id", organizationId)
|
||||
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
|
||||
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "route_id", routeId)
|
||||
|
||||
// Retrieve values from state
|
||||
var stateModel shared.RouteModel
|
||||
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 route", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
route, err := r.client.UpdateRouteOfRoutingTable(ctx, organizationId, networkAreaId, region, routingTableId, routeId).UpdateRouteOfRoutingTablePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating routing table route", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = shared.MapRouteModel(ctx, route, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating routing table route", 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 route updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *routeResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model shared.RouteModel
|
||||
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()
|
||||
routeId := model.RouteId.ValueString()
|
||||
region := r.providerData.GetRegionWithOverride(model.Region)
|
||||
|
||||
ctx = tflog.SetField(ctx, "organization_id", organizationId)
|
||||
ctx = tflog.SetField(ctx, "routing_table_id", routingTableId)
|
||||
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
|
||||
ctx = tflog.SetField(ctx, "route_id", routeId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
|
||||
// Delete existing routing table route
|
||||
err := r.client.DeleteRouteFromRoutingTable(ctx, organizationId, networkAreaId, region, routingTableId, routeId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error routing table route", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Routing table route deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the routing table route resource import identifier is: organization_id,region,network_area_id,routing_table_id,route_id
|
||||
func (r *routeResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 5 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" || idParts[4] == "" {
|
||||
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],[route_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
organizationId := idParts[0]
|
||||
region := idParts[1]
|
||||
networkAreaId := idParts[2]
|
||||
routingTableId := idParts[3]
|
||||
routeId := idParts[4]
|
||||
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)
|
||||
ctx = tflog.SetField(ctx, "route_id", routeId)
|
||||
|
||||
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)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("route_id"), routeId)...)
|
||||
tflog.Info(ctx, "Routing table route state imported")
|
||||
}
|
||||
|
||||
func mapFieldsFromList(ctx context.Context, routeResp *iaasalpha.RouteListResponse, model *shared.RouteModel, region string) error {
|
||||
if routeResp == nil || routeResp.Items == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
} else if len(*routeResp.Items) < 1 {
|
||||
return fmt.Errorf("no routes found in response")
|
||||
} else if len(*routeResp.Items) > 1 {
|
||||
return fmt.Errorf("more than 1 route found in response")
|
||||
}
|
||||
|
||||
route := (*routeResp.Items)[0]
|
||||
return shared.MapRouteModel(ctx, &route, model, region)
|
||||
}
|
||||
|
||||
func toCreatePayload(ctx context.Context, model *shared.RouteReadModel) (*iaasalpha.AddRoutesToRoutingTablePayload, 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)
|
||||
}
|
||||
|
||||
nextHopPayload, err := toNextHopPayload(ctx, model)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
destinationPayload, err := toDestinationPayload(ctx, model)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &iaasalpha.AddRoutesToRoutingTablePayload{
|
||||
Items: &[]iaasalpha.Route{
|
||||
{
|
||||
Labels: &labels,
|
||||
Nexthop: nextHopPayload,
|
||||
Destination: destinationPayload,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(ctx context.Context, model *shared.RouteModel, currentLabels types.Map) (*iaasalpha.UpdateRouteOfRoutingTablePayload, 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.UpdateRouteOfRoutingTablePayload{
|
||||
Labels: &labels,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toNextHopPayload(ctx context.Context, model *shared.RouteReadModel) (*iaasalpha.RouteNexthop, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if utils.IsUndefined(model.NextHop) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
nexthopModel := shared.RouteNextHop{}
|
||||
diags := model.NextHop.As(ctx, &nexthopModel, basetypes.ObjectAsOptions{})
|
||||
if diags.HasError() {
|
||||
return nil, core.DiagsToError(diags)
|
||||
}
|
||||
|
||||
switch nexthopModel.Type.ValueString() {
|
||||
case "blackhole":
|
||||
return sdkUtils.Ptr(iaasalpha.NexthopBlackholeAsRouteNexthop(iaasalpha.NewNexthopBlackhole("blackhole"))), nil
|
||||
case "internet":
|
||||
return sdkUtils.Ptr(iaasalpha.NexthopInternetAsRouteNexthop(iaasalpha.NewNexthopInternet("internet"))), nil
|
||||
case "ipv4":
|
||||
return sdkUtils.Ptr(iaasalpha.NexthopIPv4AsRouteNexthop(iaasalpha.NewNexthopIPv4("ipv4", nexthopModel.Value.ValueString()))), nil
|
||||
case "ipv6":
|
||||
return sdkUtils.Ptr(iaasalpha.NexthopIPv6AsRouteNexthop(iaasalpha.NewNexthopIPv6("ipv6", nexthopModel.Value.ValueString()))), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unknown nexthop type: %s", nexthopModel.Type.ValueString())
|
||||
}
|
||||
|
||||
func toDestinationPayload(ctx context.Context, model *shared.RouteReadModel) (*iaasalpha.RouteDestination, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if utils.IsUndefined(model.Destination) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
destinationModel := shared.RouteDestination{}
|
||||
diags := model.Destination.As(ctx, &destinationModel, basetypes.ObjectAsOptions{})
|
||||
if diags.HasError() {
|
||||
return nil, core.DiagsToError(diags)
|
||||
}
|
||||
|
||||
switch destinationModel.Type.ValueString() {
|
||||
case "cidrv4":
|
||||
return sdkUtils.Ptr(iaasalpha.DestinationCIDRv4AsRouteDestination(iaasalpha.NewDestinationCIDRv4("cidrv4", destinationModel.Value.ValueString()))), nil
|
||||
case "cidrv6":
|
||||
return sdkUtils.Ptr(iaasalpha.DestinationCIDRv6AsRouteDestination(iaasalpha.NewDestinationCIDRv6("cidrv6", destinationModel.Value.ValueString()))), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unknown destination type: %s", destinationModel.Type.ValueString())
|
||||
}
|
||||
|
|
@ -0,0 +1,452 @@
|
|||
package route
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"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 = "eu02"
|
||||
)
|
||||
|
||||
var (
|
||||
organizationId = uuid.New()
|
||||
networkAreaId = uuid.New()
|
||||
routingTableId = uuid.New()
|
||||
routeId = uuid.New()
|
||||
)
|
||||
|
||||
func Test_mapFieldsFromList(t *testing.T) {
|
||||
type args struct {
|
||||
routeResp *iaasalpha.RouteListResponse
|
||||
model *shared.RouteModel
|
||||
region string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
wantErr bool
|
||||
expectedModel *shared.RouteModel
|
||||
}{
|
||||
{
|
||||
name: "response is nil",
|
||||
args: args{
|
||||
model: &shared.RouteModel{},
|
||||
routeResp: nil,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "response items is nil",
|
||||
args: args{
|
||||
model: &shared.RouteModel{},
|
||||
routeResp: &iaasalpha.RouteListResponse{
|
||||
Items: nil,
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "model is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
routeResp: &iaasalpha.RouteListResponse{
|
||||
Items: nil,
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "response items is empty",
|
||||
args: args{
|
||||
model: &shared.RouteModel{},
|
||||
routeResp: &iaasalpha.RouteListResponse{
|
||||
Items: &[]iaasalpha.Route{},
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "response items contains more than one route",
|
||||
args: args{
|
||||
model: &shared.RouteModel{},
|
||||
routeResp: &iaasalpha.RouteListResponse{
|
||||
Items: &[]iaasalpha.Route{
|
||||
{
|
||||
Id: utils.Ptr(uuid.NewString()),
|
||||
},
|
||||
{
|
||||
Id: utils.Ptr(uuid.NewString()),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "success",
|
||||
args: args{
|
||||
model: &shared.RouteModel{
|
||||
RouteReadModel: shared.RouteReadModel{
|
||||
RouteId: types.StringNull(),
|
||||
},
|
||||
RoutingTableId: types.StringValue(routingTableId.String()),
|
||||
OrganizationId: types.StringValue(organizationId.String()),
|
||||
NetworkAreaId: types.StringValue(networkAreaId.String()),
|
||||
},
|
||||
routeResp: &iaasalpha.RouteListResponse{
|
||||
Items: &[]iaasalpha.Route{
|
||||
{
|
||||
Id: utils.Ptr(routeId.String()),
|
||||
Destination: utils.Ptr(iaasalpha.DestinationCIDRv4AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv4("cidrv4", "58.251.236.138/32"),
|
||||
)),
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopIPv4AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv4("ipv4", "10.20.42.2"),
|
||||
)),
|
||||
Labels: &map[string]interface{}{
|
||||
"foo": "bar",
|
||||
},
|
||||
CreatedAt: nil,
|
||||
UpdatedAt: nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
region: testRegion,
|
||||
},
|
||||
wantErr: false,
|
||||
expectedModel: &shared.RouteModel{
|
||||
RouteReadModel: shared.RouteReadModel{
|
||||
RouteId: types.StringValue(routeId.String()),
|
||||
NextHop: types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv4"),
|
||||
"value": types.StringValue("10.20.42.2"),
|
||||
}),
|
||||
Destination: types.ObjectValueMust(shared.RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv4"),
|
||||
"value": types.StringValue("58.251.236.138/32"),
|
||||
}),
|
||||
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"foo": types.StringValue("bar"),
|
||||
}),
|
||||
CreatedAt: types.StringNull(),
|
||||
UpdatedAt: types.StringNull(),
|
||||
},
|
||||
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s,%s", organizationId.String(), testRegion, networkAreaId.String(), routingTableId.String(), routeId.String())),
|
||||
RoutingTableId: types.StringValue(routingTableId.String()),
|
||||
OrganizationId: types.StringValue(organizationId.String()),
|
||||
NetworkAreaId: types.StringValue(networkAreaId.String()),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if err := mapFieldsFromList(ctx, tt.args.routeResp, tt.args.model, tt.args.region); (err != nil) != tt.wantErr {
|
||||
t.Errorf("mapFieldsFromList() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
|
||||
diff := cmp.Diff(tt.args.model, tt.expectedModel)
|
||||
if diff != "" && !tt.wantErr {
|
||||
t.Fatalf("mapFieldsFromList(): %s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_toUpdatePayload(t *testing.T) {
|
||||
type args struct {
|
||||
model *shared.RouteModel
|
||||
currentLabels types.Map
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *iaasalpha.UpdateRouteOfRoutingTablePayload
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "model is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "max",
|
||||
args: args{
|
||||
model: &shared.RouteModel{
|
||||
RouteReadModel: shared.RouteReadModel{
|
||||
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"foo1": types.StringValue("bar1"),
|
||||
"foo2": types.StringValue("bar2"),
|
||||
}),
|
||||
},
|
||||
},
|
||||
currentLabels: types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"foo1": types.StringValue("foobar"),
|
||||
"foo3": types.StringValue("bar3"),
|
||||
}),
|
||||
},
|
||||
want: &iaasalpha.UpdateRouteOfRoutingTablePayload{
|
||||
Labels: &map[string]interface{}{
|
||||
"foo1": "bar1",
|
||||
"foo2": "bar2",
|
||||
"foo3": nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
got, err := toUpdatePayload(ctx, tt.args.model, tt.args.currentLabels)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("toUpdatePayload() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
diff := cmp.Diff(got, tt.want)
|
||||
if diff != "" {
|
||||
t.Fatalf("toUpdatePayload(): %s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_toNextHopPayload(t *testing.T) {
|
||||
type args struct {
|
||||
model *shared.RouteReadModel
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *iaasalpha.RouteNexthop
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "model is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "ipv4",
|
||||
args: args{
|
||||
model: &shared.RouteReadModel{
|
||||
NextHop: types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv4"),
|
||||
"value": types.StringValue("10.20.42.2"),
|
||||
}),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: utils.Ptr(iaasalpha.NexthopIPv4AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv4("ipv4", "10.20.42.2"),
|
||||
)),
|
||||
},
|
||||
{
|
||||
name: "ipv6",
|
||||
args: args{
|
||||
model: &shared.RouteReadModel{
|
||||
NextHop: types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv6"),
|
||||
"value": types.StringValue("172b:f881:46fe:d89a:9332:90f7:3485:236d"),
|
||||
}),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: utils.Ptr(iaasalpha.NexthopIPv6AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv6("ipv6", "172b:f881:46fe:d89a:9332:90f7:3485:236d"),
|
||||
)),
|
||||
},
|
||||
{
|
||||
name: "internet",
|
||||
args: args{
|
||||
model: &shared.RouteReadModel{
|
||||
NextHop: types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("internet"),
|
||||
"value": types.StringNull(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: utils.Ptr(iaasalpha.NexthopInternetAsRouteNexthop(
|
||||
iaasalpha.NewNexthopInternet("internet"),
|
||||
)),
|
||||
},
|
||||
{
|
||||
name: "blackhole",
|
||||
args: args{
|
||||
model: &shared.RouteReadModel{
|
||||
NextHop: types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("blackhole"),
|
||||
"value": types.StringNull(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: utils.Ptr(iaasalpha.NexthopBlackholeAsRouteNexthop(
|
||||
iaasalpha.NewNexthopBlackhole("blackhole"),
|
||||
)),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
got, err := toNextHopPayload(ctx, tt.args.model)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("toNextHopPayload() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("toNextHopPayload() got = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_toDestinationPayload(t *testing.T) {
|
||||
type args struct {
|
||||
model *shared.RouteReadModel
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *iaasalpha.RouteDestination
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "model is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "cidrv4",
|
||||
args: args{
|
||||
model: &shared.RouteReadModel{
|
||||
Destination: types.ObjectValueMust(shared.RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv4"),
|
||||
"value": types.StringValue("58.251.236.138/32"),
|
||||
}),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: utils.Ptr(iaasalpha.DestinationCIDRv4AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv4("cidrv4", "58.251.236.138/32"),
|
||||
)),
|
||||
},
|
||||
{
|
||||
name: "cidrv6",
|
||||
args: args{
|
||||
model: &shared.RouteReadModel{
|
||||
Destination: types.ObjectValueMust(shared.RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv6"),
|
||||
"value": types.StringValue("2001:0db8:3c4d:1a2b::/64"),
|
||||
}),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
want: utils.Ptr(iaasalpha.DestinationCIDRv6AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv6("cidrv6", "2001:0db8:3c4d:1a2b::/64"),
|
||||
)),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
got, err := toDestinationPayload(ctx, tt.args.model)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("toDestinationPayload() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("toDestinationPayload() got = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_toCreatePayload(t *testing.T) {
|
||||
type args struct {
|
||||
model *shared.RouteReadModel
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *iaasalpha.AddRoutesToRoutingTablePayload
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "model is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "max",
|
||||
args: args{
|
||||
model: &shared.RouteReadModel{
|
||||
NextHop: types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv4"),
|
||||
"value": types.StringValue("10.20.42.2"),
|
||||
}),
|
||||
Destination: types.ObjectValueMust(shared.RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv4"),
|
||||
"value": types.StringValue("58.251.236.138/32"),
|
||||
}),
|
||||
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"foo1": types.StringValue("bar1"),
|
||||
"foo2": types.StringValue("bar2"),
|
||||
}),
|
||||
},
|
||||
},
|
||||
want: &iaasalpha.AddRoutesToRoutingTablePayload{
|
||||
Items: &[]iaasalpha.Route{
|
||||
{
|
||||
Labels: &map[string]interface{}{
|
||||
"foo1": "bar1",
|
||||
"foo2": "bar2",
|
||||
},
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopIPv4AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv4("ipv4", "10.20.42.2"),
|
||||
)),
|
||||
Destination: utils.Ptr(iaasalpha.DestinationCIDRv4AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv4("cidrv4", "58.251.236.138/32"),
|
||||
)),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
got, err := toCreatePayload(ctx, tt.args.model)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("toCreatePayload() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
diff := cmp.Diff(got, tt.want)
|
||||
if diff != "" {
|
||||
t.Fatalf("toCreatePayload(): %s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,183 @@
|
|||
package routes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"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"
|
||||
shared "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/routingtable/shared"
|
||||
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 = &routingTableRoutesDataSource{}
|
||||
)
|
||||
|
||||
type RoutingTableRoutesDataSourceModel struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
OrganizationId types.String `tfsdk:"organization_id"`
|
||||
NetworkAreaId types.String `tfsdk:"network_area_id"`
|
||||
RoutingTableId types.String `tfsdk:"routing_table_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Routes types.List `tfsdk:"routes"`
|
||||
}
|
||||
|
||||
// NewRoutingTableRoutesDataSource is a helper function to simplify the provider implementation.
|
||||
func NewRoutingTableRoutesDataSource() datasource.DataSource {
|
||||
return &routingTableRoutesDataSource{}
|
||||
}
|
||||
|
||||
// routingTableDataSource is the data source implementation.
|
||||
type routingTableRoutesDataSource struct {
|
||||
client *iaasalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *routingTableRoutesDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_routing_table_routes"
|
||||
}
|
||||
|
||||
func (d *routingTableRoutesDataSource) 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_routes", 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 *routingTableRoutesDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
description := "Routing table routes 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.GetRoutesDataSourceAttributes(),
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *routingTableRoutesDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model RoutingTableRoutesDataSourceModel
|
||||
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)
|
||||
networkAreaId := model.NetworkAreaId.ValueString()
|
||||
routingTableId := model.RoutingTableId.ValueString()
|
||||
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)
|
||||
|
||||
routesResp, err := d.client.ListRoutesOfRoutingTable(ctx, organizationId, networkAreaId, region, routingTableId).Execute()
|
||||
if err != nil {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading routes of routing table",
|
||||
fmt.Sprintf("Routing table with ID %q in 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 = mapDataSourceRoutingTableRoutes(ctx, routesResp, &model, region)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading routing table routes", 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 routes read")
|
||||
}
|
||||
|
||||
func mapDataSourceRoutingTableRoutes(ctx context.Context, routes *iaasalpha.RouteListResponse, model *RoutingTableRoutesDataSourceModel, region string) error {
|
||||
if routes == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
if routes.Items == nil {
|
||||
return fmt.Errorf("items input is nil")
|
||||
}
|
||||
|
||||
organizationId := model.OrganizationId.ValueString()
|
||||
networkAreaId := model.NetworkAreaId.ValueString()
|
||||
routingTableId := model.RoutingTableId.ValueString()
|
||||
|
||||
idParts := []string{organizationId, region, networkAreaId, routingTableId}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
|
||||
itemsList := []attr.Value{}
|
||||
for i, route := range *routes.Items {
|
||||
var routeModel shared.RouteReadModel
|
||||
err := shared.MapRouteReadModel(ctx, &route, &routeModel)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping route: %w", err)
|
||||
}
|
||||
|
||||
routeMap := map[string]attr.Value{
|
||||
"route_id": routeModel.RouteId,
|
||||
"destination": routeModel.Destination,
|
||||
"next_hop": routeModel.NextHop,
|
||||
"labels": routeModel.Labels,
|
||||
"created_at": routeModel.CreatedAt,
|
||||
"updated_at": routeModel.UpdatedAt,
|
||||
}
|
||||
|
||||
routeTF, diags := types.ObjectValue(shared.RouteReadModelTypes(), routeMap)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("mapping index %d: %w", i, core.DiagsToError(diags))
|
||||
}
|
||||
itemsList = append(itemsList, routeTF)
|
||||
}
|
||||
|
||||
routesListTF, diags := types.ListValue(types.ObjectType{AttrTypes: shared.RouteReadModelTypes()}, itemsList)
|
||||
if diags.HasError() {
|
||||
return core.DiagsToError(diags)
|
||||
}
|
||||
|
||||
model.Region = types.StringValue(region)
|
||||
model.Routes = routesListTF
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,199 @@
|
|||
package routes
|
||||
|
||||
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 = "eu02"
|
||||
)
|
||||
|
||||
var (
|
||||
testOrganizationId = uuid.NewString()
|
||||
testNetworkAreaId = uuid.NewString()
|
||||
testRoutingTableId = uuid.NewString()
|
||||
testRouteId1 = uuid.NewString()
|
||||
testRouteId2 = uuid.NewString()
|
||||
)
|
||||
|
||||
func Test_mapDataSourceRoutingTableRoutes(t *testing.T) {
|
||||
type args struct {
|
||||
routes *iaasalpha.RouteListResponse
|
||||
model *RoutingTableRoutesDataSourceModel
|
||||
region string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
wantErr bool
|
||||
expectedModel *RoutingTableRoutesDataSourceModel
|
||||
}{
|
||||
{
|
||||
name: "model is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
routes: &iaasalpha.RouteListResponse{
|
||||
Items: &[]iaasalpha.Route{},
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "response is nil",
|
||||
args: args{
|
||||
model: &RoutingTableRoutesDataSourceModel{},
|
||||
routes: nil,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "response items is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
routes: &iaasalpha.RouteListResponse{
|
||||
Items: nil,
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "response items is empty",
|
||||
args: args{
|
||||
model: &RoutingTableRoutesDataSourceModel{
|
||||
OrganizationId: types.StringValue(testOrganizationId),
|
||||
NetworkAreaId: types.StringValue(testNetworkAreaId),
|
||||
RoutingTableId: types.StringValue(testRoutingTableId),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
routes: &iaasalpha.RouteListResponse{
|
||||
Items: &[]iaasalpha.Route{},
|
||||
},
|
||||
region: testRegion,
|
||||
},
|
||||
wantErr: false,
|
||||
expectedModel: &RoutingTableRoutesDataSourceModel{
|
||||
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", testOrganizationId, testRegion, testNetworkAreaId, testRoutingTableId)),
|
||||
OrganizationId: types.StringValue(testOrganizationId),
|
||||
NetworkAreaId: types.StringValue(testNetworkAreaId),
|
||||
RoutingTableId: types.StringValue(testRoutingTableId),
|
||||
Region: types.StringValue(testRegion),
|
||||
Routes: types.ListValueMust(
|
||||
types.ObjectType{AttrTypes: shared.RouteReadModelTypes()}, []attr.Value{},
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "response items has items",
|
||||
args: args{
|
||||
model: &RoutingTableRoutesDataSourceModel{
|
||||
OrganizationId: types.StringValue(testOrganizationId),
|
||||
NetworkAreaId: types.StringValue(testNetworkAreaId),
|
||||
RoutingTableId: types.StringValue(testRoutingTableId),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
routes: &iaasalpha.RouteListResponse{
|
||||
Items: &[]iaasalpha.Route{
|
||||
{
|
||||
Id: utils.Ptr(testRouteId1),
|
||||
Destination: utils.Ptr(iaasalpha.DestinationCIDRv4AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv4("cidrv4", "58.251.236.138/32"),
|
||||
)),
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopIPv4AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv4("ipv4", "10.20.42.2"),
|
||||
)),
|
||||
Labels: &map[string]interface{}{
|
||||
"foo": "bar",
|
||||
},
|
||||
CreatedAt: nil,
|
||||
UpdatedAt: nil,
|
||||
},
|
||||
{
|
||||
Id: utils.Ptr(testRouteId2),
|
||||
Destination: utils.Ptr(iaasalpha.DestinationCIDRv6AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv6("cidrv6", "2001:0db8:3c4d:1a2b::/64"),
|
||||
)),
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopIPv6AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv6("ipv6", "172b:f881:46fe:d89a:9332:90f7:3485:236d"),
|
||||
)),
|
||||
Labels: &map[string]interface{}{
|
||||
"key": "value",
|
||||
},
|
||||
CreatedAt: nil,
|
||||
UpdatedAt: nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
region: testRegion,
|
||||
},
|
||||
wantErr: false,
|
||||
expectedModel: &RoutingTableRoutesDataSourceModel{
|
||||
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s", testOrganizationId, testRegion, testNetworkAreaId, testRoutingTableId)),
|
||||
OrganizationId: types.StringValue(testOrganizationId),
|
||||
NetworkAreaId: types.StringValue(testNetworkAreaId),
|
||||
RoutingTableId: types.StringValue(testRoutingTableId),
|
||||
Region: types.StringValue(testRegion),
|
||||
Routes: types.ListValueMust(
|
||||
types.ObjectType{AttrTypes: shared.RouteReadModelTypes()}, []attr.Value{
|
||||
types.ObjectValueMust(shared.RouteReadModelTypes(), map[string]attr.Value{
|
||||
"route_id": types.StringValue(testRouteId1),
|
||||
"created_at": types.StringNull(),
|
||||
"updated_at": types.StringNull(),
|
||||
"labels": types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"foo": types.StringValue("bar"),
|
||||
}),
|
||||
"destination": types.ObjectValueMust(shared.RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv4"),
|
||||
"value": types.StringValue("58.251.236.138/32"),
|
||||
}),
|
||||
"next_hop": types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv4"),
|
||||
"value": types.StringValue("10.20.42.2"),
|
||||
}),
|
||||
}),
|
||||
types.ObjectValueMust(shared.RouteReadModelTypes(), map[string]attr.Value{
|
||||
"route_id": types.StringValue(testRouteId2),
|
||||
"created_at": types.StringNull(),
|
||||
"updated_at": types.StringNull(),
|
||||
"labels": types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"key": types.StringValue("value"),
|
||||
}),
|
||||
"destination": types.ObjectValueMust(shared.RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv6"),
|
||||
"value": types.StringValue("2001:0db8:3c4d:1a2b::/64"),
|
||||
}),
|
||||
"next_hop": types.ObjectValueMust(shared.RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv6"),
|
||||
"value": types.StringValue("172b:f881:46fe:d89a:9332:90f7:3485:236d"),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if err := mapDataSourceRoutingTableRoutes(ctx, tt.args.routes, tt.args.model, tt.args.region); (err != nil) != tt.wantErr {
|
||||
t.Errorf("mapDataSourceRoutingTableRoutes() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
|
||||
diff := cmp.Diff(tt.args.model, tt.expectedModel)
|
||||
if diff != "" && !tt.wantErr {
|
||||
t.Fatalf("mapFieldsFromList(): %s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
213
stackit/internal/services/iaasalpha/routingtable/shared/route.go
Normal file
213
stackit/internal/services/iaasalpha/routingtable/shared/route.go
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
package shared
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
|
||||
)
|
||||
|
||||
type RouteReadModel struct {
|
||||
RouteId types.String `tfsdk:"route_id"`
|
||||
Destination types.Object `tfsdk:"destination"`
|
||||
NextHop types.Object `tfsdk:"next_hop"`
|
||||
Labels types.Map `tfsdk:"labels"`
|
||||
CreatedAt types.String `tfsdk:"created_at"`
|
||||
UpdatedAt types.String `tfsdk:"updated_at"`
|
||||
}
|
||||
|
||||
func RouteReadModelTypes() map[string]attr.Type {
|
||||
return map[string]attr.Type{
|
||||
"route_id": types.StringType,
|
||||
"destination": types.ObjectType{AttrTypes: RouteDestinationTypes},
|
||||
"next_hop": types.ObjectType{AttrTypes: RouteNextHopTypes},
|
||||
"labels": types.MapType{ElemType: types.StringType},
|
||||
"created_at": types.StringType,
|
||||
"updated_at": types.StringType,
|
||||
}
|
||||
}
|
||||
|
||||
type RouteModel struct {
|
||||
RouteReadModel
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
OrganizationId types.String `tfsdk:"organization_id"`
|
||||
RoutingTableId types.String `tfsdk:"routing_table_id"`
|
||||
NetworkAreaId types.String `tfsdk:"network_area_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
}
|
||||
|
||||
func RouteModelTypes() map[string]attr.Type {
|
||||
modelTypes := RouteReadModelTypes()
|
||||
modelTypes["id"] = types.StringType
|
||||
modelTypes["organization_id"] = types.StringType
|
||||
modelTypes["routing_table_id"] = types.StringType
|
||||
modelTypes["network_area_id"] = types.StringType
|
||||
modelTypes["region"] = types.StringType
|
||||
return modelTypes
|
||||
}
|
||||
|
||||
// RouteDestination is the struct corresponding to RouteReadModel.Destination
|
||||
type RouteDestination struct {
|
||||
Type types.String `tfsdk:"type"`
|
||||
Value types.String `tfsdk:"value"`
|
||||
}
|
||||
|
||||
// RouteDestinationTypes Types corresponding to routeDestination
|
||||
var RouteDestinationTypes = map[string]attr.Type{
|
||||
"type": types.StringType,
|
||||
"value": types.StringType,
|
||||
}
|
||||
|
||||
// RouteNextHop is the struct corresponding to RouteReadModel.NextHop
|
||||
type RouteNextHop struct {
|
||||
Type types.String `tfsdk:"type"`
|
||||
Value types.String `tfsdk:"value"`
|
||||
}
|
||||
|
||||
// RouteNextHopTypes Types corresponding to routeNextHop
|
||||
var RouteNextHopTypes = map[string]attr.Type{
|
||||
"type": types.StringType,
|
||||
"value": types.StringType,
|
||||
}
|
||||
|
||||
func MapRouteModel(ctx context.Context, route *iaasalpha.Route, model *RouteModel, region string) error {
|
||||
if route == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
err := MapRouteReadModel(ctx, route, &model.RouteReadModel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.OrganizationId.ValueString(),
|
||||
region,
|
||||
model.NetworkAreaId.ValueString(),
|
||||
model.RoutingTableId.ValueString(),
|
||||
model.RouteId.ValueString(),
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.Region = types.StringValue(region)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func MapRouteReadModel(ctx context.Context, route *iaasalpha.Route, model *RouteReadModel) error {
|
||||
if route == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var routeId string
|
||||
if model.RouteId.ValueString() != "" {
|
||||
routeId = model.RouteId.ValueString()
|
||||
} else if route.Id != nil {
|
||||
routeId = *route.Id
|
||||
} else {
|
||||
return fmt.Errorf("routing table route id not present")
|
||||
}
|
||||
|
||||
labels, err := iaasUtils.MapLabels(ctx, route.Labels, model.Labels)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// created at and updated at
|
||||
createdAtTF, updatedAtTF := types.StringNull(), types.StringNull()
|
||||
if route.CreatedAt != nil {
|
||||
createdAtValue := *route.CreatedAt
|
||||
createdAtTF = types.StringValue(createdAtValue.Format(time.RFC3339))
|
||||
}
|
||||
if route.UpdatedAt != nil {
|
||||
updatedAtValue := *route.UpdatedAt
|
||||
updatedAtTF = types.StringValue(updatedAtValue.Format(time.RFC3339))
|
||||
}
|
||||
|
||||
// destination
|
||||
model.Destination, err = MapRouteDestination(route)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error mapping route destination: %w", err)
|
||||
}
|
||||
|
||||
// next hop
|
||||
model.NextHop, err = MapRouteNextHop(route)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error mapping route next hop: %w", err)
|
||||
}
|
||||
|
||||
model.RouteId = types.StringValue(routeId)
|
||||
model.CreatedAt = createdAtTF
|
||||
model.UpdatedAt = updatedAtTF
|
||||
model.Labels = labels
|
||||
return nil
|
||||
}
|
||||
|
||||
func MapRouteNextHop(routeResp *iaasalpha.Route) (types.Object, error) {
|
||||
if routeResp.Nexthop == nil {
|
||||
return types.ObjectNull(RouteNextHopTypes), nil
|
||||
}
|
||||
|
||||
nextHopMap := map[string]attr.Value{}
|
||||
switch i := routeResp.Nexthop.GetActualInstance().(type) {
|
||||
case *iaasalpha.NexthopIPv4:
|
||||
nextHopMap["type"] = types.StringValue(*i.Type)
|
||||
nextHopMap["value"] = types.StringPointerValue(i.Value)
|
||||
case *iaasalpha.NexthopIPv6:
|
||||
nextHopMap["type"] = types.StringValue(*i.Type)
|
||||
nextHopMap["value"] = types.StringPointerValue(i.Value)
|
||||
case *iaasalpha.NexthopBlackhole:
|
||||
nextHopMap["type"] = types.StringValue(*i.Type)
|
||||
nextHopMap["value"] = types.StringNull()
|
||||
case *iaasalpha.NexthopInternet:
|
||||
nextHopMap["type"] = types.StringValue(*i.Type)
|
||||
nextHopMap["value"] = types.StringNull()
|
||||
default:
|
||||
return types.ObjectNull(RouteNextHopTypes), fmt.Errorf("unexpected Nexthop type: %T", i)
|
||||
}
|
||||
|
||||
nextHopTF, diags := types.ObjectValue(RouteNextHopTypes, nextHopMap)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(RouteNextHopTypes), core.DiagsToError(diags)
|
||||
}
|
||||
|
||||
return nextHopTF, nil
|
||||
}
|
||||
|
||||
func MapRouteDestination(routeResp *iaasalpha.Route) (types.Object, error) {
|
||||
if routeResp.Destination == nil {
|
||||
return types.ObjectNull(RouteDestinationTypes), nil
|
||||
}
|
||||
|
||||
destinationMap := map[string]attr.Value{}
|
||||
switch i := routeResp.Destination.GetActualInstance().(type) {
|
||||
case *iaasalpha.DestinationCIDRv4:
|
||||
destinationMap["type"] = types.StringValue(*i.Type)
|
||||
destinationMap["value"] = types.StringPointerValue(i.Value)
|
||||
case *iaasalpha.DestinationCIDRv6:
|
||||
destinationMap["type"] = types.StringValue(*i.Type)
|
||||
destinationMap["value"] = types.StringPointerValue(i.Value)
|
||||
default:
|
||||
return types.ObjectNull(RouteDestinationTypes), fmt.Errorf("unexpected Destionation type: %T", i)
|
||||
}
|
||||
|
||||
destinationTF, diags := types.ObjectValue(RouteDestinationTypes, destinationMap)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(RouteDestinationTypes), core.DiagsToError(diags)
|
||||
}
|
||||
|
||||
return destinationTF, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,310 @@
|
|||
package shared
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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 = "eu02"
|
||||
)
|
||||
|
||||
var (
|
||||
testRouteId = uuid.New()
|
||||
testOrganizationId = uuid.New()
|
||||
testNetworkAreaId = uuid.New()
|
||||
testRoutingTableId = uuid.New()
|
||||
)
|
||||
|
||||
func Test_MapRouteNextHop(t *testing.T) {
|
||||
type args struct {
|
||||
routeResp *iaasalpha.Route
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
wantErr bool
|
||||
expected types.Object
|
||||
}{
|
||||
{
|
||||
name: "nexthop is nil",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Nexthop: nil,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectNull(RouteNextHopTypes),
|
||||
},
|
||||
{
|
||||
name: "nexthop is empty",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Nexthop: &iaasalpha.RouteNexthop{},
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "nexthop ipv4",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopIPv4AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv4("ipv4", "10.20.42.2"),
|
||||
)),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectValueMust(RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv4"),
|
||||
"value": types.StringValue("10.20.42.2"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "nexthop ipv6",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopIPv6AsRouteNexthop(
|
||||
iaasalpha.NewNexthopIPv6("ipv6", "172b:f881:46fe:d89a:9332:90f7:3485:236d"),
|
||||
)),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectValueMust(RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv6"),
|
||||
"value": types.StringValue("172b:f881:46fe:d89a:9332:90f7:3485:236d"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "nexthop internet",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopInternetAsRouteNexthop(
|
||||
iaasalpha.NewNexthopInternet("internet"),
|
||||
)),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectValueMust(RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("internet"),
|
||||
"value": types.StringNull(),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "nexthop blackhole",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Nexthop: utils.Ptr(iaasalpha.NexthopBlackholeAsRouteNexthop(
|
||||
iaasalpha.NewNexthopBlackhole("blackhole"),
|
||||
)),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectValueMust(RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("blackhole"),
|
||||
"value": types.StringNull(),
|
||||
}),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
actual, err := MapRouteNextHop(tt.args.routeResp)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("mapNextHop() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
|
||||
diff := cmp.Diff(actual, tt.expected)
|
||||
if !tt.wantErr && diff != "" {
|
||||
t.Errorf("mapNextHop() result does not match: %s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_MapRouteDestination(t *testing.T) {
|
||||
type args struct {
|
||||
routeResp *iaasalpha.Route
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
wantErr bool
|
||||
expected types.Object
|
||||
}{
|
||||
|
||||
{
|
||||
name: "destination is nil",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Destination: nil,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectNull(RouteDestinationTypes),
|
||||
},
|
||||
{
|
||||
name: "destination is empty",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Destination: &iaasalpha.RouteDestination{},
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "destination cidrv4",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Destination: utils.Ptr(iaasalpha.DestinationCIDRv4AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv4("cidrv4", "58.251.236.138/32"),
|
||||
)),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectValueMust(RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv4"),
|
||||
"value": types.StringValue("58.251.236.138/32"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "destination cidrv6",
|
||||
args: args{
|
||||
routeResp: &iaasalpha.Route{
|
||||
Destination: utils.Ptr(iaasalpha.DestinationCIDRv6AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv6("cidrv6", "2001:0db8:3c4d:1a2b::/64"),
|
||||
)),
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
expected: types.ObjectValueMust(RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv6"),
|
||||
"value": types.StringValue("2001:0db8:3c4d:1a2b::/64"),
|
||||
}),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
actual, err := MapRouteDestination(tt.args.routeResp)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("mapDestination() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
|
||||
diff := cmp.Diff(actual, tt.expected)
|
||||
if !tt.wantErr && diff != "" {
|
||||
t.Errorf("mapDestination() result does not match: %s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapRouteModel(t *testing.T) {
|
||||
createdAt := time.Now()
|
||||
updatedAt := time.Now().Add(5 * time.Minute)
|
||||
|
||||
type args struct {
|
||||
route *iaasalpha.Route
|
||||
model *RouteModel
|
||||
region string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
wantErr bool
|
||||
expectedModel *RouteModel
|
||||
}{
|
||||
{
|
||||
name: "route is nil",
|
||||
args: args{
|
||||
model: &RouteModel{},
|
||||
route: nil,
|
||||
region: testRegion,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "model is nil",
|
||||
args: args{
|
||||
model: nil,
|
||||
route: &iaasalpha.Route{},
|
||||
region: testRegion,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "max",
|
||||
args: args{
|
||||
model: &RouteModel{
|
||||
// state
|
||||
OrganizationId: types.StringValue(testOrganizationId.String()),
|
||||
NetworkAreaId: types.StringValue(testNetworkAreaId.String()),
|
||||
RoutingTableId: types.StringValue(testRoutingTableId.String()),
|
||||
},
|
||||
route: &iaasalpha.Route{
|
||||
Id: utils.Ptr(testRouteId.String()),
|
||||
Destination: utils.Ptr(iaasalpha.DestinationCIDRv4AsRouteDestination(
|
||||
iaasalpha.NewDestinationCIDRv4("cidrv4", "58.251.236.138/32"),
|
||||
)),
|
||||
Labels: &map[string]interface{}{
|
||||
"foo1": "bar1",
|
||||
"foo2": "bar2",
|
||||
},
|
||||
Nexthop: utils.Ptr(
|
||||
iaasalpha.NexthopIPv4AsRouteNexthop(iaasalpha.NewNexthopIPv4("ipv4", "10.20.42.2")),
|
||||
),
|
||||
CreatedAt: &createdAt,
|
||||
UpdatedAt: &updatedAt,
|
||||
},
|
||||
region: testRegion,
|
||||
},
|
||||
wantErr: false,
|
||||
expectedModel: &RouteModel{
|
||||
Id: types.StringValue(fmt.Sprintf("%s,%s,%s,%s,%s",
|
||||
testOrganizationId.String(), testRegion, testNetworkAreaId.String(), testRoutingTableId.String(), testRouteId.String()),
|
||||
),
|
||||
OrganizationId: types.StringValue(testOrganizationId.String()),
|
||||
NetworkAreaId: types.StringValue(testNetworkAreaId.String()),
|
||||
RoutingTableId: types.StringValue(testRoutingTableId.String()),
|
||||
RouteReadModel: RouteReadModel{
|
||||
RouteId: types.StringValue(testRouteId.String()),
|
||||
Destination: types.ObjectValueMust(RouteDestinationTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("cidrv4"),
|
||||
"value": types.StringValue("58.251.236.138/32"),
|
||||
}),
|
||||
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"foo1": types.StringValue("bar1"),
|
||||
"foo2": types.StringValue("bar2"),
|
||||
}),
|
||||
NextHop: types.ObjectValueMust(RouteNextHopTypes, map[string]attr.Value{
|
||||
"type": types.StringValue("ipv4"),
|
||||
"value": types.StringValue("10.20.42.2"),
|
||||
}),
|
||||
CreatedAt: types.StringValue(createdAt.Format(time.RFC3339)),
|
||||
UpdatedAt: types.StringValue(updatedAt.Format(time.RFC3339)),
|
||||
},
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if err := MapRouteModel(ctx, tt.args.route, tt.args.model, tt.args.region); (err != nil) != tt.wantErr {
|
||||
t.Errorf("MapRouteModel() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
|
||||
diff := cmp.Diff(tt.args.model, tt.expectedModel)
|
||||
if !tt.wantErr && diff != "" {
|
||||
t.Errorf("MapRouteModel() model does not match: %s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,263 @@
|
|||
package shared
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
type RoutingTableReadModel struct {
|
||||
RoutingTableId types.String `tfsdk:"routing_table_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
Labels types.Map `tfsdk:"labels"`
|
||||
CreatedAt types.String `tfsdk:"created_at"`
|
||||
UpdatedAt types.String `tfsdk:"updated_at"`
|
||||
Default types.Bool `tfsdk:"default"`
|
||||
SystemRoutes types.Bool `tfsdk:"system_routes"`
|
||||
}
|
||||
|
||||
func RoutingTableReadModelTypes() map[string]attr.Type {
|
||||
return map[string]attr.Type{
|
||||
"routing_table_id": types.StringType,
|
||||
"name": types.StringType,
|
||||
"description": types.StringType,
|
||||
"labels": types.MapType{ElemType: types.StringType},
|
||||
"created_at": types.StringType,
|
||||
"updated_at": types.StringType,
|
||||
"default": types.BoolType,
|
||||
"system_routes": types.BoolType,
|
||||
}
|
||||
}
|
||||
|
||||
type RoutingTableDataSourceModel struct {
|
||||
RoutingTableReadModel
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
OrganizationId types.String `tfsdk:"organization_id"`
|
||||
NetworkAreaId types.String `tfsdk:"network_area_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
}
|
||||
|
||||
func GetDatasourceGetAttributes() map[string]schema.Attribute {
|
||||
// combine the schemas
|
||||
getAttributes := RoutingTableResponseAttributes()
|
||||
maps.Copy(getAttributes, datasourceGetAttributes())
|
||||
getAttributes["id"] = schema.StringAttribute{
|
||||
Description: "Terraform's internal datasource ID. It is structured as \"`organization_id`,`region`,`network_area_id`,`routing_table_id`\".",
|
||||
Computed: true,
|
||||
}
|
||||
return getAttributes
|
||||
}
|
||||
|
||||
func GetRouteDataSourceAttributes() map[string]schema.Attribute {
|
||||
getAttributes := datasourceGetAttributes()
|
||||
maps.Copy(getAttributes, RouteResponseAttributes())
|
||||
getAttributes["route_id"] = schema.StringAttribute{
|
||||
Description: "Route ID.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
}
|
||||
getAttributes["id"] = schema.StringAttribute{
|
||||
Description: "Terraform's internal datasource ID. It is structured as \"`organization_id`,`region`,`network_area_id`,`routing_table_id`,`route_id`\".",
|
||||
Computed: true,
|
||||
}
|
||||
return getAttributes
|
||||
}
|
||||
|
||||
func GetRoutesDataSourceAttributes() map[string]schema.Attribute {
|
||||
getAttributes := datasourceGetAttributes()
|
||||
getAttributes["id"] = schema.StringAttribute{
|
||||
Description: "Terraform's internal datasource ID. It is structured as \"`organization_id`,`region`,`network_area_id`,`routing_table_id`,`route_id`\".",
|
||||
Computed: true,
|
||||
}
|
||||
getAttributes["routes"] = schema.ListNestedAttribute{
|
||||
Description: "List of routes.",
|
||||
Computed: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: RouteResponseAttributes(),
|
||||
},
|
||||
}
|
||||
getAttributes["region"] = schema.StringAttribute{
|
||||
Description: "The datasource region. If not defined, the provider region is used.",
|
||||
Optional: true,
|
||||
}
|
||||
return getAttributes
|
||||
}
|
||||
|
||||
func datasourceGetAttributes() map[string]schema.Attribute {
|
||||
return map[string]schema.Attribute{
|
||||
"organization_id": schema.StringAttribute{
|
||||
Description: "STACKIT organization ID to which the routing table is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"routing_table_id": schema.StringAttribute{
|
||||
Description: "The routing tables ID.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"network_area_id": schema.StringAttribute{
|
||||
Description: "The network area ID to which the routing table is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Description: "The resource region. If not defined, the provider region is used.",
|
||||
Optional: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func RouteResponseAttributes() map[string]schema.Attribute {
|
||||
return map[string]schema.Attribute{
|
||||
"route_id": schema.StringAttribute{
|
||||
Description: "Route ID.",
|
||||
Computed: true,
|
||||
},
|
||||
"destination": schema.SingleNestedAttribute{
|
||||
Description: "Destination of the route.",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"type": schema.StringAttribute{
|
||||
Description: fmt.Sprintf("CIDRV type. %s %s", utils.FormatPossibleValues("cidrv4", "cidrv6"), "Only `cidrv4` is supported during experimental stage."),
|
||||
Computed: true,
|
||||
},
|
||||
"value": schema.StringAttribute{
|
||||
Description: "An CIDR string.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"next_hop": schema.SingleNestedAttribute{
|
||||
Description: "Next hop destination.",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"type": schema.StringAttribute{
|
||||
Description: fmt.Sprintf("%s %s.", utils.FormatPossibleValues("blackhole", "internet", "ipv4", "ipv6"), "Only `cidrv4` is supported during experimental stage."),
|
||||
Computed: true,
|
||||
},
|
||||
"value": schema.StringAttribute{
|
||||
Description: "Either IPv4 or IPv6 (not set for blackhole and internet). Only IPv4 supported during experimental stage.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: "Labels are key-value string pairs which can be attached to a resource container",
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"created_at": schema.StringAttribute{
|
||||
Description: "Date-time when the route was created",
|
||||
Computed: true,
|
||||
},
|
||||
"updated_at": schema.StringAttribute{
|
||||
Description: "Date-time when the route was updated",
|
||||
Computed: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func RoutingTableResponseAttributes() map[string]schema.Attribute {
|
||||
return map[string]schema.Attribute{
|
||||
"routing_table_id": schema.StringAttribute{
|
||||
Description: "The routing tables ID.",
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "The name of the routing table.",
|
||||
Computed: true,
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Description: "Description of the routing table.",
|
||||
Computed: true,
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: "Labels are key-value string pairs which can be attached to a resource container",
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"default": schema.BoolAttribute{
|
||||
Description: "When true this is the default routing table for this network area. It can't be deleted and is used if the user does not specify it otherwise.",
|
||||
Computed: true,
|
||||
},
|
||||
"system_routes": schema.BoolAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"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,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func MapRoutingTableReadModel(ctx context.Context, routingTable *iaasalpha.RoutingTable, model *RoutingTableReadModel) 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")
|
||||
}
|
||||
|
||||
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.Default = types.BoolPointerValue(routingTable.Default)
|
||||
model.SystemRoutes = types.BoolPointerValue(routingTable.SystemRoutes)
|
||||
model.Labels = labels
|
||||
model.CreatedAt = createdAtTF
|
||||
model.UpdatedAt = updatedAtTF
|
||||
return nil
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,212 @@
|
|||
package tables
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/routingtable/shared"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"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 (
|
||||
_ datasource.DataSource = &routingTablesDataSource{}
|
||||
)
|
||||
|
||||
type DataSourceModelTables struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
OrganizationId types.String `tfsdk:"organization_id"`
|
||||
NetworkAreaId types.String `tfsdk:"network_area_id"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
Items types.List `tfsdk:"items"`
|
||||
}
|
||||
|
||||
// NewRoutingTablesDataSource is a helper function to simplify the provider implementation.
|
||||
func NewRoutingTablesDataSource() datasource.DataSource {
|
||||
return &routingTablesDataSource{}
|
||||
}
|
||||
|
||||
// routingTableDataSource is the data source implementation.
|
||||
type routingTablesDataSource struct {
|
||||
client *iaasalpha.APIClient
|
||||
providerData core.ProviderData
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *routingTablesDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_routing_tables"
|
||||
}
|
||||
|
||||
func (d *routingTablesDataSource) 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_tables", 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 *routingTablesDataSource) 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: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal datasource ID. It is structured as \"`organization_id`,`region`,`network_area_id`\".",
|
||||
Computed: true,
|
||||
},
|
||||
"organization_id": schema.StringAttribute{
|
||||
Description: "STACKIT organization ID to which the routing table is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"network_area_id": schema.StringAttribute{
|
||||
Description: "The network area ID to which the routing table is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Description: "The resource region. If not defined, the provider region is used.",
|
||||
// the region cannot be found, so it has to be passed
|
||||
Optional: true,
|
||||
},
|
||||
"items": schema.ListNestedAttribute{
|
||||
Description: "List of routing tables.",
|
||||
Computed: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: shared.RoutingTableResponseAttributes(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *routingTablesDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model DataSourceModelTables
|
||||
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)
|
||||
networkAreaId := model.NetworkAreaId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "organization_id", organizationId)
|
||||
ctx = tflog.SetField(ctx, "region", region)
|
||||
ctx = tflog.SetField(ctx, "network_area_id", networkAreaId)
|
||||
|
||||
routingTablesResp, err := d.client.ListRoutingTablesOfArea(ctx, organizationId, networkAreaId, region).Execute()
|
||||
if err != nil {
|
||||
utils.LogError(
|
||||
ctx,
|
||||
&resp.Diagnostics,
|
||||
err,
|
||||
"Reading routing tables",
|
||||
fmt.Sprintf("Routing tables with network area with ID %q does not exist in organization %q.", 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 = mapDataSourceRoutingTables(ctx, routingTablesResp, &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 mapDataSourceRoutingTables(ctx context.Context, routingTables *iaasalpha.RoutingTableListResponse, model *DataSourceModelTables, region string) error {
|
||||
if routingTables == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
if routingTables.Items == nil {
|
||||
return fmt.Errorf("items input is nil")
|
||||
}
|
||||
|
||||
organizationId := model.OrganizationId.ValueString()
|
||||
networkAreaId := model.NetworkAreaId.ValueString()
|
||||
|
||||
model.Id = utils.BuildInternalTerraformId(organizationId, region, networkAreaId)
|
||||
|
||||
itemsList := []attr.Value{}
|
||||
for i, routingTable := range *routingTables.Items {
|
||||
var routingTableModel shared.RoutingTableReadModel
|
||||
err := shared.MapRoutingTableReadModel(ctx, &routingTable, &routingTableModel)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping routes: %w", err)
|
||||
}
|
||||
|
||||
routingTableMap := map[string]attr.Value{
|
||||
"routing_table_id": routingTableModel.RoutingTableId,
|
||||
"name": routingTableModel.Name,
|
||||
"description": routingTableModel.Description,
|
||||
"labels": routingTableModel.Labels,
|
||||
"created_at": routingTableModel.CreatedAt,
|
||||
"updated_at": routingTableModel.UpdatedAt,
|
||||
"default": routingTableModel.Default,
|
||||
"system_routes": routingTableModel.SystemRoutes,
|
||||
}
|
||||
|
||||
routingTableTF, diags := types.ObjectValue(shared.RoutingTableReadModelTypes(), routingTableMap)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("mapping index %d: %w", i, core.DiagsToError(diags))
|
||||
}
|
||||
itemsList = append(itemsList, routingTableTF)
|
||||
}
|
||||
|
||||
itemsListTF, diags := types.ListValue(types.ObjectType{AttrTypes: shared.RoutingTableReadModelTypes()}, itemsList)
|
||||
if diags.HasError() {
|
||||
return core.DiagsToError(diags)
|
||||
}
|
||||
model.Items = itemsListTF
|
||||
model.Region = types.StringValue(region)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
package tables
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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()
|
||||
secondRoutingTableId = uuid.New()
|
||||
)
|
||||
|
||||
func TestMapDataFields(t *testing.T) {
|
||||
terraformId := fmt.Sprintf("%s,%s,%s", organizationId.String(), testRegion, networkAreaId.String())
|
||||
createdAt := time.Now()
|
||||
updatedAt := time.Now().Add(5 * time.Minute)
|
||||
|
||||
tests := []struct {
|
||||
description string
|
||||
state DataSourceModelTables
|
||||
input *iaasalpha.RoutingTableListResponse
|
||||
expected DataSourceModelTables
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
DataSourceModelTables{
|
||||
OrganizationId: types.StringValue(organizationId.String()),
|
||||
NetworkAreaId: types.StringValue(networkAreaId.String()),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
&iaasalpha.RoutingTableListResponse{
|
||||
Items: &[]iaasalpha.RoutingTable{
|
||||
{
|
||||
Id: utils.Ptr(routingTableId.String()),
|
||||
Name: utils.Ptr("test"),
|
||||
Description: utils.Ptr("description"),
|
||||
Default: utils.Ptr(true),
|
||||
CreatedAt: &createdAt,
|
||||
UpdatedAt: &updatedAt,
|
||||
SystemRoutes: utils.Ptr(false),
|
||||
},
|
||||
},
|
||||
},
|
||||
DataSourceModelTables{
|
||||
Id: types.StringValue(terraformId),
|
||||
OrganizationId: types.StringValue(organizationId.String()),
|
||||
NetworkAreaId: types.StringValue(networkAreaId.String()),
|
||||
Region: types.StringValue(testRegion),
|
||||
Items: types.ListValueMust(types.ObjectType{AttrTypes: shared.RoutingTableReadModelTypes()}, []attr.Value{
|
||||
types.ObjectValueMust(shared.RoutingTableReadModelTypes(), map[string]attr.Value{
|
||||
"routing_table_id": types.StringValue(routingTableId.String()),
|
||||
"name": types.StringValue("test"),
|
||||
"description": types.StringValue("description"),
|
||||
"default": types.BoolValue(true),
|
||||
"system_routes": types.BoolValue(false),
|
||||
"created_at": types.StringValue(createdAt.Format(time.RFC3339)),
|
||||
"updated_at": types.StringValue(updatedAt.Format(time.RFC3339)),
|
||||
"labels": types.MapNull(types.StringType),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"two routing tables",
|
||||
DataSourceModelTables{
|
||||
OrganizationId: types.StringValue(organizationId.String()),
|
||||
NetworkAreaId: types.StringValue(networkAreaId.String()),
|
||||
Region: types.StringValue(testRegion),
|
||||
},
|
||||
&iaasalpha.RoutingTableListResponse{
|
||||
Items: &[]iaasalpha.RoutingTable{
|
||||
{
|
||||
Id: utils.Ptr(routingTableId.String()),
|
||||
Name: utils.Ptr("test"),
|
||||
Description: utils.Ptr("description"),
|
||||
Default: utils.Ptr(true),
|
||||
CreatedAt: &createdAt,
|
||||
UpdatedAt: &updatedAt,
|
||||
SystemRoutes: utils.Ptr(false),
|
||||
},
|
||||
{
|
||||
Id: utils.Ptr(secondRoutingTableId.String()),
|
||||
Name: utils.Ptr("test2"),
|
||||
Description: utils.Ptr("description2"),
|
||||
Default: utils.Ptr(false),
|
||||
CreatedAt: &createdAt,
|
||||
UpdatedAt: &updatedAt,
|
||||
SystemRoutes: utils.Ptr(false),
|
||||
},
|
||||
},
|
||||
},
|
||||
DataSourceModelTables{
|
||||
Id: types.StringValue(terraformId),
|
||||
OrganizationId: types.StringValue(organizationId.String()),
|
||||
NetworkAreaId: types.StringValue(networkAreaId.String()),
|
||||
Region: types.StringValue(testRegion),
|
||||
Items: types.ListValueMust(types.ObjectType{AttrTypes: shared.RoutingTableReadModelTypes()}, []attr.Value{
|
||||
types.ObjectValueMust(shared.RoutingTableReadModelTypes(), map[string]attr.Value{
|
||||
"routing_table_id": types.StringValue(routingTableId.String()),
|
||||
"name": types.StringValue("test"),
|
||||
"description": types.StringValue("description"),
|
||||
"default": types.BoolValue(true),
|
||||
"system_routes": types.BoolValue(false),
|
||||
"created_at": types.StringValue(createdAt.Format(time.RFC3339)),
|
||||
"updated_at": types.StringValue(updatedAt.Format(time.RFC3339)),
|
||||
"labels": types.MapNull(types.StringType),
|
||||
}),
|
||||
types.ObjectValueMust(shared.RoutingTableReadModelTypes(), map[string]attr.Value{
|
||||
"routing_table_id": types.StringValue(secondRoutingTableId.String()),
|
||||
"name": types.StringValue("test2"),
|
||||
"description": types.StringValue("description2"),
|
||||
"default": types.BoolValue(false),
|
||||
"system_routes": types.BoolValue(false),
|
||||
"created_at": types.StringValue(createdAt.Format(time.RFC3339)),
|
||||
"updated_at": types.StringValue(updatedAt.Format(time.RFC3339)),
|
||||
"labels": types.MapNull(types.StringType),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"response_fields_items_nil_fail",
|
||||
DataSourceModelTables{},
|
||||
&iaasalpha.RoutingTableListResponse{
|
||||
Items: nil,
|
||||
},
|
||||
DataSourceModelTables{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"response_nil_fail",
|
||||
DataSourceModelTables{},
|
||||
nil,
|
||||
DataSourceModelTables{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
err := mapDataSourceRoutingTables(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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue