Validate domain resource and extend DNS record typed fields

This commit is contained in:
beatz174-bit committed 2026-05-04 00:48:54 +10:00
1 parent 6badcf35f4
commit e59ad5a65b
9 files changed
+599 -20

No files matched your search

+1
View File
@@ -98,6 +98,7 @@ func (p *dynuProvider) DataSources(_ context.Context) []func() datasource.DataSo
func (p *dynuProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewDomainResource,
NewDNSRecordResource,
}
}
+64 -2
View File
@@ -43,6 +43,12 @@ type dnsRecordResourceModel struct {
Enabled types.Bool `tfsdk:"enabled"`
Group types.String `tfsdk:"group"`
Host types.String `tfsdk:"host"`
Priority types.Int64 `tfsdk:"priority"`
Weight types.Int64 `tfsdk:"weight"`
Port types.Int64 `tfsdk:"port"`
Flags types.Int64 `tfsdk:"flags"`
Tag types.String `tfsdk:"tag"`
Value types.String `tfsdk:"value"`
NodeName types.String `tfsdk:"node_name"`
DomainID types.Int64 `tfsdk:"domain_id"`
DomainName types.String `tfsdk:"domain_name"`
@@ -82,6 +88,12 @@ func (r *dnsRecordResource) Schema(_ context.Context, _ resource.SchemaRequest,
"enabled": schema.BoolAttribute{Optional: true, Computed: true, Default: booldefault.StaticBool(true), Description: "Whether this DNS record is enabled/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."},
"priority": schema.Int64Attribute{Optional: true, Computed: true, Description: "Priority value used by MX/SRV records."},
"weight": schema.Int64Attribute{Optional: true, Computed: true, Description: "Weight value used by SRV records."},
"port": schema.Int64Attribute{Optional: true, Computed: true, Description: "Port value used by SRV records."},
"flags": schema.Int64Attribute{Optional: true, Computed: true, Description: "Flags value used by CAA records."},
"tag": schema.StringAttribute{Optional: true, Computed: true, Description: "Tag value used by CAA records."},
"value": schema.StringAttribute{Optional: true, Computed: true, Description: "Value field used by CAA records."},
"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."},
@@ -149,6 +161,12 @@ func (r *dnsRecordResource) Create(ctx context.Context, req resource.CreateReque
State: boolPointerFromOptional(plan.Enabled),
Group: stringFromOptional(plan.Group),
Host: stringFromOptional(plan.Host),
Priority: int64FromOptional(plan.Priority),
Weight: int64FromOptional(plan.Weight),
Port: int64FromOptional(plan.Port),
Flags: int64FromOptional(plan.Flags),
Tag: stringFromOptional(plan.Tag),
Value: stringFromOptional(plan.Value),
}
createReq = normalizeDNSRecordCreateRequestForType(createReq)
if !validateDNSRecordContentForType(createReq.RecordType, createReq.Content, dynamicIntent, &resp.Diagnostics) {
@@ -249,6 +267,12 @@ func (r *dnsRecordResource) Update(ctx context.Context, req resource.UpdateReque
State: boolPointerFromOptional(preferKnownBool(plan.Enabled, state.Enabled)),
Group: stringFromOptional(preferKnownString(plan.Group, state.Group)),
Host: stringFromOptional(preferKnownString(plan.Host, state.Host)),
Priority: int64FromOptional(preferKnownInt64(plan.Priority, state.Priority)),
Weight: int64FromOptional(preferKnownInt64(plan.Weight, state.Weight)),
Port: int64FromOptional(preferKnownInt64(plan.Port, state.Port)),
Flags: int64FromOptional(preferKnownInt64(plan.Flags, state.Flags)),
Tag: stringFromOptional(preferKnownString(plan.Tag, state.Tag)),
Value: stringFromOptional(preferKnownString(plan.Value, state.Value)),
}
updateReq = normalizeDNSRecordUpdateRequestForType(updateReq)
if !validateDNSRecordContentForType(updateReq.RecordType, updateReq.Content, dynamicIntent, &resp.Diagnostics) {
@@ -268,6 +292,12 @@ func (r *dnsRecordResource) Update(ctx context.Context, req resource.UpdateReque
State: updateReq.State,
Group: updateReq.Group,
Host: updateReq.Host,
Priority: updateReq.Priority,
Weight: updateReq.Weight,
Port: updateReq.Port,
Flags: updateReq.Flags,
Tag: updateReq.Tag,
Value: updateReq.Value,
}, &resp.Diagnostics); retryOK {
updateReq.Content = retryReq.Content
updateReq.Group = retryReq.Group
@@ -337,6 +367,12 @@ func mapDNSRecordToState(record dynuclient.DNSRecord, dynamicIntent bool) dnsRec
Enabled: types.BoolValue(record.State),
Group: mapString(record.Group),
Host: mapString(record.Host),
Priority: types.Int64Value(record.Priority),
Weight: types.Int64Value(record.Weight),
Port: types.Int64Value(record.Port),
Flags: types.Int64Value(record.Flags),
Tag: mapString(record.Tag),
Value: mapString(record.Value),
NodeName: mapString(record.NodeName),
DomainID: types.Int64Value(record.DomainID),
DomainName: mapString(record.DomainName),
@@ -455,19 +491,45 @@ func stringPointer(value string) *string {
}
func normalizeDNSRecordCreateRequestForType(req dynuclient.CreateDNSRecordRequest) dynuclient.CreateDNSRecordRequest {
if strings.EqualFold(strings.TrimSpace(req.RecordType), "CNAME") {
switch strings.ToUpper(strings.TrimSpace(req.RecordType)) {
case "CNAME", "NS", "PTR":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil {
req.Host = *normalizedContent
}
case "MX":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil {
req.Host = *normalizedContent
}
case "SRV":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil {
req.Host = *normalizedContent
}
case "CAA":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil && req.Value == "" {
req.Value = *normalizedContent
}
}
return req
}
func normalizeDNSRecordUpdateRequestForType(req dynuclient.UpdateDNSRecordRequest) dynuclient.UpdateDNSRecordRequest {
if strings.EqualFold(strings.TrimSpace(req.RecordType), "CNAME") {
switch strings.ToUpper(strings.TrimSpace(req.RecordType)) {
case "CNAME", "NS", "PTR":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil {
req.Host = *normalizedContent
}
case "MX":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil {
req.Host = *normalizedContent
}
case "SRV":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil {
req.Host = *normalizedContent
}
case "CAA":
if normalizedContent := normalizeOptionalContentString(req.Content); normalizedContent != nil && req.Value == "" {
req.Value = *normalizedContent
}
}
return req
}
+142
View File
@@ -0,0 +1,142 @@
package provider
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/dynu/terraform-provider-dynu/internal/dynuclient"
)
var (
_ resource.Resource = &domainResource{}
_ resource.ResourceWithConfigure = &domainResource{}
_ resource.ResourceWithImportState = &domainResource{}
)
type domainResource struct{ clientProvider *providerData }
type domainResourceModel struct {
ID types.Int64 `tfsdk:"id"`
Name types.String `tfsdk:"name"`
IPv4Address types.String `tfsdk:"ipv4_address"`
IPv6Address types.String `tfsdk:"ipv6_address"`
TTL types.Int64 `tfsdk:"ttl"`
Group types.String `tfsdk:"group"`
State types.String `tfsdk:"state"`
Token types.String `tfsdk:"token"`
}
func NewDomainResource() resource.Resource { return &domainResource{} }
func (r *domainResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_domain"
}
func (r *domainResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{Description: "Manages a Dynu DNS domain.", Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{Computed: true},
"name": schema.StringAttribute{Required: true, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
"ipv4_address": schema.StringAttribute{Optional: true, Computed: true},
"ipv6_address": schema.StringAttribute{Optional: true, Computed: true},
"ttl": schema.Int64Attribute{Optional: true, Computed: true},
"group": schema.StringAttribute{Optional: true, Computed: true},
"state": schema.StringAttribute{Computed: true},
"token": schema.StringAttribute{Computed: true, Sensitive: true},
}}
}
func (r *domainResource) 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 *domainResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan domainResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
domain, err := r.clientProvider.client.CreateDomain(ctx, dynuclient.CreateDomainRequest{Name: plan.Name.ValueString(), IPv4Address: stringFromOptional(plan.IPv4Address), IPv6Address: stringFromOptional(plan.IPv6Address), TTL: int64FromOptional(plan.TTL), Group: stringFromOptional(plan.Group)})
if err != nil {
resp.Diagnostics.AddError(diagnosticSummary("Unable to create Dynu domain", err), err.Error())
return
}
state := mapDomainResource(*domain)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *domainResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state domainResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
domain, err := r.clientProvider.client.GetDomainByID(ctx, state.ID.ValueInt64())
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 domain", err), err.Error())
return
}
next := mapDomainResource(*domain)
resp.Diagnostics.Append(resp.State.Set(ctx, &next)...)
}
func (r *domainResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan domainResourceModel
var state domainResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
domain, err := r.clientProvider.client.UpdateDomain(ctx, state.ID.ValueInt64(), dynuclient.UpdateDomainRequest{Name: plan.Name.ValueString(), IPv4Address: stringFromOptional(plan.IPv4Address), IPv6Address: stringFromOptional(plan.IPv6Address), TTL: int64FromOptional(plan.TTL), Group: stringFromOptional(plan.Group)})
if err != nil {
resp.Diagnostics.AddError(diagnosticSummary("Unable to update Dynu domain", err), err.Error())
return
}
next := mapDomainResource(*domain)
resp.Diagnostics.Append(resp.State.Set(ctx, &next)...)
}
func (r *domainResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state domainResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
err := r.clientProvider.client.DeleteDomain(ctx, state.ID.ValueInt64())
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 domain", err), err.Error())
}
func (r *domainResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
id, err := strconv.ParseInt(strings.TrimSpace(req.ID), 10, 64)
if err != nil {
resp.Diagnostics.AddError("Invalid domain import ID", "Use the Dynu numeric domain ID.")
return
}
state := domainResourceModel{ID: types.Int64Value(id)}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func mapDomainResource(domain dynuclient.Domain) domainResourceModel {
return domainResourceModel{ID: types.Int64Value(domain.ID), Name: types.StringValue(strings.TrimSpace(domain.Name)), IPv4Address: mapString(domain.IPv4Address), IPv6Address: mapString(domain.IPv6Address), TTL: types.Int64Value(domain.TTL), Group: mapString(domain.Group), State: mapString(domain.State), Token: mapString(domain.Token)}
}
@@ -0,0 +1,57 @@
package provider
import (
"context"
"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 TestIntegrationResourceDomainLifecycleAndImport(t *testing.T) {
ctx := context.Background()
fake := fakedynu.NewServer()
defer fake.Close()
r := NewDomainResource().(*domainResource)
configureResource(t, r, fake.BaseURL())
var schemaResp resource.SchemaResponse
r.Schema(ctx, resource.SchemaRequest{}, &schemaResp)
planModel := domainResourceModel{Name: types.StringValue("new.example.com"), TTL: types.Int64Value(120), IPv4Address: types.StringValue("203.0.113.7")}
plan := tfsdk.Plan{Schema: schemaResp.Schema}
_ = plan.Set(ctx, &planModel)
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 domainResourceModel
_ = createResp.State.Get(ctx, &state)
if state.ID.ValueInt64() == 0 {
t.Fatal("expected created id")
}
state.TTL = types.Int64Value(300)
plan = tfsdk.Plan{Schema: schemaResp.Schema}
_ = plan.Set(ctx, &state)
updateResp := resource.UpdateResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
r.Update(ctx, resource.UpdateRequest{Plan: plan, State: createResp.State}, &updateResp)
if updateResp.Diagnostics.HasError() {
t.Fatalf("update diagnostics: %v", updateResp.Diagnostics)
}
importResp := resource.ImportStateResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
r.ImportState(ctx, resource.ImportStateRequest{ID: "5002"}, &importResp)
if importResp.Diagnostics.HasError() {
t.Fatalf("import diagnostics: %v", importResp.Diagnostics)
}
var imported int64
_ = importResp.State.GetAttribute(ctx, path.Root("id"), &imported)
if imported != 5002 {
t.Fatalf("unexpected imported id %d", imported)
}
}