diff --git a/internal/provider/config_hostname.go b/internal/provider/config_hostname.go new file mode 100644 index 0000000..08e9909 --- /dev/null +++ b/internal/provider/config_hostname.go @@ -0,0 +1,41 @@ +package provider + +import ( + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-go/tftypes" +) + +func hostnameFromConfig(config tfsdk.Config) (types.String, error) { + if !config.Raw.IsKnown() { + return types.StringUnknown(), nil + } + if config.Raw.IsNull() { + return types.StringNull(), nil + } + + attributes := map[string]tftypes.Value{} + if err := config.Raw.As(&attributes); err != nil { + return types.StringNull(), fmt.Errorf("decode data source config object: %w", err) + } + + hostnameValue, ok := attributes["hostname"] + if !ok { + return types.StringNull(), fmt.Errorf("hostname is missing from data source config") + } + if !hostnameValue.IsKnown() { + return types.StringUnknown(), nil + } + if hostnameValue.IsNull() { + return types.StringNull(), nil + } + + var hostname string + if err := hostnameValue.As(&hostname); err != nil { + return types.StringNull(), fmt.Errorf("decode hostname: %w", err) + } + + return types.StringValue(hostname), nil +} diff --git a/internal/provider/data_source_dns_records.go b/internal/provider/data_source_dns_records.go index a9342f9..cf43121 100644 --- a/internal/provider/data_source_dns_records.go +++ b/internal/provider/data_source_dns_records.go @@ -100,9 +100,9 @@ func (d *dnsRecordsDataSource) Configure(_ context.Context, req datasource.Confi } func (d *dnsRecordsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var hostname types.String - resp.Diagnostics.Append(req.Config.GetAttribute(ctx, path.Root("hostname"), &hostname)...) - if resp.Diagnostics.HasError() { + hostname, err := hostnameFromConfig(req.Config) + if err != nil { + resp.Diagnostics.AddError("Unable to parse data source configuration", err.Error()) return } diff --git a/internal/provider/data_source_domain.go b/internal/provider/data_source_domain.go index a84b666..5e225bb 100644 --- a/internal/provider/data_source_domain.go +++ b/internal/provider/data_source_domain.go @@ -73,9 +73,9 @@ func (d *domainDataSource) Configure(_ context.Context, req datasource.Configure } func (d *domainDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var hostname types.String - resp.Diagnostics.Append(req.Config.GetAttribute(ctx, path.Root("hostname"), &hostname)...) - if resp.Diagnostics.HasError() { + hostname, err := hostnameFromConfig(req.Config) + if err != nil { + resp.Diagnostics.AddError("Unable to parse data source configuration", err.Error()) return }