feat(iaas): support for v2 API (#1070)

relates to STACKITTPR-313
This commit is contained in:
Ruben Hönle 2025-12-17 15:40:46 +01:00 committed by GitHub
parent 460c18c202
commit 53a3697850
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
124 changed files with 8342 additions and 6042 deletions

View file

@ -24,14 +24,15 @@ var (
_ datasource.DataSource = &networkInterfaceDataSource{}
)
// NewNetworkDataSource is a helper function to simplify the provider implementation.
// NewNetworkInterfaceDataSource is a helper function to simplify the provider implementation.
func NewNetworkInterfaceDataSource() datasource.DataSource {
return &networkInterfaceDataSource{}
}
// networkInterfaceDataSource is the data source implementation.
type networkInterfaceDataSource struct {
client *iaas.APIClient
client *iaas.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
@ -40,12 +41,13 @@ func (d *networkInterfaceDataSource) Metadata(_ context.Context, req datasource.
}
func (d *networkInterfaceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
apiClient := iaasUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
@ -63,7 +65,7 @@ func (d *networkInterfaceDataSource) Schema(_ context.Context, _ datasource.Sche
Description: description,
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Terraform's internal data source ID. It is structured as \"`project_id`,`network_id`,`network_interface_id`\".",
Description: "Terraform's internal data source ID. It is structured as \"`project_id`,`region`,`network_id`,`network_interface_id`\".",
Computed: true,
},
"project_id": schema.StringAttribute{
@ -74,6 +76,11 @@ func (d *networkInterfaceDataSource) Schema(_ context.Context, _ datasource.Sche
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,
},
"network_id": schema.StringAttribute{
Description: "The network ID to which the network interface is associated.",
Required: true,
@ -141,17 +148,20 @@ func (d *networkInterfaceDataSource) Read(ctx context.Context, req datasource.Re
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
networkId := model.NetworkId.ValueString()
networkInterfaceId := model.NetworkInterfaceId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "network_interface_id", networkInterfaceId)
networkInterfaceResp, err := d.client.GetNic(ctx, projectId, networkId, networkInterfaceId).Execute()
networkInterfaceResp, err := d.client.GetNic(ctx, projectId, region, networkId, networkInterfaceId).Execute()
if err != nil {
utils.LogError(
ctx,
@ -169,7 +179,7 @@ func (d *networkInterfaceDataSource) Read(ctx context.Context, req datasource.Re
ctx = core.LogResponse(ctx)
err = mapFields(ctx, networkInterfaceResp, &model)
err = mapFields(ctx, networkInterfaceResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network interface", fmt.Sprintf("Processing API payload: %v", err))
return

View file

@ -40,6 +40,7 @@ type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
NetworkId types.String `tfsdk:"network_id"`
Region types.String `tfsdk:"region"`
NetworkInterfaceId types.String `tfsdk:"network_interface_id"`
Name types.String `tfsdk:"name"`
AllowedAddresses types.List `tfsdk:"allowed_addresses"`
@ -59,7 +60,8 @@ func NewNetworkInterfaceResource() resource.Resource {
// networkResource is the resource implementation.
type networkInterfaceResource struct {
client *iaas.APIClient
client *iaas.APIClient
providerData core.ProviderData
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
@ -92,6 +94,17 @@ func (r *networkInterfaceResource) ModifyPlan(ctx context.Context, req resource.
if resp.Diagnostics.HasError() {
return
}
// Use the modifier to set the effective region in the current plan.
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
if resp.Diagnostics.HasError() {
return
}
}
// Metadata returns the resource type name.
@ -101,12 +114,13 @@ func (r *networkInterfaceResource) Metadata(_ context.Context, req resource.Meta
// Configure adds the provider configured client to the resource.
func (r *networkInterfaceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
apiClient := iaasUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
@ -124,7 +138,7 @@ func (r *networkInterfaceResource) Schema(_ context.Context, _ resource.SchemaRe
Description: description,
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`network_id`,`network_interface_id`\".",
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`network_id`,`network_interface_id`\".",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
@ -164,6 +178,15 @@ func (r *networkInterfaceResource) Schema(_ context.Context, _ resource.SchemaRe
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(),
},
},
"name": schema.StringAttribute{
Description: "The name of the network interface.",
Optional: true,
@ -260,8 +283,10 @@ func (r *networkInterfaceResource) Create(ctx context.Context, req resource.Crea
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
region := r.providerData.GetRegionWithOverride(model.Region)
networkId := model.NetworkId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_id", networkId)
// Generate API request body from model
@ -272,7 +297,7 @@ func (r *networkInterfaceResource) Create(ctx context.Context, req resource.Crea
}
// Create new network interface
networkInterface, err := r.client.CreateNic(ctx, projectId, networkId).CreateNicPayload(*payload).Execute()
networkInterface, err := r.client.CreateNic(ctx, projectId, region, networkId).CreateNicPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network interface", fmt.Sprintf("Calling API: %v", err))
return
@ -285,7 +310,7 @@ func (r *networkInterfaceResource) Create(ctx context.Context, req resource.Crea
ctx = tflog.SetField(ctx, "network_interface_id", networkInterfaceId)
// Map response body to schema
err = mapFields(ctx, networkInterface, &model)
err = mapFields(ctx, networkInterface, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network interface", fmt.Sprintf("Processing API payload: %v", err))
return
@ -308,16 +333,18 @@ func (r *networkInterfaceResource) Read(ctx context.Context, req resource.ReadRe
return
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
networkId := model.NetworkId.ValueString()
networkInterfaceId := model.NetworkInterfaceId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "network_interface_id", networkInterfaceId)
networkInterfaceResp, err := r.client.GetNic(ctx, projectId, networkId, networkInterfaceId).Execute()
networkInterfaceResp, err := r.client.GetNic(ctx, projectId, region, networkId, networkInterfaceId).Execute()
if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound {
@ -331,7 +358,7 @@ func (r *networkInterfaceResource) Read(ctx context.Context, req resource.ReadRe
ctx = core.LogResponse(ctx)
// Map response body to schema
err = mapFields(ctx, networkInterfaceResp, &model)
err = mapFields(ctx, networkInterfaceResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network interface", fmt.Sprintf("Processing API payload: %v", err))
return
@ -355,12 +382,14 @@ func (r *networkInterfaceResource) Update(ctx context.Context, req resource.Upda
return
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
networkId := model.NetworkId.ValueString()
networkInterfaceId := model.NetworkInterfaceId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "network_interface_id", networkInterfaceId)
@ -379,7 +408,7 @@ func (r *networkInterfaceResource) Update(ctx context.Context, req resource.Upda
return
}
// Update existing network
nicResp, err := r.client.UpdateNic(ctx, projectId, networkId, networkInterfaceId).UpdateNicPayload(*payload).Execute()
nicResp, err := r.client.UpdateNic(ctx, projectId, region, networkId, networkInterfaceId).UpdateNicPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network interface", fmt.Sprintf("Calling API: %v", err))
return
@ -387,7 +416,7 @@ func (r *networkInterfaceResource) Update(ctx context.Context, req resource.Upda
ctx = core.LogResponse(ctx)
err = mapFields(ctx, nicResp, &model)
err = mapFields(ctx, nicResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network interface", fmt.Sprintf("Processing API payload: %v", err))
return
@ -411,17 +440,19 @@ func (r *networkInterfaceResource) Delete(ctx context.Context, req resource.Dele
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
networkId := model.NetworkId.ValueString()
networkInterfaceId := model.NetworkInterfaceId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "network_interface_id", networkInterfaceId)
// Delete existing network interface
err := r.client.DeleteNic(ctx, projectId, networkId, networkInterfaceId).Execute()
err := r.client.DeleteNic(ctx, projectId, region, networkId, networkInterfaceId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting network interface", fmt.Sprintf("Calling API: %v", err))
return
@ -437,28 +468,25 @@ func (r *networkInterfaceResource) Delete(ctx context.Context, req resource.Dele
func (r *networkInterfaceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing network interface",
fmt.Sprintf("Expected import identifier with format: [project_id],[network_id],[network_interface_id] Got: %q", req.ID),
fmt.Sprintf("Expected import identifier with format: [project_id],[region],[network_id],[network_interface_id] Got: %q", req.ID),
)
return
}
projectId := idParts[0]
networkId := idParts[1]
networkInterfaceId := idParts[2]
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "network_interface_id", networkInterfaceId)
utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": idParts[0],
"region": idParts[1],
"network_id": idParts[2],
"network_interface_id": idParts[3],
})
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("network_id"), networkId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("network_interface_id"), networkInterfaceId)...)
tflog.Info(ctx, "Network interface state imported")
}
func mapFields(ctx context.Context, networkInterfaceResp *iaas.NIC, model *Model) error {
func mapFields(ctx context.Context, networkInterfaceResp *iaas.NIC, model *Model, region string) error {
if networkInterfaceResp == nil {
return fmt.Errorf("response input is nil")
}
@ -475,7 +503,8 @@ func mapFields(ctx context.Context, networkInterfaceResp *iaas.NIC, model *Model
return fmt.Errorf("network interface id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), model.NetworkId.ValueString(), networkInterfaceId)
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, model.NetworkId.ValueString(), networkInterfaceId)
model.Region = types.StringValue(region)
respAllowedAddresses := []string{}
var diags diag.Diagnostics

View file

@ -12,25 +12,32 @@ import (
)
func TestMapFields(t *testing.T) {
type args struct {
state Model
input *iaas.NIC
region string
}
tests := []struct {
description string
state Model
input *iaas.NIC
args args
expected Model
isValid bool
}{
{
"id_ok",
Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
description: "id_ok",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
},
input: &iaas.NIC{
Id: utils.Ptr("nicid"),
},
region: "eu01",
},
&iaas.NIC{
Id: utils.Ptr("nicid"),
},
Model{
Id: types.StringValue("pid,nid,nicid"),
expected: Model{
Id: types.StringValue("pid,eu01,nid,nicid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
@ -43,41 +50,46 @@ func TestMapFields(t *testing.T) {
Mac: types.StringNull(),
Type: types.StringNull(),
Labels: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
},
true,
isValid: true,
},
{
"values_ok",
Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
},
&iaas.NIC{
Id: utils.Ptr("nicid"),
Name: utils.Ptr("name"),
AllowedAddresses: &[]iaas.AllowedAddressesInner{
{
String: utils.Ptr("aa1"),
description: "values_ok",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
Region: types.StringValue("eu01"),
},
input: &iaas.NIC{
Id: utils.Ptr("nicid"),
Name: utils.Ptr("name"),
AllowedAddresses: &[]iaas.AllowedAddressesInner{
{
String: utils.Ptr("aa1"),
},
},
SecurityGroups: &[]string{
"prefix1",
"prefix2",
},
Ipv4: utils.Ptr("ipv4"),
Ipv6: utils.Ptr("ipv6"),
NicSecurity: utils.Ptr(true),
Device: utils.Ptr("device"),
Mac: utils.Ptr("mac"),
Status: utils.Ptr("status"),
Type: utils.Ptr("type"),
Labels: &map[string]interface{}{
"label1": "ref1",
},
},
SecurityGroups: &[]string{
"prefix1",
"prefix2",
},
Ipv4: utils.Ptr("ipv4"),
Ipv6: utils.Ptr("ipv6"),
NicSecurity: utils.Ptr(true),
Device: utils.Ptr("device"),
Mac: utils.Ptr("mac"),
Status: utils.Ptr("status"),
Type: utils.Ptr("type"),
Labels: &map[string]interface{}{
"label1": "ref1",
},
region: "eu02",
},
Model{
Id: types.StringValue("pid,nid,nicid"),
expected: Model{
Id: types.StringValue("pid,eu02,nid,nicid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
@ -95,29 +107,33 @@ func TestMapFields(t *testing.T) {
Mac: types.StringValue("mac"),
Type: types.StringValue("type"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{"label1": types.StringValue("ref1")}),
Region: types.StringValue("eu02"),
},
true,
isValid: true,
},
{
"allowed_addresses_changed_outside_tf",
Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
AllowedAddresses: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("aa1"),
}),
},
&iaas.NIC{
Id: utils.Ptr("nicid"),
AllowedAddresses: &[]iaas.AllowedAddressesInner{
{
String: utils.Ptr("aa2"),
description: "allowed_addresses_changed_outside_tf",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
AllowedAddresses: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("aa1"),
}),
},
input: &iaas.NIC{
Id: utils.Ptr("nicid"),
AllowedAddresses: &[]iaas.AllowedAddressesInner{
{
String: utils.Ptr("aa2"),
},
},
},
region: "eu01",
},
Model{
Id: types.StringValue("pid,nid,nicid"),
expected: Model{
Id: types.StringValue("pid,eu01,nid,nicid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
@ -127,23 +143,27 @@ func TestMapFields(t *testing.T) {
types.StringValue("aa2"),
}),
Labels: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
},
true,
isValid: true,
},
{
"empty_list_allowed_addresses",
Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
AllowedAddresses: types.ListValueMust(types.StringType, []attr.Value{}),
description: "empty_list_allowed_addresses",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
AllowedAddresses: types.ListValueMust(types.StringType, []attr.Value{}),
},
input: &iaas.NIC{
Id: utils.Ptr("nicid"),
AllowedAddresses: nil,
},
region: "eu01",
},
&iaas.NIC{
Id: utils.Ptr("nicid"),
AllowedAddresses: nil,
},
Model{
Id: types.StringValue("pid,nid,nicid"),
expected: Model{
Id: types.StringValue("pid,eu01,nid,nicid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
NetworkInterfaceId: types.StringValue("nicid"),
@ -151,29 +171,34 @@ func TestMapFields(t *testing.T) {
SecurityGroupIds: types.ListNull(types.StringType),
AllowedAddresses: types.ListValueMust(types.StringType, []attr.Value{}),
Labels: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
},
true,
isValid: true,
},
{
"response_nil_fail",
Model{},
nil,
Model{},
false,
description: "response_nil_fail",
args: args{
state: Model{},
input: nil,
},
expected: Model{},
isValid: false,
},
{
"no_resource_id",
Model{
ProjectId: types.StringValue("pid"),
description: "no_resource_id",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
},
input: &iaas.NIC{},
},
&iaas.NIC{},
Model{},
false,
expected: Model{},
isValid: false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
err := mapFields(context.Background(), tt.input, &tt.state)
err := mapFields(context.Background(), tt.args.input, &tt.args.state, tt.args.region)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
@ -181,7 +206,7 @@ func TestMapFields(t *testing.T) {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected)
diff := cmp.Diff(tt.args.state, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}