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 netbox_vlan resource #83

Merged
merged 5 commits into from
Oct 25, 2021
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
1 change: 1 addition & 0 deletions netbox/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func Provider() *schema.Provider {
"netbox_tag": resourceNetboxTag(),
"netbox_cluster_group": resourceNetboxClusterGroup(),
"netbox_site": resourceNetboxSite(),
"netbox_vlan": resourceNetboxVlan(),
},
DataSourcesMap: map[string]*schema.Resource{
"netbox_cluster": dataSourceNetboxCluster(),
Expand Down
189 changes: 189 additions & 0 deletions netbox/resource_netbox_vlan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package netbox

import (
"strconv"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/ipam"
"github.com/fbreckle/go-netbox/netbox/models"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)

func resourceNetboxVlan() *schema.Resource {
return &schema.Resource{
Create: resourceNetboxVlanCreate,
Read: resourceNetboxVlanRead,
Update: resourceNetboxVlanUpdate,
Delete: resourceNetboxVlanDelete,

Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"vid": {
Type: schema.TypeInt,
Required: true,
},
"status": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"active", "reserved", "deprecated"}, false),
},
"tenant_id": {
Type: schema.TypeInt,
Optional: true,
},

"role_id": {
Type: schema.TypeInt,
Optional: true,
},

"site_id": {
Type: schema.TypeInt,
Optional: true,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"tags": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Required: true,
Set: schema.HashString,
},
},
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
}
}

func resourceNetboxVlanCreate(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
data := models.WritableVLAN{}

name := d.Get("name").(string)
vid := int64(d.Get("vid").(int))
status := d.Get("status").(string)
description := d.Get("description").(string)

data.Name = &name
data.Vid = &vid
data.Status = status
data.Description = description

data.Tags, _ = getNestedTagListFromResourceDataSet(api, d.Get("tags"))

params := ipam.NewIpamVlansCreateParams().WithData(&data)
res, err := api.Ipam.IpamVlansCreate(params, nil)
if err != nil {
return err
}
d.SetId(strconv.FormatInt(res.GetPayload().ID, 10))

return resourceNetboxVlanUpdate(d, m)
}

func resourceNetboxVlanRead(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
id, _ := strconv.ParseInt(d.Id(), 10, 64)
params := ipam.NewIpamVlansReadParams().WithID(id)

res, err := api.Ipam.IpamVlansRead(params, nil)
if err != nil {
errorcode := err.(*ipam.IpamVlansReadDefault).Code()
if errorcode == 404 {
// If the ID is updated to blank, this tells Terraform the resource no longer exists (maybe it was destroyed out of band). Just like the destroy callback, the Read function should gracefully handle this case. https://www.terraform.io/docs/extend/writing-custom-providers.html
d.SetId("")
return nil
}
return err
}

if res.GetPayload().Name != nil {
d.Set("name", res.GetPayload().Name)
}

if res.GetPayload().Vid != nil {
d.Set("vid", res.GetPayload().Vid)
}

if res.GetPayload().Status != nil {
d.Set("status", res.GetPayload().Status.Value)
}

if res.GetPayload().Description != "" {
d.Set("description", res.GetPayload().Description)
}

if res.GetPayload().Site != nil {
d.Set("site_id", res.GetPayload().Site.ID)
}

if res.GetPayload().Tenant != nil {
d.Set("tenant_id", res.GetPayload().Tenant.ID)
}

if res.GetPayload().Role != nil {
d.Set("role_id", res.GetPayload().Role.ID)
}

d.Set("tags", getTagListFromNestedTagList(res.GetPayload().Tags))

return nil
}

func resourceNetboxVlanUpdate(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
id, _ := strconv.ParseInt(d.Id(), 10, 64)
data := models.WritableVLAN{}
name := d.Get("name").(string)
vid := int64(d.Get("vid").(int))
status := d.Get("status").(string)
description := d.Get("description").(string)

data.Name = &name
data.Vid = &vid

data.Status = status
data.Description = description

if siteID, ok := d.GetOk("site_id"); ok {
data.Site = int64ToPtr(int64(siteID.(int)))
}

if tenantID, ok := d.GetOk("tenant_id"); ok {
data.Tenant = int64ToPtr(int64(tenantID.(int)))
}

if roleID, ok := d.GetOk("role_id"); ok {
data.Role = int64ToPtr(int64(roleID.(int)))
}

data.Tags, _ = getNestedTagListFromResourceDataSet(api, d.Get("tags"))

params := ipam.NewIpamVlansUpdateParams().WithID(id).WithData(&data)
_, err := api.Ipam.IpamVlansUpdate(params, nil)
if err != nil {
return err
}
return resourceNetboxVlanRead(d, m)
}

