Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório terraform-provider-mozoutmz, anteriormente
0
terraform-provider-mozoutmz/internal/provider/resource_domain.go
2026-11-28 15:28:10 +02:00

398 linhas
15 KiB
Go

package provider
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework/diag"
"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/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
"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/mozout-mz/terraform-provider-mozoutmz/internal/brand"
"github.com/mozout-mz/terraform-provider-mozoutmz/internal/client"
)
var (
_ resource.Resource = &domainResource{}
_ resource.ResourceWithConfigure = &domainResource{}
_ resource.ResourceWithImportState = &domainResource{}
)
// NewDomainResource returns the domain resource.
func NewDomainResource() resource.Resource { return &domainResource{} }
type domainResource struct{ c *client.Client }
type domainModel struct {
ID types.String `tfsdk:"id"`
Domain types.String `tfsdk:"domain"`
Years types.Int64 `tfsdk:"years"`
PromoCode types.String `tfsdk:"promo_code"`
Nameservers types.List `tfsdk:"nameservers"`
Locked types.Bool `tfsdk:"locked"`
AutoRenew types.Bool `tfsdk:"auto_renew"`
WaitMinutes types.Int64 `tfsdk:"wait_minutes"`
DomainID types.Int64 `tfsdk:"domain_id"`
Status types.String `tfsdk:"status"`
RegisteredAt types.String `tfsdk:"registered_at"`
ExpiresAt types.String `tfsdk:"expires_at"`
NextDueDate types.String `tfsdk:"next_due_date"`
RenewalAmount types.Float64 `tfsdk:"renewal_amount"`
Currency types.String `tfsdk:"currency"`
Premium types.Bool `tfsdk:"premium"`
DNSManagement types.Bool `tfsdk:"dns_management"`
Registered types.Bool `tfsdk:"registered_by_terraform"`
Simulated types.Bool `tfsdk:"simulated"`
}
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) {
keep := []planmodifier.String{stringplanmodifier.UseStateForUnknown()}
resp.Schema = schema.Schema{
MarkdownDescription: "A domain of your " + brand.Name + " account. If the domain is not in the account yet, it is registered " +
"with credit; if it already is, it is only managed (nothing is bought). Destroying only removes it from the state: " +
"domains are not deleted through the API. With a `sandbox_` key the registration is simulated.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "The domain name."},
"domain": schema.StringAttribute{
Required: true, MarkdownDescription: "Domain name, such as `example.co.mz`.",
PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()},
},
"years": schema.Int64Attribute{
Optional: true, Computed: true, Default: int64default.StaticInt64(1),
MarkdownDescription: "Years to register, from 1 to 10. Only used when registering; renewals are not made by Terraform.",
},
"promo_code": schema.StringAttribute{Optional: true, MarkdownDescription: "Promo code, only used when registering."},
"nameservers": schema.ListAttribute{
Optional: true, Computed: true, ElementType: types.StringType,
MarkdownDescription: "From 2 to 5 nameservers. When not set, they are only read.",
PlanModifiers: []planmodifier.List{listplanmodifier.UseStateForUnknown()},
},
"locked": schema.BoolAttribute{
Optional: true, Computed: true, MarkdownDescription: "Transfer lock. When not set, it is only read.",
PlanModifiers: []planmodifier.Bool{boolplanmodifier.UseStateForUnknown()},
},
"auto_renew": schema.BoolAttribute{
Optional: true, Computed: true, MarkdownDescription: "Whether renewal invoices are issued. When not set, it is only read.",
PlanModifiers: []planmodifier.Bool{boolplanmodifier.UseStateForUnknown()},
},
"wait_minutes": schema.Int64Attribute{
Optional: true, Computed: true, Default: int64default.StaticInt64(15),
MarkdownDescription: "How long to wait for a new registration to show in the account. Default 15.",
},
"domain_id": schema.Int64Attribute{Computed: true, PlanModifiers: []planmodifier.Int64{int64planmodifier.UseStateForUnknown()}, MarkdownDescription: "Numeric id of the domain."},
"status": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Status, such as `active` or `pending_registration`."},
"registered_at": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Registration date."},
"expires_at": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Expiry date."},
"next_due_date": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Next renewal invoice date."},
"renewal_amount": schema.Float64Attribute{Computed: true, MarkdownDescription: "Renewal price."},
"currency": schema.StringAttribute{Computed: true, PlanModifiers: keep, MarkdownDescription: "Currency of the prices."},
"premium": schema.BoolAttribute{Computed: true, PlanModifiers: []planmodifier.Bool{boolplanmodifier.UseStateForUnknown()}, MarkdownDescription: "Premium domain."},
"dns_management": schema.BoolAttribute{Computed: true, MarkdownDescription: "Whether DNS management is on (needed by the DNS record resource)."},
"registered_by_terraform": schema.BoolAttribute{Computed: true, PlanModifiers: []planmodifier.Bool{boolplanmodifier.UseStateForUnknown()}, MarkdownDescription: "True when Terraform registered the domain, false when it was already in the account."},
"simulated": schema.BoolAttribute{Computed: true, PlanModifiers: []planmodifier.Bool{boolplanmodifier.UseStateForUnknown()}, MarkdownDescription: "True when the registration was simulated (`sandbox_` key)."},
},
}
}
func (r *domainResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if c := clientFrom(req.ProviderData, &resp.Diagnostics); c != nil {
r.c = c
}
}
func (r *domainResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan domainModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
name := strings.ToLower(strings.TrimSpace(plan.Domain.ValueString()))
plan.ID = types.StringValue(name)
plan.Registered = types.BoolValue(false)
plan.Simulated = types.BoolValue(false)
d, err := r.c.Domain(ctx, name)
if err != nil && !client.IsNotFound(err) {
apiError(&resp.Diagnostics, "Could not read the domain", err)
return
}
if err != nil {
// Not in the account: register it.
body := map[string]interface{}{"domain": name, "years": plan.Years.ValueInt64()}
var ns []string
if !plan.Nameservers.IsNull() && !plan.Nameservers.IsUnknown() {
resp.Diagnostics.Append(plan.Nameservers.ElementsAs(ctx, &ns, false)...)
body["nameservers"] = ns
}
if !plan.Locked.IsNull() && !plan.Locked.IsUnknown() {
body["locked"] = plan.Locked.ValueBool()
}
if !plan.PromoCode.IsNull() && plan.PromoCode.ValueString() != "" {
body["promo_code"] = plan.PromoCode.ValueString()
}
reg, err := r.c.Register(ctx, body, client.NewIdempotencyKey())
if err != nil {
apiError(&resp.Diagnostics, "Could not register the domain", err)
return
}
plan.Registered = types.BoolValue(true)
if reg.Simulated {
plan.Simulated = types.BoolValue(true)
if plan.Locked.IsUnknown() {
plan.Locked = types.BoolValue(reg.Locked == nil || *reg.Locked)
}
fillUnknownDomain(&plan)
resp.Diagnostics.AddWarning("Simulated registration", "The API key is a sandbox_ key: the registration was simulated and the domain was not registered.")
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
return
}
d, err = r.waitDomain(ctx, name, time.Duration(plan.WaitMinutes.ValueInt64())*time.Minute)
if err != nil {
fillUnknownDomain(&plan)
resp.Diagnostics.AddWarning("Registration still in progress", err.Error()+" It stays in the state; run terraform apply again later.")
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
return
}
}
r.apply(ctx, &plan, d, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *domainResource) waitDomain(ctx context.Context, name string, timeout time.Duration) (*client.Domain, error) {
if timeout <= 0 {
timeout = 15 * time.Minute
}
deadline := time.Now().Add(timeout)
for {
d, err := r.c.Domain(ctx, name)
if err == nil {
return d, nil
}
if !client.IsNotFound(err) {
return nil, err
}
if time.Now().After(deadline) {
return nil, fmt.Errorf("%s is not in the account after %s", name, timeout)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(15 * time.Second):
}
}
}
// apply sends the nameservers, lock and auto-renew that differ, then fills the computed values.
func (r *domainResource) apply(ctx context.Context, plan *domainModel, d *client.Domain, diags *diag.Diagnostics) {
name := plan.ID.ValueString()
if !plan.Nameservers.IsNull() && !plan.Nameservers.IsUnknown() {
var want []string
diags.Append(plan.Nameservers.ElementsAs(ctx, &want, false)...)
have, err := r.c.Nameservers(ctx, name)
if err != nil {
apiError(diags, "Could not read the nameservers", err)
return
}
if !sameNames(want, have) {
if err := r.c.SetNameservers(ctx, name, want); err != nil {
apiError(diags, "Could not change the nameservers", err)
return
}
}
} else if ns, err := r.c.Nameservers(ctx, name); err == nil {
plan.Nameservers = listOfStrings(ns)
} else {
plan.Nameservers = types.ListNull(types.StringType)
}
if !plan.Locked.IsNull() && !plan.Locked.IsUnknown() {
have, err := r.c.Lock(ctx, name)
if err != nil || have != plan.Locked.ValueBool() {
if err := r.c.SetLock(ctx, name, plan.Locked.ValueBool()); err != nil {
apiError(diags, "Could not change the transfer lock", err)
return
}
}
} else if l, err := r.c.Lock(ctx, name); err == nil {
plan.Locked = types.BoolValue(l)
} else {
plan.Locked = types.BoolNull()
}
if !plan.AutoRenew.IsNull() && !plan.AutoRenew.IsUnknown() {
if plan.AutoRenew.ValueBool() != d.AutoRenew {
if err := r.c.SetAutoRenew(ctx, name, plan.AutoRenew.ValueBool()); err != nil {
apiError(diags, "Could not change the renewal setting", err)
return
}
}
} else {
plan.AutoRenew = types.BoolValue(d.AutoRenew)
}
fillDomain(plan, d)
}
func (r *domainResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var st domainModel
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
if resp.Diagnostics.HasError() {
return
}
if st.Simulated.ValueBool() {
return
}
name := st.ID.ValueString()
d, err := r.c.Domain(ctx, name)
if client.IsNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
if err != nil {
apiError(&resp.Diagnostics, "Could not read the domain", err)
return
}
if st.Domain.IsNull() {
st.Domain = types.StringValue(name)
}
if ns, err := r.c.Nameservers(ctx, name); err == nil {
if !st.Nameservers.IsNull() {
var old []string
resp.Diagnostics.Append(st.Nameservers.ElementsAs(ctx, &old, false)...)
if sameNames(old, ns) {
ns = old // keep the order and case of the configuration
}
}
st.Nameservers = listOfStrings(ns)
}
if l, err := r.c.Lock(ctx, name); err == nil {
st.Locked = types.BoolValue(l)
}
st.AutoRenew = types.BoolValue(d.AutoRenew)
if st.Years.IsNull() {
st.Years = types.Int64Value(1)
}
if st.WaitMinutes.IsNull() {
st.WaitMinutes = types.Int64Value(15)
}
if st.Registered.IsNull() {
st.Registered = types.BoolValue(false)
}
if st.Simulated.IsNull() {
st.Simulated = types.BoolValue(false)
}
fillDomain(&st, d)
resp.Diagnostics.Append(resp.State.Set(ctx, &st)...)
}
func (r *domainResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan, st domainModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
if resp.Diagnostics.HasError() {
return
}
plan.ID, plan.Registered, plan.Simulated = st.ID, st.Registered, st.Simulated
if st.Simulated.ValueBool() {
fillUnknownDomain(&plan)
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
return
}
d, err := r.c.Domain(ctx, plan.ID.ValueString())
if err != nil {
apiError(&resp.Diagnostics, "Could not read the domain", err)
return
}
r.apply(ctx, &plan, d, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
if fresh, err := r.c.Domain(ctx, plan.ID.ValueString()); err == nil {
fillDomain(&plan, fresh)
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *domainResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var st domainModel
resp.Diagnostics.Append(req.State.Get(ctx, &st)...)
if st.Simulated.ValueBool() {
return
}
resp.Diagnostics.AddWarning("Domain kept in the account", removedFromStateWarning)
}
func (r *domainResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
name := strings.ToLower(strings.TrimSpace(req.ID))
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), name)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("domain"), name)...)
}
func fillDomain(m *domainModel, d *client.Domain) {
m.DomainID = types.Int64Value(d.ID)
m.Status = types.StringValue(d.Status)
m.RegisteredAt = strOrNull(d.RegisteredAt)
m.ExpiresAt = strOrNull(d.ExpiresAt)
m.NextDueDate = strOrNull(d.NextDueDate)
m.RenewalAmount = types.Float64Value(d.RenewalAmount)
m.Currency = types.StringValue(d.Currency)
m.Premium = types.BoolValue(d.Premium)
m.DNSManagement = types.BoolValue(d.Features.DNSManagement)
}
func fillUnknownDomain(m *domainModel) {
for _, v := range []*types.String{&m.Status, &m.RegisteredAt, &m.ExpiresAt, &m.NextDueDate, &m.Currency} {
if v.IsUnknown() {
*v = types.StringNull()
}
}
for _, v := range []*types.Bool{&m.Locked, &m.AutoRenew, &m.Premium, &m.DNSManagement} {
if v.IsUnknown() {
*v = types.BoolNull()
}
}
if m.DomainID.IsUnknown() {
m.DomainID = types.Int64Null()
}
if m.RenewalAmount.IsUnknown() {
m.RenewalAmount = types.Float64Null()
}
if m.Nameservers.IsUnknown() {
m.Nameservers = types.ListNull(types.StringType)
}
}
// sameNames compares two lists of host names without order, case or final dot.
func sameNames(a, b []string) bool {
if len(a) != len(b) {
return false
}
seen := map[string]int{}
for _, s := range a {
seen[strings.TrimSuffix(strings.ToLower(s), ".")]++
}
for _, s := range b {
k := strings.TrimSuffix(strings.ToLower(s), ".")
if seen[k] == 0 {
return false
}
seen[k]--
}
return true
}