Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce apstra_datacenter_routing_zone_loopback_addresses resource #1037

Merged
merged 5 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions apstra/blueprint/routing_zone_loopback.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package blueprint

import (
"github.com/hashicorp/terraform-plugin-framework-nettypes/cidrtypes"
"github.com/hashicorp/terraform-plugin-framework/attr"
resourceSchema "github.com/hashicorp/terraform-plugin-framework/resource/schema"
)

type RoutingZoneLoopback struct {
Ipv4Addr cidrtypes.IPv4Prefix `tfsdk:"ipv4_addr"`
Ipv6Addr cidrtypes.IPv6Prefix `tfsdk:"ipv6_addr"`
}

func (o RoutingZoneLoopback) AttrTypes() map[string]attr.Type {
return map[string]attr.Type{
"ipv4_addr": cidrtypes.IPv4PrefixType{},
"ipv6_addr": cidrtypes.IPv6PrefixType{},
}
}

func (o RoutingZoneLoopback) ResourceAttributes() map[string]resourceSchema.Attribute {
return map[string]resourceSchema.Attribute{
"ipv4_addr": resourceSchema.StringAttribute{
CustomType: cidrtypes.IPv4PrefixType{},
MarkdownDescription: "The IPv4 address to be assigned within the Routing Zone, in CIDR notation.",
Optional: true,
},
"ipv6_addr": resourceSchema.StringAttribute{
CustomType: cidrtypes.IPv6PrefixType{},
MarkdownDescription: "The IPv6 address to be assigned within the Routing Zone, in CIDR notation.",
Optional: true,
},
}
}
189 changes: 189 additions & 0 deletions apstra/blueprint/routing_zone_loopbacks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package blueprint

import (
"context"
"fmt"
"net/netip"

"github.com/Juniper/apstra-go-sdk/apstra"
"github.com/Juniper/terraform-provider-apstra/apstra/private"
"github.com/Juniper/terraform-provider-apstra/apstra/utils"
"github.com/hashicorp/terraform-plugin-framework-nettypes/cidrtypes"
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/diag"
resourceSchema "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/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
)

type RoutingZoneLoopbacks struct {
BlueprintId types.String `tfsdk:"blueprint_id"`
RoutingZoneId types.String `tfsdk:"routing_zone_id"`
Loopbacks types.Map `tfsdk:"loopbacks"`
}

func (o RoutingZoneLoopbacks) ResourceAttributes() map[string]resourceSchema.Attribute {
return map[string]resourceSchema.Attribute{
"blueprint_id": resourceSchema.StringAttribute{
MarkdownDescription: "Apstra Blueprint ID.",
Required: true,
Validators: []validator.String{stringvalidator.LengthAtLeast(1)},
PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()},
},
"routing_zone_id": resourceSchema.StringAttribute{
MarkdownDescription: "Routing Zone ID.",
Required: true,
Validators: []validator.String{stringvalidator.LengthAtLeast(1)},
PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()},
},
"loopbacks": resourceSchema.MapNestedAttribute{
MarkdownDescription: "Map of Loopback IPv4 and IPv6 addresses, keyed by System (switch) Node ID.",
Required: true,
NestedObject: resourceSchema.NestedAttributeObject{
Attributes: RoutingZoneLoopback{}.ResourceAttributes(),
},
Validators: []validator.Map{mapvalidator.SizeAtLeast(1)},
},
}
}

