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 vlan resource #6

Merged
merged 5 commits into from
Nov 26, 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
1 change: 1 addition & 0 deletions anxcloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func Provider() *schema.Provider {
},
ResourcesMap: map[string]*schema.Resource{
"anxcloud_virtual_server": resourceVirtualServer(),
"anxcloud_vlan": resourceVLAN(),
},
DataSourcesMap: map[string]*schema.Resource{},
ConfigureContextFunc: providerConfigure,
Expand Down
4 changes: 2 additions & 2 deletions anxcloud/resource_virtual_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,12 @@ func resourceVirtualServerDelete(ctx context.Context, d *schema.ResourceData, m
_, err := v.Info().Get(ctx, d.Id())
if err != nil {
if err := handleNotFoundError(err); err != nil {
return resource.NonRetryableError(fmt.Errorf("unable to get vm '%s': %w", d.Id(), err))
return resource.NonRetryableError(fmt.Errorf("unable to get vm with id '%s': %w", d.Id(), err))
}
d.SetId("")
return nil
}
return resource.RetryableError(fmt.Errorf("waiting for vm with ID '%s' to be deleted", d.Id()))
return resource.RetryableError(fmt.Errorf("waiting for vm with id '%s' to be deleted", d.Id()))
})
if err != nil {
return diag.FromErr(err)
Expand Down
10 changes: 5 additions & 5 deletions anxcloud/resource_virtual_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestAccAnxcloudVirtualServerBasic(t *testing.T) {

locationID := "52b5f6b2fd3a4a7eaaedf1a7c019e9ea"
templateID := "12c28aa7-604d-47e9-83fb-5f1d1f1837b3"
vlanID := "ff70791b398e4ab29786dd34f211694c"
vlanID := "02f39d20ca0f4adfb5032f88dbc26c39"
cpus := 4
memory := 4096
diskSize := 50
Expand Down Expand Up @@ -66,7 +66,7 @@ func testAccCheckAnxcloudVirtualServerDestroy(s *terraform.State) error {
return nil
}
if info.Identifier != "" {
return fmt.Errorf("virtual machine '%s' exist", info.Identifier)
return fmt.Errorf("virtual machine '%s' exists", info.Identifier)
}
}

Expand Down Expand Up @@ -102,11 +102,11 @@ func testAccCheckAnxcloudVirtualServerExists(n string) resource.TestCheckFunc {
ctx := context.Background()

if !ok {
return fmt.Errorf("not found: %s", n)
return fmt.Errorf("virtual server not found: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("id not set for virtual machine")
return fmt.Errorf("virtual server id not set")
}

info, err := v.Info().Get(ctx, rs.Primary.ID)
Expand All @@ -115,7 +115,7 @@ func testAccCheckAnxcloudVirtualServerExists(n string) resource.TestCheckFunc {
}

if info.Status != vmPoweredOn {
return fmt.Errorf("virtual machine found but it is in '%s' state", info.Status)
return fmt.Errorf("virtual machine found but it is not in the expected state '%s': '%s'", vmPoweredOn, info.Status)
}

return nil
Expand Down
147 changes: 147 additions & 0 deletions anxcloud/resource_vlan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package anxcloud

import (
"context"
"fmt"
"time"

"github.com/anexia-it/go-anxcloud/pkg/client"
"github.com/anexia-it/go-anxcloud/pkg/vlan"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

const (
vlanStatusActive = "Active"
)

func resourceVLAN() *schema.Resource {
return &schema.Resource{
CreateContext: resourceVLANCreate,
ReadContext: resourceVLANRead,
UpdateContext: resourceVLANUpdate,
DeleteContext: resourceVLANDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Read: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(15 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: schemaVLAN(),
}
}

func resourceVLANCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(client.Client)
v := vlan.NewAPI(c)
locationID := d.Get("location_id").(string)

def := vlan.CreateDefinition{
Location: locationID,
VMProvisioning: d.Get("vm_provisioning").(bool),
CustomerDescription: d.Get("description_customer").(string),
}
res, err := v.Create(ctx, def)
if err != nil {
return diag.FromErr(err)
}
d.SetId(res.Identifier)

err = resource.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
vlan, err := v.Get(ctx, d.Id())
if err != nil {
return resource.NonRetryableError(fmt.Errorf("unable to fetch vlan with '%s' id: %w", d.Id(), err))
}
if vlan.Status == vlanStatusActive {
return nil
}
return resource.RetryableError(fmt.Errorf("waiting for vlan with '%s' id to be '%s'", d.Id(), vlanStatusActive))
})
if err != nil {
return diag.FromErr(err)
}

return resourceVLANRead(ctx, d, m)
}

func resourceVLANRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
var diags []diag.Diagnostic
c := m.(client.Client)
v := vlan.NewAPI(c)

vlan, err := v.Get(ctx, d.Id())
if err != nil {
return diag.FromErr(err)
}

if err := d.Set("name", vlan.Name); err != nil {
diags = append(diags, diag.FromErr(err)...)
}
if err := d.Set("role_text", vlan.Role); err != nil {
diags = append(diags, diag.FromErr(err)...)
}
if err := d.Set("status", vlan.Status); err != nil {
diags = append(diags, diag.FromErr(err)...)
}
if err := d.Set("description_customer", vlan.CustomerDescription); err != nil {
diags = append(diags, diag.FromErr(err)...)
}
if err := d.Set("description_internal", vlan.InternalDescription); err != nil {
diags = append(diags, diag.FromErr(err)...)
}
if err := d.Set("locations", flattenVLANLocations(vlan.Locations)); err != nil {
diags = append(diags, diag.FromErr(err)...)
}

return diags
}

func resourceVLANUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(client.Client)
v := vlan.NewAPI(c)

if !d.HasChange("description_customer") {
return nil
}

def := vlan.UpdateDefinition{
CustomerDescription: d.Get("description_customer").(string),
}
if err := v.Update(ctx, d.Id(), def); err != nil {
return diag.FromErr(err)
}

return resourceVLANRead(ctx, d, m)
}

func resourceVLANDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
c := m.(client.Client)
v := vlan.NewAPI(c)

err := v.Delete(ctx, d.Id())
if err != nil {
if err := handleNotFoundError(err); err != nil {
return diag.FromErr(err)
}
d.SetId("")
return nil
}

err = resource.RetryContext(ctx, d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
_, err := v.Get(ctx, d.Id())
if err != nil {
if err := handleNotFoundError(err); err != nil {
return resource.NonRetryableError(fmt.Errorf("unable to get vlan with id '%s': %w", d.Id(), err))
}
d.SetId("")
return nil
}
return resource.RetryableError(fmt.Errorf("waiting for vlan with id '%s' to be deleted", d.Id()))
})
if err != nil {
return diag.FromErr(err)
}

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

import (
"context"
"fmt"
"testing"

"github.com/anexia-it/go-anxcloud/pkg/client"
"github.com/anexia-it/go-anxcloud/pkg/vlan"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccAnxcloudVLAN(t *testing.T) {
resourceName := "acc_test_basic"
resourcePath := "anxcloud_vlan." + resourceName

locationID := "52b5f6b2fd3a4a7eaaedf1a7c019e9ea"
customerDescription := "vlan acceptance tests"
customerDescriptionUpdate := "vlan acceptance tests update"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviders,
CheckDestroy: testAccCheckAnxcloudVLANDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckAnxcloudVLAN(resourceName, locationID, customerDescription),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourcePath, "location_id", locationID),
resource.TestCheckResourceAttr(resourcePath, "vm_provisioning", "true"),
resource.TestCheckResourceAttr(resourcePath, "description_customer", customerDescription),
testAccCheckAnxcloudVLANExists(resourcePath, customerDescription),
),
},
{
Config: testAccCheckAnxcloudVLAN(resourceName, locationID, customerDescriptionUpdate),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourcePath, "location_id", locationID),
resource.TestCheckResourceAttr(resourcePath, "vm_provisioning", "true"),
resource.TestCheckResourceAttr(resourcePath, "description_customer", customerDescriptionUpdate),
testAccCheckAnxcloudVLANExists(resourcePath, customerDescriptionUpdate),
),
},
},
})
}

func testAccCheckAnxcloudVLANDestroy(s *terraform.State) error {
c := testAccProvider.Meta().(client.Client)
v := vlan.NewAPI(c)
ctx := context.Background()
for _, rs := range s.RootModule().Resources {
if rs.Type != "anxcloud_vlan" {
continue
}

if rs.Primary.ID == "" {
return nil
}

info, err := v.Get(ctx, rs.Primary.ID)
if err != nil {
if err := handleNotFoundError(err); err != nil {
return err
}
return nil
}
if info.Identifier != "" {
return fmt.Errorf("vlan '%s' exists", info.Identifier)
}
}

return nil
}

func testAccCheckAnxcloudVLAN(resourceName, locationID, customerDescription string) string {
return fmt.Sprintf(`
resource "anxcloud_vlan" "%s" {
location_id = "%s"
vm_provisioning = true
description_customer = "%s"
}
`, resourceName, locationID, customerDescription)
}

func testAccCheckAnxcloudVLANExists(n string, expectedCustomerDescription string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
c := testAccProvider.Meta().(client.Client)
v := vlan.NewAPI(c)
ctx := context.Background()

if !ok {
return fmt.Errorf("vlan not found: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("vlan id not set")
}

i, err := v.Get(ctx, rs.Primary.ID)
if err != nil {
return err
}

if i.Status != vlanStatusActive {
return fmt.Errorf("vlan found but it is not in the expected state '%s': %s", vlanStatusActive, i.Status)
}

if i.CustomerDescription != expectedCustomerDescription {
return fmt.Errorf("customer description is different than expected '%s': '%s'", i.CustomerDescription, expectedCustomerDescription)
}

return nil
}
}
Loading