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

@ -31,7 +31,8 @@ func NewVolumeDataSource() datasource.DataSource {
// volumeDataSource is the data source implementation.
type volumeDataSource struct {
client *iaas.APIClient
client *iaas.APIClient
providerData core.ProviderData
}
// Metadata returns the data source type name.
@ -40,12 +41,13 @@ func (d *volumeDataSource) Metadata(_ context.Context, req datasource.MetadataRe
}
func (d *volumeDataSource) 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
}
@ -54,14 +56,14 @@ func (d *volumeDataSource) Configure(ctx context.Context, req datasource.Configu
}
// Schema defines the schema for the resource.
func (r *volumeDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
func (d *volumeDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
description := "Volume resource schema. Must have a `region` specified in the provider configuration."
resp.Schema = schema.Schema{
MarkdownDescription: description,
Description: description,
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`volume_id`\".",
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`volume_id`\".",
Computed: true,
},
"project_id": schema.StringAttribute{
@ -72,6 +74,11 @@ func (r *volumeDataSource) Schema(_ context.Context, _ datasource.SchemaRequest,
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,
},
"volume_id": schema.StringAttribute{
Description: "The volume ID.",
Required: true,
@ -140,14 +147,16 @@ func (d *volumeDataSource) Read(ctx context.Context, req datasource.ReadRequest,
return
}
projectId := model.ProjectId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
volumeId := model.VolumeId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
volumeResp, err := d.client.GetVolume(ctx, projectId, volumeId).Execute()
volumeResp, err := d.client.GetVolume(ctx, projectId, region, volumeId).Execute()
if err != nil {
utils.LogError(
ctx,
@ -165,7 +174,7 @@ func (d *volumeDataSource) Read(ctx context.Context, req datasource.ReadRequest,
ctx = core.LogResponse(ctx)
err = mapFields(ctx, volumeResp, &model)
err = mapFields(ctx, volumeResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading volume", fmt.Sprintf("Processing API payload: %v", err))
return

View file

@ -37,6 +37,7 @@ var (
_ resource.Resource = &volumeResource{}
_ resource.ResourceWithConfigure = &volumeResource{}
_ resource.ResourceWithImportState = &volumeResource{}
_ resource.ResourceWithModifyPlan = &volumeResource{}
SupportedSourceTypes = []string{"volume", "image", "snapshot", "backup"}
)
@ -44,6 +45,7 @@ var (
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
VolumeId types.String `tfsdk:"volume_id"`
Name types.String `tfsdk:"name"`
AvailabilityZone types.String `tfsdk:"availability_zone"`
@ -74,7 +76,8 @@ func NewVolumeResource() resource.Resource {
// volumeResource is the resource implementation.
type volumeResource struct {
client *iaas.APIClient
client *iaas.APIClient
providerData core.ProviderData
}
// Metadata returns the resource type name.
@ -82,6 +85,36 @@ func (r *volumeResource) Metadata(_ context.Context, req resource.MetadataReques
resp.TypeName = req.ProviderTypeName + "_volume"
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *volumeResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
}
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
}
}
// ConfigValidators validates the resource configuration
func (r *volumeResource) ConfigValidators(_ context.Context) []resource.ConfigValidator {
return []resource.ConfigValidator{
@ -94,12 +127,13 @@ func (r *volumeResource) ConfigValidators(_ context.Context) []resource.ConfigVa
// Configure adds the provider configured client to the resource.
func (r *volumeResource) 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
}
@ -115,7 +149,7 @@ func (r *volumeResource) Schema(_ context.Context, _ resource.SchemaRequest, res
Description: description,
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`volume_id`\".",
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`volume_id`\".",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
@ -132,6 +166,15 @@ func (r *volumeResource) Schema(_ context.Context, _ resource.SchemaRequest, res
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(),
},
},
"volume_id": schema.StringAttribute{
Description: "The volume ID.",
Computed: true,
@ -290,7 +333,9 @@ func (r *volumeResource) Create(ctx context.Context, req resource.CreateRequest,
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
var source = &sourceModel{}
if !(model.Source.IsNull() || model.Source.IsUnknown()) {
@ -310,7 +355,7 @@ func (r *volumeResource) Create(ctx context.Context, req resource.CreateRequest,
// Create new volume
volume, err := r.client.CreateVolume(ctx, projectId).CreateVolumePayload(*payload).Execute()
volume, err := r.client.CreateVolume(ctx, projectId, region).CreateVolumePayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", fmt.Sprintf("Calling API: %v", err))
return
@ -319,7 +364,7 @@ func (r *volumeResource) Create(ctx context.Context, req resource.CreateRequest,
ctx = core.LogResponse(ctx)
volumeId := *volume.Id
volume, err = wait.CreateVolumeWaitHandler(ctx, r.client, projectId, volumeId).WaitWithContext(ctx)
volume, err = wait.CreateVolumeWaitHandler(ctx, r.client, projectId, region, volumeId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", fmt.Sprintf("volume creation waiting: %v", err))
return
@ -328,7 +373,7 @@ func (r *volumeResource) Create(ctx context.Context, req resource.CreateRequest,
ctx = tflog.SetField(ctx, "volume_id", volumeId)
// Map response body to schema
err = mapFields(ctx, volume, &model)
err = mapFields(ctx, volume, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", fmt.Sprintf("Processing API payload: %v", err))
return
@ -350,15 +395,18 @@ func (r *volumeResource) Read(ctx context.Context, req resource.ReadRequest, res
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
volumeId := model.VolumeId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
volumeResp, err := r.client.GetVolume(ctx, projectId, volumeId).Execute()
volumeResp, err := r.client.GetVolume(ctx, projectId, region, volumeId).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 {
@ -372,7 +420,7 @@ func (r *volumeResource) Read(ctx context.Context, req resource.ReadRequest, res
ctx = core.LogResponse(ctx)
// Map response body to schema
err = mapFields(ctx, volumeResp, &model)
err = mapFields(ctx, volumeResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading volume", fmt.Sprintf("Processing API payload: %v", err))
return
@ -399,8 +447,10 @@ func (r *volumeResource) Update(ctx context.Context, req resource.UpdateRequest,
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
volumeId := model.VolumeId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
// Retrieve values from state
@ -418,7 +468,7 @@ func (r *volumeResource) Update(ctx context.Context, req resource.UpdateRequest,
return
}
// Update existing volume
updatedVolume, err := r.client.UpdateVolume(ctx, projectId, volumeId).UpdateVolumePayload(*payload).Execute()
updatedVolume, err := r.client.UpdateVolume(ctx, projectId, region, volumeId).UpdateVolumePayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", fmt.Sprintf("Calling API: %v", err))
return
@ -436,7 +486,7 @@ func (r *volumeResource) Update(ctx context.Context, req resource.UpdateRequest,
payload := iaas.ResizeVolumePayload{
Size: modelSize,
}
err := r.client.ResizeVolume(ctx, projectId, volumeId).ResizeVolumePayload(payload).Execute()
err := r.client.ResizeVolume(ctx, projectId, region, volumeId).ResizeVolumePayload(payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", fmt.Sprintf("Resizing the volume, calling API: %v", err))
}
@ -444,7 +494,7 @@ func (r *volumeResource) Update(ctx context.Context, req resource.UpdateRequest,
updatedVolume.Size = modelSize
}
}
err = mapFields(ctx, updatedVolume, &model)
err = mapFields(ctx, updatedVolume, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", fmt.Sprintf("Processing API payload: %v", err))
return
@ -468,15 +518,17 @@ func (r *volumeResource) Delete(ctx context.Context, req resource.DeleteRequest,
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
volumeId := model.VolumeId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
// Delete existing volume
err := r.client.DeleteVolume(ctx, projectId, volumeId).Execute()
err := r.client.DeleteVolume(ctx, projectId, region, volumeId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting volume", fmt.Sprintf("Calling API: %v", err))
return
@ -484,7 +536,7 @@ func (r *volumeResource) Delete(ctx context.Context, req resource.DeleteRequest,
ctx = core.LogResponse(ctx)
_, err = wait.DeleteVolumeWaitHandler(ctx, r.client, projectId, volumeId).WaitWithContext(ctx)
_, err = wait.DeleteVolumeWaitHandler(ctx, r.client, projectId, region, volumeId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting volume", fmt.Sprintf("volume deletion waiting: %v", err))
return
@ -498,25 +550,24 @@ func (r *volumeResource) Delete(ctx context.Context, req resource.DeleteRequest,
func (r *volumeResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing volume",
fmt.Sprintf("Expected import identifier with format: [project_id],[volume_id] Got: %q", req.ID),
fmt.Sprintf("Expected import identifier with format: [project_id],[region],[volume_id] Got: %q", req.ID),
)
return
}
projectId := idParts[0]
volumeId := idParts[1]
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": idParts[0],
"region": idParts[1],
"volume_id": idParts[2],
})
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("volume_id"), volumeId)...)
tflog.Info(ctx, "volume state imported")
}
func mapFields(ctx context.Context, volumeResp *iaas.Volume, model *Model) error {
func mapFields(ctx context.Context, volumeResp *iaas.Volume, model *Model, region string) error {
if volumeResp == nil {
return fmt.Errorf("response input is nil")
}
@ -533,7 +584,8 @@ func mapFields(ctx context.Context, volumeResp *iaas.Volume, model *Model) error
return fmt.Errorf("Volume id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), volumeId)
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, volumeId)
model.Region = types.StringValue(region)
labels, err := iaasUtils.MapLabels(ctx, volumeResp.Labels, model.Labels)
if err != nil {

View file

@ -12,24 +12,31 @@ import (
)
func TestMapFields(t *testing.T) {
type args struct {
state Model
input *iaas.Volume
region string
}
tests := []struct {
description string
state Model
input *iaas.Volume
args args
expected Model
isValid bool
}{
{
"default_values",
Model{
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
description: "default_values",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
},
input: &iaas.Volume{
Id: utils.Ptr("nid"),
},
region: "eu01",
},
&iaas.Volume{
Id: utils.Ptr("nid"),
},
Model{
Id: types.StringValue("pid,nid"),
expected: Model{
Id: types.StringValue("pid,eu01,nid"),
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
Name: types.StringNull(),
@ -40,30 +47,35 @@ func TestMapFields(t *testing.T) {
ServerId: types.StringNull(),
Size: types.Int64Null(),
Source: types.ObjectNull(sourceTypes),
Region: types.StringValue("eu01"),
},
true,
isValid: true,
},
{
"simple_values",
Model{
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
},
&iaas.Volume{
Id: utils.Ptr("nid"),
Name: utils.Ptr("name"),
AvailabilityZone: utils.Ptr("zone"),
Labels: &map[string]interface{}{
"key": "value",
description: "simple_values",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
Region: types.StringValue("eu01"),
},
Description: utils.Ptr("desc"),
PerformanceClass: utils.Ptr("class"),
ServerId: utils.Ptr("sid"),
Size: utils.Ptr(int64(1)),
Source: &iaas.VolumeSource{},
input: &iaas.Volume{
Id: utils.Ptr("nid"),
Name: utils.Ptr("name"),
AvailabilityZone: utils.Ptr("zone"),
Labels: &map[string]interface{}{
"key": "value",
},
Description: utils.Ptr("desc"),
PerformanceClass: utils.Ptr("class"),
ServerId: utils.Ptr("sid"),
Size: utils.Ptr(int64(1)),
Source: &iaas.VolumeSource{},
},
region: "eu02",
},
Model{
Id: types.StringValue("pid,nid"),
expected: Model{
Id: types.StringValue("pid,eu02,nid"),
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
Name: types.StringValue("name"),
@ -79,21 +91,25 @@ func TestMapFields(t *testing.T) {
"type": types.StringNull(),
"id": types.StringNull(),
}),
Region: types.StringValue("eu02"),
},
true,
isValid: true,
},
{
"empty_labels",
Model{
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
description: "empty_labels",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
},
input: &iaas.Volume{
Id: utils.Ptr("nid"),
},
region: "eu01",
},
&iaas.Volume{
Id: utils.Ptr("nid"),
},
Model{
Id: types.StringValue("pid,nid"),
expected: Model{
Id: types.StringValue("pid,eu01,nid"),
ProjectId: types.StringValue("pid"),
VolumeId: types.StringValue("nid"),
Name: types.StringNull(),
@ -104,29 +120,28 @@ func TestMapFields(t *testing.T) {
ServerId: types.StringNull(),
Size: types.Int64Null(),
Source: types.ObjectNull(sourceTypes),
Region: types.StringValue("eu01"),
},
true,
isValid: true,
},
{
"response_nil_fail",
Model{},
nil,
Model{},
false,
description: "response_nil_fail",
},
{
"no_resource_id",
Model{
ProjectId: types.StringValue("pid"),
description: "no_resource_id",
args: args{
state: Model{
ProjectId: types.StringValue("pid"),
},
input: &iaas.Volume{},
},
&iaas.Volume{},
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")
}
@ -134,7 +149,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)
}