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

Add data_source_netbox_interfaces #9

Merged
merged 2 commits into from
Nov 20, 2020
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
240 changes: 240 additions & 0 deletions netbox/data_source_netbox_interfaces.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
package netbox

import (
"errors"
"fmt"
"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/virtualization"
"github.com/fbreckle/go-netbox/netbox/models"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"regexp"
)

func dataSourceNetboxInterfaces() *schema.Resource {
return &schema.Resource{
Read: dataSourceNetboxInterfaceRead,
Schema: map[string]*schema.Schema{
"filter": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"name_regex": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringIsValidRegExp,
},
"interfaces": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
},
"mac_address": {
Type: schema.TypeString,
Computed: true,
},
"mode": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
"mtu": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"tag_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
},
"tagged_vlans": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"vid": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
// Do as a TypeList due to limitation of TypeMap
"untagged_vlan": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Computed: true,
},
"vid": {
Type: schema.TypeInt,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"vm_id": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}

func dataSourceNetboxInterfaceRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)

params := virtualization.NewVirtualizationInterfacesListParams()

if filter, ok := d.GetOk("filter"); ok {
var filterParams = filter.(*schema.Set)
for _, f := range filterParams.List() {
k := f.(map[string]interface{})["name"]
v := f.(map[string]interface{})["value"]
vString := v.(string)
switch k {
case "cluster_id":
params.ClusterID = &vString
case "mac_address":
params.MacAddress = &vString
case "name":
params.Name = &vString
case "tag":
params.Tag = &vString
case "vm_id":
params.VirtualMachineID = &vString
default:
return fmt.Errorf("'%s' is not a supported filter parameter", k)
}
}
}

res, err := api.Virtualization.VirtualizationInterfacesList(params, nil)
if err != nil {
return err
}

if *res.GetPayload().Count == int64(0) {
return errors.New("no result")
}

var filteredInterfaces []*models.VMInterface
if nameRegex, ok := d.GetOk("name_regex"); ok {
r := regexp.MustCompile(nameRegex.(string))
for _, vmInterface := range res.GetPayload().Results {
if r.MatchString(*vmInterface.Name) {
filteredInterfaces = append(filteredInterfaces, vmInterface)
}
}
} else {
filteredInterfaces = res.GetPayload().Results
}

var s []map[string]interface{}
for _, v := range filteredInterfaces {
var mapping = make(map[string]interface{})
if v.Description != "" {
mapping["description"] = v.Description
}
mapping["enabled"] = v.Enabled
if v.MacAddress != nil {
mapping["mac_address"] = *v.MacAddress
}
if v.Mode != nil {
mapping["mode"] = map[string]string{
"label": *v.Mode.Label,
"value": *v.Mode.Value,
}
}
if v.Mtu != nil {
mapping["mtu"] = *v.Mtu
}
if v.Name != nil {
mapping["name"] = *v.Name
}
if v.TaggedVlans != nil {
mapping["tagged_vlans"] = flattenVlanAttributes(v.TaggedVlans)
}
if v.Tags != nil {
var tags []int64
for _, t := range v.Tags {
tags = append(tags, t.ID)
}
mapping["tag_ids"] = tags
}
if v.UntaggedVlan != nil {
vlanSlice := []*models.NestedVLAN{v.UntaggedVlan}
mapping["untagged_vlan"] = flattenVlanAttributes(vlanSlice)
}

mapping["vm_id"] = v.VirtualMachine.ID

s = append(s, mapping)
}

d.SetId(resource.UniqueId())
return d.Set("interfaces", s)

}

func flattenVlanAttributes(vlans []*models.NestedVLAN) []map[string]interface{} {
var mappedVlans []map[string]interface{}
for _, vlan := range vlans {
v := *vlan
mappedVlan := map[string]interface{}{
"id": v.ID,
"vid": *v.Vid,
"name": *v.Name,
}
mappedVlans = append(mappedVlans, mappedVlan)
}
return mappedVlans
}
109 changes: 109 additions & 0 deletions netbox/data_source_netbox_interfaces_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package netbox

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"testing"
)

func TestAccNetboxInterfacesDataSource_basic(t *testing.T) {

testSlug := "interface_ds_basic"
testResource := "data.netbox_interfaces.test"
testName := testAccGetTestName(testSlug)
dependencies := testAccNetboxInterfacesDataSourceDependencies(testName)
resource.ParallelTest(t, resource.TestCase{
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: dependencies,
},
{
Config: dependencies + testAccNetboxInterfacesDataSourceFilterName(testName),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(testResource, "interfaces.#", "1"),
resource.TestCheckResourceAttr(testResource, "interfaces.0.name", testName+"_0"),
resource.TestCheckResourceAttr(testResource, "interfaces.0.enabled", "true"),
resource.TestCheckResourceAttrPair(testResource, "interfaces.0.vm_id", "netbox_virtual_machine.test0", "id"),
),
},
{
Config: dependencies + testAccNetboxInterfacesDataSourceFilterVM,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(testResource, "interfaces.#", "2"),
resource.TestCheckResourceAttrPair(testResource, "interfaces.0.vm_id", "netbox_virtual_machine.test1", "id"),
resource.TestCheckResourceAttrPair(testResource, "interfaces.1.vm_id", "netbox_virtual_machine.test1", "id"),
),
},
{
Config: dependencies + testAccNetboxInterfacesDataSourceNameRegex,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(testResource, "interfaces.#", "1"),
resource.TestCheckResourceAttr(testResource, "interfaces.0.name", testName+"_2_regex"),
),
},
},
})
}

func testAccNetboxInterfacesDataSourceDependencies(testName string) string {
return fmt.Sprintf(`
resource "netbox_cluster_type" "test" {
name = "%[1]s"
}

resource "netbox_cluster" "test" {
name = "%[1]s"
cluster_type_id = netbox_cluster_type.test.id
}

resource "netbox_virtual_machine" "test0" {
name = "%[1]s_0"
cluster_id = netbox_cluster.test.id
}

resource "netbox_virtual_machine" "test1" {
name = "%[1]s_1"
cluster_id = netbox_cluster.test.id
}

resource "netbox_interface" "vm0_1" {
name = "%[1]s_0"
virtual_machine_id = netbox_virtual_machine.test0.id
}

resource "netbox_interface" "vm1_1" {
name = "%[1]s_1"
virtual_machine_id = netbox_virtual_machine.test1.id
}

resource "netbox_interface" "vm1_2" {
name = "%[1]s_2_regex"
virtual_machine_id = netbox_virtual_machine.test1.id
}

`, testName)
}

const testAccNetboxInterfacesDataSourceFilterVM = `
data "netbox_interfaces" "test" {
filter {
name = "vm_id"
value = netbox_virtual_machine.test1.id
}
}`

func testAccNetboxInterfacesDataSourceFilterName(testName string) string {
return fmt.Sprintf(`
data "netbox_interfaces" "test" {
filter {
name = "name"
value = "%[1]s_0"
}
}`, testName)
}

const testAccNetboxInterfacesDataSourceNameRegex = `
data "netbox_interfaces" "test" {
name_regex = "test.*_regex"
}`
1 change: 1 addition & 0 deletions netbox/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func Provider() *schema.Provider {
"netbox_device_role": dataSourceNetboxDeviceRole(),
"netbox_tag": dataSourceNetboxTag(),
"netbox_virtual_machines": dataSourceNetboxVirtualMachine(),
"netbox_interfaces": dataSourceNetboxInterfaces(),
},
Schema: map[string]*schema.Schema{
"server_url": {
Expand Down