func (o RoutingZoneLoopbacks) Request(ctx context.Context, bp *apstra.TwoStageL3ClosClient, previousLoopbackMap private.ResourceDatacenterRoutingZoneLoopbackAddresses, diags *diag.Diagnostics) (map[apstra.ObjectId]apstra.SecurityZoneLoopback, *private.ResourceDatacenterRoutingZoneLoopbackAddresses) {
// API response will allow us to determine interface IDs from system IDs
szInfo, err := bp.GetSecurityZoneInfo(ctx, apstra.ObjectId(o.RoutingZoneId.ValueString()))
if err != nil {
diags.AddError("failed querying for security zone", err.Error())
return nil, nil
}

// convert API response to map (switchId -> loopbackId) for easy lookups
nodeIdToIfId := make(map[string]apstra.ObjectId)
for _, memberInterface := range szInfo.MemberInterfaces {
for _, loopback := range memberInterface.Loopbacks {
nodeIdToIfId[memberInterface.HostingSystem.Id.String()] = loopback.Id
}
}

// extract the planned loopbacks
var planLoopbackMap map[string]RoutingZoneLoopback
diags.Append(o.Loopbacks.ElementsAs(ctx, &planLoopbackMap, false)...)
if diags.HasError() {
return nil, nil
}

// we return these two maps
resultMap := make(map[apstra.ObjectId]apstra.SecurityZoneLoopback, len(planLoopbackMap))
resultPrivate := make(private.ResourceDatacenterRoutingZoneLoopbackAddresses, len(planLoopbackMap))

for sysId, loopback := range planLoopbackMap {
// ensure the specified system ID exists in the RZ-specific map we got from the API
loopbackId, ok := nodeIdToIfId[sysId]
if !ok {
diags.AddError(
"System not participating in Routing Zone",
fmt.Sprintf("System %s not participating in routing zone %s", sysId, o.RoutingZoneId),
)
return nil, nil
}

var szl apstra.SecurityZoneLoopback // this will be a resultMap entry
var p struct { // this will be a resultPrivate entry
HasIpv4 bool `json:"has_ipv4"`
HasIpv6 bool `json:"has_ipv6"`
}

if !loopback.Ipv4Addr.IsNull() {
szl.IPv4Addr = utils.ToPtr(netip.MustParsePrefix(loopback.Ipv4Addr.ValueString()))
p.HasIpv4 = true
} else {
if previousLoopbackMap[sysId].HasIpv4 {
szl.IPv4Addr = new(netip.Prefix) // signals to remove previous value
}
}

if !loopback.Ipv6Addr.IsNull() {
szl.IPv6Addr = utils.ToPtr(netip.MustParsePrefix(loopback.Ipv6Addr.ValueString()))
p.HasIpv6 = true
} else {
if previousLoopbackMap[sysId].HasIpv6 {
szl.IPv6Addr = new(netip.Prefix) // signals to remove previous value
}
}

// previous addresses (if any) are no longer of any interest
delete(previousLoopbackMap, sysId)

resultPrivate[sysId] = p
resultMap[loopbackId] = szl
}

// loop over remaining previous IP assignments; clear them as necessary
for sysId, previous := range previousLoopbackMap {
ifId, ok := nodeIdToIfId[sysId]
if !ok {
continue // system no longer exists
}

var szl apstra.SecurityZoneLoopback
if previous.HasIpv4 {
szl.IPv4Addr = new(netip.Prefix) // bogus prefix clears entry from API
}
if previous.HasIpv6 {
szl.IPv6Addr = new(netip.Prefix) // bogus prefix clears entry from API
}
resultMap[ifId] = szl
}

return resultMap, &resultPrivate
}

