Add dynu_dns_record CRUD resource and write-capable client

This commit is contained in:
beatz174-bit committed 2026-04-23 13:52:55 +10:00
1 parent d6b52c1f44
commit 7d636b6371
9 files changed
+970 -49

No files matched your search

+5 -3
View File
@@ -43,7 +43,7 @@ func (p *dynuProvider) Metadata(_ context.Context, _ provider.MetadataRequest, r
func (p *dynuProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Terraform provider for Dynu DNS read-only data sources.",
Description: "Terraform provider for Dynu DNS domains, records, and data sources.",
Attributes: map[string]schema.Attribute{
"api_key": schema.StringAttribute{
Optional: true,
@@ -78,7 +78,7 @@ func (p *dynuProvider) Configure(ctx context.Context, req provider.ConfigureRequ
providerData := &providerData{client: newDynuClient(apiKey, data.BaseURL)}
resp.DataSourceData = providerData
resp.ResourceData = nil
resp.ResourceData = providerData
}
func resolveAPIKey(configValue types.String, envValue string) string {
@@ -97,7 +97,9 @@ func (p *dynuProvider) DataSources(_ context.Context) []func() datasource.DataSo
}
func (p *dynuProvider) Resources(_ context.Context) []func() resource.Resource {
return nil
return []func() resource.Resource{
NewDNSRecordResource,
}
}
func newDynuClient(apiKey string, baseURL types.String) *dynuclient.Client {
+316
View File
@@ -0,0 +1,316 @@
package provider
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/dynu/terraform-provider-dynu/internal/dynuclient"
)
var (
_ resource.Resource = &dnsRecordResource{}
_ resource.ResourceWithConfigure = &dnsRecordResource{}
_ resource.ResourceWithImportState = &dnsRecordResource{}
)
type dnsRecordResource struct {
clientProvider *providerData
}
type dnsRecordResourceModel struct {
ID types.String `tfsdk:"id"`
Hostname types.String `tfsdk:"hostname"`
RecordType types.String `tfsdk:"record_type"`
Content types.String `tfsdk:"content"`
TTL types.Int64 `tfsdk:"ttl"`
State types.Bool `tfsdk:"state"`
Group types.String `tfsdk:"group"`
Host types.String `tfsdk:"host"`
NodeName types.String `tfsdk:"node_name"`
DomainID types.Int64 `tfsdk:"domain_id"`
DomainName types.String `tfsdk:"domain_name"`
UpdatedOn types.String `tfsdk:"updated_on"`
}
func NewDNSRecordResource() resource.Resource {
return &dnsRecordResource{}
}
func (r *dnsRecordResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_dns_record"
}
func (r *dnsRecordResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a Dynu DNS record for the root domain resolved from hostname.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true, Description: "Resource identifier in domain_id/record_id format."},
"hostname": schema.StringAttribute{
Required: true,
Description: "Fully-qualified hostname under the target root domain.",
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.RegexMatches(hostnameValidator, "must be a valid fully-qualified hostname"),
},
},
"record_type": schema.StringAttribute{Required: true, Description: "DNS record type (A, AAAA, CNAME, TXT, etc.).", Validators: []validator.String{stringvalidator.LengthAtLeast(1)}},
"content": schema.StringAttribute{Required: true, Description: "Record content/value."},
"ttl": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "DNS TTL in seconds.",
Validators: []validator.Int64{int64validator.AtLeast(0)},
},
"state": schema.BoolAttribute{Optional: true, Computed: true, Description: "Whether this DNS record is active."},
"group": schema.StringAttribute{Optional: true, Computed: true, Description: "Dynu group value for this record."},
"host": schema.StringAttribute{Optional: true, Computed: true, Description: "Host field for supported Dynu record types."},
"node_name": schema.StringAttribute{Optional: true, Computed: true, Description: "Node/label portion of the record."},
"domain_id": schema.Int64Attribute{Computed: true, Description: "Dynu domain ID resolved from hostname."},
"domain_name": schema.StringAttribute{Computed: true, Description: "Dynu root domain name resolved from hostname."},
"updated_on": schema.StringAttribute{Computed: true, Description: "Last update timestamp as returned by Dynu."},
},
}
}
func (r *dnsRecordResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
providerData, ok := req.ProviderData.(*providerData)
if !ok {
resp.Diagnostics.AddError("Unexpected resource configure type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
return
}
r.clientProvider = providerData
}
func (r *dnsRecordResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan dnsRecordResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
domainID, domainName, err := r.clientProvider.client.GetRootDomain(ctx, plan.Hostname.ValueString())
if err != nil {
resp.Diagnostics.AddError(diagnosticSummary("Unable to resolve Dynu domain from hostname", err), err.Error())
return
}
createReq := dynuclient.CreateDNSRecordRequest{
NodeName: recordNodeName(plan.NodeName, plan.Hostname, domainName),
RecordType: strings.TrimSpace(plan.RecordType.ValueString()),
Content: strings.TrimSpace(plan.Content.ValueString()),
TTL: int64FromOptional(plan.TTL),
State: boolPointerFromOptional(plan.State),
Group: stringFromOptional(plan.Group),
Host: stringFromOptional(plan.Host),
}
record, err := r.clientProvider.client.CreateDNSRecord(ctx, domainID, createReq)
if err != nil {
resp.Diagnostics.AddError(diagnosticSummary("Unable to create Dynu DNS record", err), err.Error())
return
}
state := mapDNSRecordToState(*record)
state.ID = types.StringValue(formatDNSRecordID(record.DomainID, record.ID))
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *dnsRecordResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state dnsRecordResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
domainID, recordID, err := parseDNSRecordID(state.ID.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid resource ID", err.Error())
return
}
record, err := r.clientProvider.client.GetDNSRecord(ctx, domainID, recordID)
if err != nil {
var apiErr *dynuclient.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == 404 {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(diagnosticSummary("Unable to read Dynu DNS record", err), err.Error())
return
}
nextState := mapDNSRecordToState(*record)
nextState.ID = state.ID
resp.Diagnostics.Append(resp.State.Set(ctx, &nextState)...)
}
func (r *dnsRecordResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan dnsRecordResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
domainID, recordID, err := parseDNSRecordID(plan.ID.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid resource ID", err.Error())
return
}
domainName := strings.TrimSpace(plan.DomainName.ValueString())
if domainName == "" {
_, resolvedDomainName, err := r.clientProvider.client.GetRootDomain(ctx, plan.Hostname.ValueString())
if err != nil {
resp.Diagnostics.AddError(diagnosticSummary("Unable to resolve Dynu domain from hostname", err), err.Error())
return
}
domainName = resolvedDomainName
}
updateReq := dynuclient.UpdateDNSRecordRequest{
NodeName: recordNodeName(plan.NodeName, plan.Hostname, domainName),
RecordType: strings.TrimSpace(plan.RecordType.ValueString()),
Content: strings.TrimSpace(plan.Content.ValueString()),
TTL: int64FromOptional(plan.TTL),
State: boolPointerFromOptional(plan.State),
Group: stringFromOptional(plan.Group),
Host: stringFromOptional(plan.Host),
}
if _, err := r.clientProvider.client.UpdateDNSRecord(ctx, domainID, recordID, updateReq); err != nil {
resp.Diagnostics.AddError(diagnosticSummary("Unable to update Dynu DNS record", err), err.Error())
return
}
record, err := r.clientProvider.client.GetDNSRecord(ctx, domainID, recordID)
if err != nil {
resp.Diagnostics.AddError(diagnosticSummary("Unable to read Dynu DNS record", err), err.Error())
return
}
nextState := mapDNSRecordToState(*record)
nextState.ID = types.StringValue(formatDNSRecordID(record.DomainID, record.ID))
resp.Diagnostics.Append(resp.State.Set(ctx, &nextState)...)
}
func (r *dnsRecordResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state dnsRecordResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
domainID, recordID, err := parseDNSRecordID(state.ID.ValueString())
if err != nil {
resp.Diagnostics.AddError("Invalid resource ID", err.Error())
return
}
err = r.clientProvider.client.DeleteDNSRecord(ctx, domainID, recordID)
if err == nil {
return
}
var apiErr *dynuclient.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == 404 {
return
}
resp.Diagnostics.AddError(diagnosticSummary("Unable to delete Dynu DNS record", err), err.Error())
}
func (r *dnsRecordResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
domainID, recordID, err := parseDNSRecordID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Invalid import ID", err.Error())
return
}
state := dnsRecordResourceModel{ID: types.StringValue(formatDNSRecordID(domainID, recordID))}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func mapDNSRecordToState(record dynuclient.DNSRecord) dnsRecordResourceModel {
return dnsRecordResourceModel{
Hostname: mapString(record.Hostname),
RecordType: mapString(record.RecordType),
Content: mapString(record.Content),
TTL: types.Int64Value(record.TTL),
State: types.BoolValue(record.State),
Group: mapString(record.Group),
Host: mapString(record.Host),
NodeName: mapString(record.NodeName),
DomainID: types.Int64Value(record.DomainID),
DomainName: mapString(record.DomainName),
UpdatedOn: mapString(record.UpdatedOn),
}
}
func parseDNSRecordID(id string) (int64, int64, error) {
parts := strings.Split(strings.TrimSpace(id), "/")
if len(parts) != 2 {
return 0, 0, fmt.Errorf("expected import ID in domain_id/record_id format")
}
domainID, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil || domainID <= 0 {
return 0, 0, fmt.Errorf("invalid domain_id in ID %q", id)
}
recordID, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil || recordID <= 0 {
return 0, 0, fmt.Errorf("invalid record_id in ID %q", id)
}
return domainID, recordID, nil
}
func formatDNSRecordID(domainID int64, recordID int64) string {
return fmt.Sprintf("%d/%d", domainID, recordID)
}
func recordNodeName(nodeName types.String, hostname types.String, domainName string) string {
if !nodeName.IsNull() && !nodeName.IsUnknown() {
return strings.TrimSpace(nodeName.ValueString())
}
host := strings.TrimSpace(hostname.ValueString())
domain := strings.TrimSpace(domainName)
if strings.EqualFold(host, domain) {
return ""
}
suffix := "." + domain
if strings.HasSuffix(strings.ToLower(host), strings.ToLower(suffix)) {
return strings.TrimSuffix(host, suffix)
}
return host
}
func int64FromOptional(value types.Int64) int64 {
if value.IsNull() || value.IsUnknown() {
return 0
}
return value.ValueInt64()
}
func boolPointerFromOptional(value types.Bool) *bool {
if value.IsNull() || value.IsUnknown() {
return nil
}
v := value.ValueBool()
return &v
}
func stringFromOptional(value types.String) string {
if value.IsNull() || value.IsUnknown() {
return ""
}
return strings.TrimSpace(value.ValueString())
}
@@ -0,0 +1,154 @@
package provider
import (
"context"
"strings"
"testing"
"github.com/dynu/terraform-provider-dynu/internal/testutil/fakedynu"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestIntegrationResourceDNSRecordLifecycleAndImport(t *testing.T) {
ctx := context.Background()
fake := fakedynu.NewServer()
defer fake.Close()
r := NewDNSRecordResource().(*dnsRecordResource)
configureResource(t, r, fake.BaseURL())
var schemaResp resource.SchemaResponse
r.Schema(ctx, resource.SchemaRequest{}, &schemaResp)
createPlan := dnsRecordResourceModel{
Hostname: types.StringValue("api.a.example.com"),
RecordType: types.StringValue("TXT"),
Content: types.StringValue("created"),
TTL: types.Int64Value(60),
State: types.BoolValue(true),
Group: types.StringValue("test"),
Host: types.StringNull(),
NodeName: types.StringNull(),
}
plan := tfsdk.Plan{Schema: schemaResp.Schema}
if diags := plan.Set(ctx, &createPlan); diags.HasError() {
t.Fatalf("set plan diagnostics: %v", diags)
}
createResp := resource.CreateResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
r.Create(ctx, resource.CreateRequest{Plan: plan}, &createResp)
if createResp.Diagnostics.HasError() {
t.Fatalf("create diagnostics: %v", createResp.Diagnostics)
}
var state dnsRecordResourceModel
if diags := createResp.State.Get(ctx, &state); diags.HasError() {
t.Fatalf("state get diagnostics: %v", diags)
}
if !strings.HasPrefix(state.ID.ValueString(), "1001/") {
t.Fatalf("expected composite id, got %q", state.ID.ValueString())
}
if state.Content.ValueString() != "created" {
t.Fatalf("unexpected created content: %q", state.Content.ValueString())
}
updatePlan := state
updatePlan.Content = types.StringValue("updated")
updatePlan.TTL = types.Int64Value(600)
plan = tfsdk.Plan{Schema: schemaResp.Schema}
if diags := plan.Set(ctx, &updatePlan); diags.HasError() {
t.Fatalf("set update plan diagnostics: %v", diags)
}
updateResp := resource.UpdateResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
r.Update(ctx, resource.UpdateRequest{Plan: plan}, &updateResp)
if updateResp.Diagnostics.HasError() {
t.Fatalf("update diagnostics: %v", updateResp.Diagnostics)
}
if diags := updateResp.State.Get(ctx, &state); diags.HasError() {
t.Fatalf("updated state get diagnostics: %v", diags)
}
if state.Content.ValueString() != "updated" || state.TTL.ValueInt64() != 600 {
t.Fatalf("unexpected updated state: %#v", state)
}
importResp := resource.ImportStateResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
r.ImportState(ctx, resource.ImportStateRequest{ID: state.ID.ValueString()}, &importResp)
if importResp.Diagnostics.HasError() {
t.Fatalf("import diagnostics: %v", importResp.Diagnostics)
}
var importedID string
if diags := importResp.State.GetAttribute(ctx, path.Root("id"), &importedID); diags.HasError() {
t.Fatalf("imported id diagnostics: %v", diags)
}
if importedID != state.ID.ValueString() {
t.Fatalf("expected imported id %q, got %q", state.ID.ValueString(), importedID)
}
deleteResp := resource.DeleteResponse{}
r.Delete(ctx, resource.DeleteRequest{State: updateResp.State}, &deleteResp)
if deleteResp.Diagnostics.HasError() {
t.Fatalf("delete diagnostics: %v", deleteResp.Diagnostics)
}
}
func TestIntegrationResourceDNSRecordReadNotFoundRemovesState(t *testing.T) {
ctx := context.Background()
fake := fakedynu.NewServer()
defer fake.Close()
r := NewDNSRecordResource().(*dnsRecordResource)
configureResource(t, r, fake.BaseURL())
var schemaResp resource.SchemaResponse
r.Schema(ctx, resource.SchemaRequest{}, &schemaResp)
state := dnsRecordResourceModel{
ID: types.StringValue("1001/10"),
}
tfState := tfsdk.State{Schema: schemaResp.Schema}
if diags := tfState.Set(ctx, &state); diags.HasError() {
t.Fatalf("set state diagnostics: %v", diags)
}
fake.DeleteRecord(1001, 10)
readResp := resource.ReadResponse{State: tfState}
r.Read(ctx, resource.ReadRequest{State: tfState}, &readResp)
if readResp.Diagnostics.HasError() {
t.Fatalf("read diagnostics: %v", readResp.Diagnostics)
}
var after dnsRecordResourceModel
diags := readResp.State.Get(ctx, &after)
if !diags.HasError() {
t.Fatal("expected diagnostics because resource was removed from state")
}
}
func TestIntegrationResourceDNSRecordImportStateInvalidID(t *testing.T) {
ctx := context.Background()
r := NewDNSRecordResource().(*dnsRecordResource)
importResp := resource.ImportStateResponse{}
r.ImportState(ctx, resource.ImportStateRequest{ID: "bad-id"}, &importResp)
if !importResp.Diagnostics.HasError() {
t.Fatal("expected import diagnostics for malformed ID")
}
if !strings.Contains(importResp.Diagnostics[0].Detail(), "domain_id/record_id") {
t.Fatalf("unexpected diagnostic detail: %s", importResp.Diagnostics[0].Detail())
}
}
func configureResource(t *testing.T, r resource.ResourceWithConfigure, baseURL string) {
t.Helper()
resp := resource.ConfigureResponse{}
r.Configure(context.Background(), resource.ConfigureRequest{
ProviderData: &providerData{client: newDynuClient("dummy-local-key", types.StringValue(baseURL))},
}, &resp)
if resp.Diagnostics.HasError() {
t.Fatalf("configure diagnostics: %v", resp.Diagnostics)
}
}
@@ -0,0 +1,19 @@
package provider
import "testing"
func TestParseDNSRecordID(t *testing.T) {
domainID, recordID, err := parseDNSRecordID("1001/55")
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
if domainID != 1001 || recordID != 55 {
t.Fatalf("unexpected ids: domain=%d record=%d", domainID, recordID)
}
}
func TestParseDNSRecordIDInvalid(t *testing.T) {
if _, _, err := parseDNSRecordID("1001"); err == nil {
t.Fatal("expected parse error")
}
}