261 linhas
10 KiB
Go
261 linhas
10 KiB
Go
package provider
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"strings"
|
|
|
|
"github.com/hashicorp/terraform-plugin-framework/path"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
|
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
|
"github.com/hashicorp/terraform-plugin-framework/types"
|
|
|
|
"github.com/mozout-mz/terraform-provider-mozoutmz/internal/brand"
|
|
"github.com/mozout-mz/terraform-provider-mozoutmz/internal/client"
|
|
)
|
|
|
|
var (
|
|
_ resource.Resource = &dnsRecordResource{}
|
|
_ resource.ResourceWithConfigure = &dnsRecordResource{}
|
|
_ resource.ResourceWithImportState = &dnsRecordResource{}
|
|
)
|
|
|
|
// NewDNSRecordResource returns the DNS record resource.
|
|
func NewDNSRecordResource() resource.Resource { return &dnsRecordResource{} }
|
|
|
|
type dnsRecordResource struct{ c *client.Client }
|
|
|
|
type dnsRecordModel struct {
|
|
ID types.String `tfsdk:"id"`
|
|
Domain types.String `tfsdk:"domain"`
|
|
Name types.String `tfsdk:"name"`
|
|
Type types.String `tfsdk:"type"`
|
|
Value types.String `tfsdk:"value"`
|
|
TTL types.Int64 `tfsdk:"ttl"`
|
|
Priority types.Int64 `tfsdk:"priority"`
|
|
Simulated types.Bool `tfsdk:"simulated"`
|
|
}
|
|
|
|
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) {
|
|
replace := []planmodifier.String{stringplanmodifier.RequiresReplace()}
|
|
resp.Schema = schema.Schema{
|
|
MarkdownDescription: "One record of the DNS zone of a domain of your " + brand.Name + " account. The domain needs DNS management on. " +
|
|
"A copy of the zone is saved before each change. With a `sandbox_` key the changes are simulated.",
|
|
Attributes: map[string]schema.Attribute{
|
|
"id": schema.StringAttribute{
|
|
Computed: true, MarkdownDescription: "Record id. It changes when the name, value or priority change.",
|
|
},
|
|
"domain": schema.StringAttribute{Required: true, PlanModifiers: replace, MarkdownDescription: "Domain of the zone, such as `example.co.mz`."},
|
|
"name": schema.StringAttribute{Required: true, MarkdownDescription: "Name, such as `www`. Use `@` for the domain itself."},
|
|
"type": schema.StringAttribute{
|
|
Required: true, PlanModifiers: replace,
|
|
MarkdownDescription: "`A`, `AAAA`, `CNAME`, `MX`, `TXT`, `NS`, `SRV` or `CAA`.",
|
|
Validators: []validator.String{stringOneOf("A", "AAAA", "CNAME", "MX", "TXT", "NS", "SRV", "CAA")},
|
|
},
|
|
"value": schema.StringAttribute{Required: true, MarkdownDescription: "Value. SRV: `weight port target`. CAA: `tag value`."},
|
|
"ttl": schema.Int64Attribute{
|
|
Optional: true, Computed: true, Default: int64default.StaticInt64(14400),
|
|
MarkdownDescription: "TTL in seconds, from 60 to 604800. Default 14400.",
|
|
},
|
|
"priority": schema.Int64Attribute{
|
|
Optional: true, Computed: true, Default: int64default.StaticInt64(0),
|
|
MarkdownDescription: "Priority for MX and SRV; the flag for CAA. Default 0.",
|
|
},
|
|
"simulated": schema.BoolAttribute{Computed: true, MarkdownDescription: "True when the change was simulated (`sandbox_` key)."},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (r *dnsRecordResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
|
if c := clientFrom(req.ProviderData, &resp.Diagnostics); c != nil {
|
|
r.c = c
|
|
}
|
|
}
|
|
|
|
func input(m *dnsRecordModel) client.DNSRecordInput {
|
|
return client.DNSRecordInput{
|
|
Name: m.Name.ValueString(),
|
|
Type: strings.ToUpper(m.Type.ValueString()),
|
|
Value: m.Value.ValueString(),
|
|
TTL: m.TTL.ValueInt64(),
|
|
Priority: m.Priority.ValueInt64(),
|
|
}
|
|
}
|
|
|
|
func (r *dnsRecordResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
|
var plan dnsRecordModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
rec, err := r.c.CreateDNSRecord(ctx, plan.Domain.ValueString(), input(&plan))
|
|
if err != nil {
|
|
apiError(&resp.Diagnostics, "Could not create the DNS record", err)
|
|
return
|
|
}
|
|
plan.ID = types.StringValue(rec.ID)
|
|
plan.Simulated = types.BoolValue(rec.Simulated)
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
|
}
|
|
|
|
func (r *dnsRecordResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
|
var st dnsRecordModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
recs, err := r.c.DNSRecords(ctx, st.Domain.ValueString())
|
|
if client.IsNotFound(err) {
|
|
resp.State.RemoveResource(ctx)
|
|
return
|
|
}
|
|
if err != nil {
|
|
apiError(&resp.Diagnostics, "Could not read the DNS zone", err)
|
|
return
|
|
}
|
|
found := findRecord(recs, &st)
|
|
if found == nil {
|
|
if st.Simulated.ValueBool() {
|
|
return // simulated record: it never reached the zone
|
|
}
|
|
resp.State.RemoveResource(ctx)
|
|
return
|
|
}
|
|
st.ID = types.StringValue(found.ID)
|
|
if !sameRecordName(st.Name.ValueString(), found.Name, st.Domain.ValueString()) {
|
|
st.Name = types.StringValue(found.Name)
|
|
}
|
|
if st.Type.IsNull() || !strings.EqualFold(st.Type.ValueString(), found.Type) {
|
|
st.Type = types.StringValue(found.Type)
|
|
}
|
|
if !sameRecordValue(found.Type, st.Value.ValueString(), found.Value) {
|
|
st.Value = types.StringValue(found.Value)
|
|
}
|
|
st.TTL = types.Int64Value(found.TTL)
|
|
st.Priority = types.Int64Value(found.Priority)
|
|
st.Simulated = types.BoolValue(false)
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &st)...)
|
|
}
|
|
|
|
func (r *dnsRecordResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
|
var plan, st dnsRecordModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if st.Simulated.ValueBool() {
|
|
// Sandbox placeholder: the record never reached the zone, so there is nothing to change.
|
|
plan.ID, plan.Simulated = st.ID, st.Simulated
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
|
return
|
|
}
|
|
rec, err := r.c.UpdateDNSRecord(ctx, st.Domain.ValueString(), st.ID.ValueString(), input(&plan))
|
|
if err != nil {
|
|
apiError(&resp.Diagnostics, "Could not change the DNS record", err)
|
|
return
|
|
}
|
|
plan.ID = types.StringValue(rec.ID)
|
|
plan.Simulated = types.BoolValue(rec.Simulated)
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
|
}
|
|
|
|
func (r *dnsRecordResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
|
var st dnsRecordModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if st.Simulated.ValueBool() {
|
|
return // sandbox placeholder: nothing to delete
|
|
}
|
|
if err := r.c.DeleteDNSRecord(ctx, st.Domain.ValueString(), st.ID.ValueString()); err != nil {
|
|
apiError(&resp.Diagnostics, "Could not delete the DNS record", err)
|
|
}
|
|
}
|
|
|
|
// ImportState takes "domain/record_id", such as "example.co.mz/a1b2c3d4e5f60718".
|
|
func (r *dnsRecordResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
|
parts := strings.SplitN(req.ID, "/", 2)
|
|
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
|
resp.Diagnostics.AddError("Invalid import id", "Use domain/record_id, such as example.co.mz/a1b2c3d4e5f60718.")
|
|
return
|
|
}
|
|
recs, err := r.c.DNSRecords(ctx, parts[0])
|
|
if err != nil {
|
|
apiError(&resp.Diagnostics, "Could not read the DNS zone", err)
|
|
return
|
|
}
|
|
for _, rec := range recs {
|
|
if rec.ID == parts[1] {
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), rec.ID)...)
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("domain"), strings.ToLower(parts[0]))...)
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), rec.Name)...)
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("type"), rec.Type)...)
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("value"), rec.Value)...)
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("ttl"), rec.TTL)...)
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("priority"), rec.Priority)...)
|
|
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("simulated"), false)...)
|
|
return
|
|
}
|
|
}
|
|
resp.Diagnostics.AddError("Record not found", "There is no record "+parts[1]+" in the zone of "+parts[0]+".")
|
|
}
|
|
|
|
// findRecord finds the record by id, or, when the id changed outside Terraform, by name, type, value and priority.
|
|
func findRecord(recs []client.DNSRecord, st *dnsRecordModel) *client.DNSRecord {
|
|
for i := range recs {
|
|
if recs[i].ID == st.ID.ValueString() {
|
|
return &recs[i]
|
|
}
|
|
}
|
|
for i := range recs {
|
|
r := &recs[i]
|
|
if r.ReadOnly || !strings.EqualFold(r.Type, st.Type.ValueString()) {
|
|
continue
|
|
}
|
|
if sameRecordName(st.Name.ValueString(), r.Name, st.Domain.ValueString()) &&
|
|
sameRecordValue(r.Type, st.Value.ValueString(), r.Value) && r.Priority == st.Priority.ValueInt64() {
|
|
return r
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// sameRecordName compares "www", "www.example.co.mz" and "www.example.co.mz." as the same name, and "@" with the domain.
|
|
func sameRecordName(a, b, domain string) bool {
|
|
norm := func(s string) string {
|
|
s = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
|
|
d := strings.ToLower(domain)
|
|
if s == "" || s == d {
|
|
return "@"
|
|
}
|
|
return strings.TrimSuffix(s, "."+d)
|
|
}
|
|
return norm(a) == norm(b)
|
|
}
|
|
|
|
// sameRecordValue ignores what the API normalizes: quotes around TXT, final dots, case of host names and IPv6 forms.
|
|
func sameRecordValue(typ, a, b string) bool {
|
|
if a == b {
|
|
return true
|
|
}
|
|
switch strings.ToUpper(typ) {
|
|
case "TXT":
|
|
return strings.Trim(a, "\"") == strings.Trim(b, "\"")
|
|
case "AAAA", "A":
|
|
ia, ib := net.ParseIP(a), net.ParseIP(b)
|
|
return ia != nil && ib != nil && ia.Equal(ib)
|
|
case "CNAME", "NS", "MX":
|
|
return strings.TrimSuffix(strings.ToLower(a), ".") == strings.TrimSuffix(strings.ToLower(b), ".")
|
|
}
|
|
return strings.EqualFold(strings.TrimSpace(a), strings.TrimSpace(b))
|
|
}
|