func (o *RoutingZoneLoopbacks) LoadApiData(ctx context.Context, info *apstra.TwoStageL3ClosSecurityZoneInfo, ps private.State, diags *diag.Diagnostics) {
// extract private state (previously configured loopbacks)
var previousLoopbackMap private.ResourceDatacenterRoutingZoneLoopbackAddresses
if ps != nil {
previousLoopbackMap.LoadPrivateState(ctx, ps, diags)
if diags.HasError() {
return
}
}

loopbacks := make(map[string]RoutingZoneLoopback, len(previousLoopbackMap))
for _, memberInterface := range info.MemberInterfaces {
switch len(memberInterface.Loopbacks) {
case 0: // weird, but whatever
continue
case 1: // expected case handled below
default: // error condition
diags.AddError(
"invalid API response",
fmt.Sprintf("System %q has %d loopback interfaces in Routing Zone %s, expected 0 or 1",
memberInterface.HostingSystem.Id, len(memberInterface.Loopbacks), o.RoutingZoneId),
)
return
}

previous, ok := previousLoopbackMap[memberInterface.HostingSystem.Id.String()]
if !ok {
continue
}

var ipv4Addr cidrtypes.IPv4Prefix
if memberInterface.Loopbacks[0].Ipv4Addr != nil && previous.HasIpv4 {
ipv4Addr = cidrtypes.NewIPv4PrefixValue(memberInterface.Loopbacks[0].Ipv4Addr.String())
}

var ipv6Addr cidrtypes.IPv6Prefix
if memberInterface.Loopbacks[0].Ipv6Addr != nil && previous.HasIpv6 {
ipv6Addr = cidrtypes.NewIPv6PrefixValue(memberInterface.Loopbacks[0].Ipv6Addr.String())
}

loopbacks[memberInterface.HostingSystem.Id.String()] = RoutingZoneLoopback{
Ipv4Addr: ipv4Addr,
Ipv6Addr: ipv6Addr,
}
}

o.Loopbacks = utils.MapValueOrNull(ctx, types.ObjectType{AttrTypes: RoutingZoneLoopback{}.AttrTypes()}, loopbacks, diags)
}
1 change: 1 addition & 0 deletions apstra/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ var (
ResourceDatacenterIpLinkAddressing = resourceDatacenterIpLinkAddressing{}
ResourceDatacenterRoutingZone = resourceDatacenterRoutingZone{}
ResourceDatacenterRoutingZoneConstraint = resourceDatacenterRoutingZoneConstraint{}
ResourceDatacenterRoutingZoneLoopbackAddresses = resourceDatacenterRoutingZoneLoopbackAddresses{}
ResourceDatacenterVirtualNetwork = resourceDatacenterVirtualNetwork{}
ResourceFreeformAllocGroup = resourceFreeformAllocGroup{}
ResourceFreeformBlueprint = resourceFreeformBlueprint{}
Expand Down
46 changes: 46 additions & 0 deletions apstra/private/resource_routing_zone_loopback_addresses.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package private

import (
"context"
"encoding/json"
"fmt"

"github.com/hashicorp/terraform-plugin-framework/diag"
)

// ResourceDatacenterRoutingZoneLoopbackAddresses is stored in private state by
// resourceDatacenterRoutingZoneLoopbackAddresses methods Create() and Update().
// It contains a record of switch node IDs which previously had IPv4 and IPv6
// loopback addresses configured.
// This record is consulted in the following methods:
// - Read() - we don't read all loopbacks, only ones previously configured.
// - Update() - previous assignments which do not appear in the plan are cleared.
// - Delete() - all previous assignments are cleared.
type ResourceDatacenterRoutingZoneLoopbackAddresses map[string]struct {
HasIpv4 bool `json:"has_ipv4"`
HasIpv6 bool `json:"has_ipv6"`
}

func (o *ResourceDatacenterRoutingZoneLoopbackAddresses) LoadPrivateState(ctx context.Context, ps State, diags *diag.Diagnostics) {
b, d := ps.GetKey(ctx, fmt.Sprintf("%T", *o))
diags.Append(d...)
if diags.HasError() {
return
}

err := json.Unmarshal(b, &o)
if err != nil {
diags.AddError("failed to unmarshal private state", err.Error())
return
}
}

func (o *ResourceDatacenterRoutingZoneLoopbackAddresses) SetPrivateState(ctx context.Context, ps State, diags *diag.Diagnostics) {
b, err := json.Marshal(o)
if err != nil {
diags.AddError("failed to marshal private state", err.Error())
return
}

diags.Append(ps.SetKey(ctx, fmt.Sprintf("%T", *o), b)...)
}
1 change: 1 addition & 0 deletions apstra/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,7 @@ func (p *Provider) Resources(_ context.Context) []func() resource.Resource {
func() resource.Resource { return &resourceDatacenterRack{} },
func() resource.Resource { return &resourceDatacenterRoutingZone{} },
func() resource.Resource { return &resourceDatacenterRoutingZoneConstraint{} },
func() resource.Resource { return &resourceDatacenterRoutingZoneLoopbackAddresses{} },
func() resource.Resource { return &resourceDatacenterRoutingPolicy{} },
func() resource.Resource { return &resourceDatacenterSecurityPolicy{} },
func() resource.Resource { return &resourceDatacenterIpLinkAddressing{} },
Expand Down
Loading
Loading