terraform-provider-stackitp.../stackit/internal/services/cdn/distribution/datasource.go
Malte Ehrlen 855d3040ef
Feature: CDN distribution resource and data source (#786)
* add datasource

* finish data source

* implement resource

* add unit tests

* add examples

* acceptance test

* review comments

* review comments 2

---------

Co-authored-by: Malte Ehrlen <malte.ehrlen@freiheit.com>
2025-04-29 15:59:07 +02:00

203 lines
6.6 KiB
Go

package cdn
import (
"context"
"fmt"
"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/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/cdn"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
type distributionDataSource struct {
client *cdn.APIClient
}
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &distributionDataSource{}
)
func NewDistributionDataSource() datasource.DataSource {
return &distributionDataSource{}
}
func (d *distributionDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
providerData, ok := req.ProviderData.(core.ProviderData)
if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
return
}
features.CheckBetaResourcesEnabled(ctx, &providerData, &resp.Diagnostics, "stackit_cdn_distribution", "datasource")
if resp.Diagnostics.HasError() {
return
}
var apiClient *cdn.APIClient
var err error
if providerData.CdnCustomEndpoint != "" {
apiClient, err = cdn.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithEndpoint(providerData.CdnCustomEndpoint),
)
} else {
apiClient, err = cdn.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
)
}
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v. This is an error related to the provider configuration, not to the resource configuration", err))
return
}
d.client = apiClient
tflog.Info(ctx, "Service Account client configured")
}
func (r *distributionDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_cdn_distribution"
}
func (r *distributionDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: features.AddBetaDescription("CDN distribution data source schema."),
Description: "CDN distribution data source schema.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: schemaDescriptions["id"],
Computed: true,
},
"distribution_id": schema.StringAttribute{
Description: schemaDescriptions["project_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
},
},
"project_id": schema.StringAttribute{
Description: schemaDescriptions["project_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
},
},
"status": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["status"],
},
"created_at": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["created_at"],
},
"updated_at": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["updated_at"],
},
"errors": schema.ListAttribute{
ElementType: types.StringType,
Computed: true,
Description: schemaDescriptions["errors"],
},
"domains": schema.ListNestedAttribute{
Computed: true,
Description: schemaDescriptions["domains"],
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["domain_name"],
},
"status": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["domain_status"],
},
"type": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["domain_type"],
},
"errors": schema.ListAttribute{
Computed: true,
Description: schemaDescriptions["domain_errors"],
ElementType: types.StringType,
},
},
},
},
"config": schema.SingleNestedAttribute{
Computed: true,
Description: schemaDescriptions["config"],
Attributes: map[string]schema.Attribute{
"backend": schema.SingleNestedAttribute{
Computed: true,
Description: schemaDescriptions["config_backend"],
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["config_backend_type"],
},
"origin_url": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["config_backend_origin_url"],
},
"origin_request_headers": schema.MapAttribute{
Computed: true,
Description: schemaDescriptions["config_backend_origin_request_headers"],
ElementType: types.StringType,
},
},
},
"regions": schema.ListAttribute{
Computed: true,
Description: schemaDescriptions["config_regions"],
ElementType: types.StringType,
}},
},
},
}
}
func (r *distributionDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
distributionId := model.DistributionId.ValueString()
distributionResp, err := r.client.GetDistributionExecute(ctx, projectId, distributionId)
if err != nil {
utils.LogError(
ctx,
&resp.Diagnostics,
err,
"Reading CDN distribution",
fmt.Sprintf("Unable to access CDN distribution %q.", distributionId),
map[int]string{},
)
resp.State.RemoveResource(ctx)
return
}
err = mapFields(distributionResp.Distribution, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading CDN distribution", fmt.Sprintf("Error processing API response: %v", err))
return
}
diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...)
}