func resourceNetboxVlanDelete(d *schema.ResourceData, m interface{}) error {
api := m.(*client.NetBoxAPI)
id, _ := strconv.ParseInt(d.Id(), 10, 64)
params := ipam.NewIpamVlansDeleteParams().WithID(id)
_, err := api.Ipam.IpamVlansDelete(params, nil)
if err != nil {
return err
}

return nil
}
134 changes: 134 additions & 0 deletions netbox/resource_netbox_vlan_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package netbox

import (
"fmt"
"log"
"strings"
"testing"

"github.com/fbreckle/go-netbox/netbox/client"
"github.com/fbreckle/go-netbox/netbox/client/ipam"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

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

resource "netbox_tenant" "test" {
name = "%[1]s"
}

resource "netbox_site" "test" {
name = "%[1]s"
status = "active"
}
`, testName)
}
func TestAccNetboxVlan_basic(t *testing.T) {

testSlug := "vlan_basic"
testName := testAccGetTestName(testSlug)
testVid := "777"
testDescription := "Test Description"
resource.ParallelTest(t, resource.TestCase{
Providers: testAccProviders,
PreCheck: func() { testAccPreCheck(t) },
Steps: []resource.TestStep{
{
Config: testAccNetboxPrefixFullDependencies(testName) + fmt.Sprintf(`
resource "netbox_vlan" "test_basic" {
name = "%s"
vid = "%s"
status = "active"
description = "%s"
tags = []
}`, testName, testVid, testDescription),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("netbox_vlan.test_basic", "name", testName),
resource.TestCheckResourceAttr("netbox_vlan.test_basic", "vid", testVid),
resource.TestCheckResourceAttr("netbox_vlan.test_basic", "description", testDescription),
resource.TestCheckResourceAttr("netbox_vlan.test_basic", "tags.#", "0"),
),
},
{
ResourceName: "netbox_vlan.test_basic",
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func TestAccNetboxVlan_with_dependencies(t *testing.T) {

testSlug := "vlan_with_dependencies"
testName := testAccGetTestName(testSlug)
testVid := "666"
testDescription := "Test Description"
resource.ParallelTest(t, resource.TestCase{
Providers: testAccProviders,
PreCheck: func() { testAccPreCheck(t) },
Steps: []resource.TestStep{
{
Config: testAccNetboxPrefixFullDependencies(testName) + fmt.Sprintf(`
resource "netbox_vlan" "test_with_dependencies" {
name = "%s"
vid = "%s"
description = "%s"
status = "active"
tenant_id = netbox_tenant.test.id
site_id = netbox_site.test.id
tags = [netbox_tag.test.name]
}`, testName, testVid, testDescription),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("netbox_vlan.test_with_dependencies", "name", testName),
resource.TestCheckResourceAttr("netbox_vlan.test_with_dependencies", "vid", testVid),
resource.TestCheckResourceAttr("netbox_vlan.test_with_dependencies", "description", testDescription),
resource.TestCheckResourceAttr("netbox_vlan.test_with_dependencies", "status", "active"),
resource.TestCheckResourceAttrPair("netbox_vlan.test_with_dependencies", "tenant_id", "netbox_tenant.test", "id"),
resource.TestCheckResourceAttrPair("netbox_vlan.test_with_dependencies", "site_id", "netbox_site.test", "id"),
resource.TestCheckResourceAttr("netbox_vlan.test_with_dependencies", "tags.#", "1"),
resource.TestCheckResourceAttr("netbox_vlan.test_with_dependencies", "tags.0", testName),
),
},
{
ResourceName: "netbox_vlan.test_with_dependencies",
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func init() {
resource.AddTestSweepers("netbox_vlan", &resource.Sweeper{
Name: "netbox_vlan",
Dependencies: []string{},
F: func(region string) error {
m, err := sharedClientForRegion(region)
if err != nil {
return fmt.Errorf("Error getting client: %s", err)
}
api := m.(*client.NetBoxAPI)
params := ipam.NewIpamVlansListParams()
res, err := api.Ipam.IpamVlansList(params, nil)
if err != nil {
return err
}
for _, vlan := range res.GetPayload().Results {
if strings.HasPrefix(*vlan.Name, testPrefix) {
deleteParams := ipam.NewIpamVlansDeleteParams().WithID(vlan.ID)
_, err := api.Ipam.IpamVlansDelete(deleteParams, nil)
if err != nil {
return err
}
log.Print("[DEBUG] Deleted a vlan")
}
}
return nil
},
})
}