diff --git a/examples/resources/netbox_dcim_platform/resource.tf b/examples/resources/netbox_dcim_platform/resource.tf new file mode 100644 index 000000000..db545fbbc --- /dev/null +++ b/examples/resources/netbox_dcim_platform/resource.tf @@ -0,0 +1,83 @@ +resource "netbox_dcim_platform" "platform_test" { + name = "Test platform" + slug = "Test platform" + description = "Platform for testing" + manufacturer_id = netbox_dcim_manufacturer.manufacturer_test.id + + tag { + name = "tag1" + slug = "tag1" + } + + custom_field { + name = "cf_boolean" + type = "boolean" + value = "true" + } + + custom_field { + name = "cf_date" + type = "date" + value = "2020-12-25" + } + + custom_field { + name = "cf_text" + type = "text" + value = "some text" + } + + custom_field { + name = "cf_integer" + type = "integer" + value = "10" + } + + custom_field { + name = "cf_selection" + type = "select" + value = "1" + } + + custom_field { + name = "cf_url" + type = "url" + value = "https://github.com" + } + + custom_field { + name = "cf_multi_selection" + type = "multiselect" + value = jsonencode([ + "0", + "1" + ]) + } + + custom_field { + name = "cf_json" + type = "json" + value = jsonencode({ + stringvalue = "string" + boolvalue = false + dictionary = { + numbervalue = 5 + } + }) + } + + custom_field { + name = "cf_object" + type = "object" + value = 1 + } + + custom_field { + name = "cf_multi_object" + type = "multiobject" + value = jsonencode([ + 1, + 2 + ]) + } +} diff --git a/netbox/dcim/resource_netbox_dcim_platform.go b/netbox/dcim/resource_netbox_dcim_platform.go new file mode 100644 index 000000000..807cb2a5f --- /dev/null +++ b/netbox/dcim/resource_netbox_dcim_platform.go @@ -0,0 +1,320 @@ +package dcim + +import ( + "context" + "strconv" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + netboxclient "github.com/smutel/go-netbox/v3/netbox/client" + "github.com/smutel/go-netbox/v3/netbox/client/dcim" + "github.com/smutel/go-netbox/v3/netbox/models" + "github.com/smutel/terraform-provider-netbox/v4/netbox/internal/customfield" + "github.com/smutel/terraform-provider-netbox/v4/netbox/internal/requestmodifier" + "github.com/smutel/terraform-provider-netbox/v4/netbox/internal/tag" + "github.com/smutel/terraform-provider-netbox/v4/netbox/internal/util" +) + +func ResourceNetboxDcimPlatform() *schema.Resource { + return &schema.Resource{ + Description: "Manage a platform (dcim module) within Netbox.", + CreateContext: resourceNetboxDcimPlatformCreate, + ReadContext: resourceNetboxDcimPlatformRead, + UpdateContext: resourceNetboxDcimPlatformUpdate, + DeleteContext: resourceNetboxDcimPlatformDelete, + Exists: resourceNetboxDcimPlatformExists, + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + + Schema: map[string]*schema.Schema{ + "content_type": { + Type: schema.TypeString, + Computed: true, + Description: "The content type of this platform (dcim module).", + }, + "created": { + Type: schema.TypeString, + Computed: true, + Description: "Date when this platform was created.", + }, + "custom_field": &customfield.CustomFieldSchema, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(0, 100), + Description: "The description of this platform (dcim module).", + }, + "device_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of devices this platform (dcim module).", + }, + "last_updated": { + Type: schema.TypeString, + Computed: true, + Description: "Date when this platform was last updated.", + }, + "manufacturer_id": { + Type: schema.TypeInt, + Optional: true, + Description: "The manufacturer of this platform (dcim module).", + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 100), + Description: "The name of this platform (dcim module).", + }, + "napalm_args": { + Type: schema.TypeString, + Optional: true, + Description: "Argument for the napalm driver.", + }, + "napalm_driver": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(0, 50), + Description: "The napalm driver", + }, + "slug": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 100), + Description: "The slug of this platform (dcim module).", + }, + "tag": &tag.TagSchema, + "url": { + Type: schema.TypeString, + Computed: true, + Description: "The link to this platform (dcim module).", + }, + "virtualmachine_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of virtual machines of this platform (dcim module).", + }, + }, + } +} + +var platformRequiredFields = []string{ + "created", + "last_updated", + "name", + "slug", + "tags", +} + +func resourceNetboxDcimPlatformCreate(ctx context.Context, d *schema.ResourceData, + m interface{}) diag.Diagnostics { + client := m.(*netboxclient.NetBoxAPI) + + resourceCustomFields := d.Get("custom_field").(*schema.Set).List() + customFields := customfield.ConvertCustomFieldsFromTerraformToAPI(nil, resourceCustomFields) + manufacturerID := int64(d.Get("manufacturer_id").(int)) + name := d.Get("name").(string) + napalmArgs := d.Get("napalm_args").(string) + slug := d.Get("slug").(string) + tags := d.Get("tag").(*schema.Set).List() + + newResource := &models.WritablePlatform{ + CustomFields: customFields, + Description: d.Get("description").(string), + Name: &name, + NapalmArgs: &napalmArgs, + NapalmDriver: d.Get("napalm_driver").(string), + Slug: &slug, + Tags: tag.ConvertTagsToNestedTags(tags), + } + if manufacturerID != 0 { + newResource.Manufacturer = &manufacturerID + } + + resource := dcim.NewDcimPlatformsCreateParams().WithData(newResource) + + resourceCreated, err := client.Dcim.DcimPlatformsCreate(resource, nil) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(strconv.FormatInt(resourceCreated.Payload.ID, 10)) + + return resourceNetboxDcimPlatformRead(ctx, d, m) +} + +func resourceNetboxDcimPlatformRead(ctx context.Context, d *schema.ResourceData, + m interface{}) diag.Diagnostics { + client := m.(*netboxclient.NetBoxAPI) + + resourceID := d.Id() + params := dcim.NewDcimPlatformsListParams().WithID(&resourceID) + resources, err := client.Dcim.DcimPlatformsList(params, nil) + if err != nil { + return diag.FromErr(err) + } + + if len(resources.Payload.Results) != 1 { + d.SetId("") + return nil + } + + resource := resources.Payload.Results[0] + + if err = d.Set("content_type", util.ConvertURIContentType(resource.URL)); err != nil { + return diag.FromErr(err) + } + if err = d.Set("created", resource.Created.String()); err != nil { + return diag.FromErr(err) + } + resourceCustomFields := d.Get("custom_field").(*schema.Set).List() + customFields := customfield.UpdateCustomFieldsFromAPI(resourceCustomFields, resource.CustomFields) + + if err = d.Set("custom_field", customFields); err != nil { + return diag.FromErr(err) + } + if err = d.Set("description", resource.Description); err != nil { + return diag.FromErr(err) + } + if err = d.Set("device_count", resource.DeviceCount); err != nil { + return diag.FromErr(err) + } + if err = d.Set("last_updated", resource.LastUpdated.String()); err != nil { + return diag.FromErr(err) + } + if err = d.Set("manufacturer_id", util.GetNestedManufacturerID(resource.Manufacturer)); err != nil { + return diag.FromErr(err) + } + if err = d.Set("name", resource.Name); err != nil { + return diag.FromErr(err) + } + if err = d.Set("napalm_args", resource.NapalmArgs); err != nil { + return diag.FromErr(err) + } + if err = d.Set("napalm_driver", resource.NapalmDriver); err != nil { + return diag.FromErr(err) + } + if err = d.Set("slug", resource.Slug); err != nil { + return diag.FromErr(err) + } + if err = d.Set("tag", tag.ConvertNestedTagsToTags(resource.Tags)); err != nil { + return diag.FromErr(err) + } + if err = d.Set("url", resource.URL); err != nil { + return diag.FromErr(err) + } + if err = d.Set("virtualmachine_count", resource.VirtualmachineCount); err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceNetboxDcimPlatformUpdate(ctx context.Context, d *schema.ResourceData, + m interface{}) diag.Diagnostics { + client := m.(*netboxclient.NetBoxAPI) + modifiedFields := make(map[string]interface{}) + + resourceID, err := strconv.ParseInt(d.Id(), 10, 64) + if err != nil { + return diag.Errorf("Unable to convert ID into int64") + } + params := &models.WritablePlatform{} + + if d.HasChange("custom_field") { + stateCustomFields, resourceCustomFields := d.GetChange("custom_field") + customFields := customfield.ConvertCustomFieldsFromTerraformToAPI(stateCustomFields.(*schema.Set).List(), resourceCustomFields.(*schema.Set).List()) + params.CustomFields = &customFields + } + if d.HasChange("description") { + description := d.Get("description").(string) + params.Description = description + modifiedFields["description"] = description + } + if d.HasChange("manufacturer_id") { + manufacturerID := int64(d.Get("manufacturer_id").(int)) + params.Manufacturer = &manufacturerID + modifiedFields["manufacturer"] = manufacturerID + } + if d.HasChange("name") { + name := d.Get("name").(string) + params.Name = &name + } + if d.HasChange("napalm_args") { + napalmArgs := d.Get("napalm_args").(string) + params.NapalmArgs = &napalmArgs + modifiedFields["napalm_args"] = napalmArgs + } + if d.HasChange("napalm_driver") { + napalmDriver := d.Get("napalm_driver").(string) + params.NapalmDriver = napalmDriver + modifiedFields["napalm_driver"] = napalmDriver + } + if d.HasChange("slug") { + slug := d.Get("slug").(string) + params.Slug = &slug + } + if d.HasChange("tag") { + tags := d.Get("tag").(*schema.Set).List() + params.Tags = tag.ConvertTagsToNestedTags(tags) + } + + resource := dcim.NewDcimPlatformsPartialUpdateParams().WithData(params) + + resource.SetID(resourceID) + + _, err = client.Dcim.DcimPlatformsPartialUpdate(resource, nil, requestmodifier.NewNetboxRequestModifier(modifiedFields, platformRequiredFields)) + if err != nil { + return diag.FromErr(err) + } + + return resourceNetboxDcimPlatformRead(ctx, d, m) +} + +func resourceNetboxDcimPlatformDelete(ctx context.Context, d *schema.ResourceData, + m interface{}) diag.Diagnostics { + client := m.(*netboxclient.NetBoxAPI) + + resourceExists, err := resourceNetboxDcimPlatformExists(d, m) + if err != nil { + return diag.FromErr(err) + } + + if !resourceExists { + return nil + } + + id, err := strconv.ParseInt(d.Id(), 10, 64) + if err != nil { + return diag.Errorf("Unable to convert ID into int64") + } + + resource := dcim.NewDcimPlatformsDeleteParams().WithID(id) + if _, err := client.Dcim.DcimPlatformsDelete(resource, nil); err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceNetboxDcimPlatformExists(d *schema.ResourceData, + m interface{}) (b bool, e error) { + client := m.(*netboxclient.NetBoxAPI) + resourceExist := false + + resourceID := d.Id() + params := dcim.NewDcimPlatformsListParams().WithID(&resourceID) + resources, err := client.Dcim.DcimPlatformsList(params, nil) + if err != nil { + return resourceExist, err + } + + for _, resource := range resources.Payload.Results { + if strconv.FormatInt(resource.ID, 10) == d.Id() { + resourceExist = true + } + } + + return resourceExist, nil +} diff --git a/netbox/dcim/resource_netbox_dcim_platform_test.go b/netbox/dcim/resource_netbox_dcim_platform_test.go new file mode 100644 index 000000000..07781b3c3 --- /dev/null +++ b/netbox/dcim/resource_netbox_dcim_platform_test.go @@ -0,0 +1,129 @@ +package dcim_test + +import ( + "strconv" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/smutel/terraform-provider-netbox/v4/netbox/internal/util" +) + +const resourceNameNetboxDcimPlatform = "netbox_dcim_platform.test" + +func TestAccNetboxDcimPlatformMinimal(t *testing.T) { + nameSuffix := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { util.TestAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckNetboxDcimPlatformConfig(nameSuffix, false, false), + Check: resource.ComposeTestCheckFunc( + util.TestAccResourceExists(resourceNameNetboxDcimPlatform), + ), + }, + { + ResourceName: resourceNameNetboxDcimPlatform, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccNetboxDcimPlatformFull(t *testing.T) { + nameSuffix := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { util.TestAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckNetboxDcimPlatformConfig(nameSuffix, true, true), + Check: resource.ComposeTestCheckFunc( + util.TestAccResourceExists(resourceNameNetboxDcimPlatform), + ), + }, + { + ResourceName: resourceNameNetboxDcimPlatform, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccNetboxDcimPlatformMinimalFullMinimal(t *testing.T) { + nameSuffix := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { util.TestAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckNetboxDcimPlatformConfig(nameSuffix, false, false), + Check: resource.ComposeTestCheckFunc( + util.TestAccResourceExists(resourceNameNetboxDcimPlatform), + ), + }, + { + Config: testAccCheckNetboxDcimPlatformConfig(nameSuffix, true, true), + Check: resource.ComposeTestCheckFunc( + util.TestAccResourceExists(resourceNameNetboxDcimPlatform), + ), + }, + { + Config: testAccCheckNetboxDcimPlatformConfig(nameSuffix, false, true), + Check: resource.ComposeTestCheckFunc( + util.TestAccResourceExists(resourceNameNetboxDcimPlatform), + ), + }, + { + Config: testAccCheckNetboxDcimPlatformConfig(nameSuffix, false, false), + Check: resource.ComposeTestCheckFunc( + util.TestAccResourceExists(resourceNameNetboxDcimPlatform), + ), + }, + }, + }) +} + +func testAccCheckNetboxDcimPlatformConfig(nameSuffix string, resourceFull, extraResources bool) string { + template := ` + {{ if eq .extraresources "true" }} + resource "netbox_dcim_manufacturer" "test" { + name = "test-{{ .namesuffix }}" + slug = "test-{{ .namesuffix }}" + } + + #resource "netbox_extras_tag" "test" { + # name = "test-{{ .namesuffix }}" + # slug = "test-{{ .namesuffix }}" + #} + {{ end }} + + resource "netbox_dcim_platform" "test" { + name = "test-{{ .namesuffix }}" + slug = "test-{{ .namesuffix }}" + {{ if eq .resourcefull "true" }} + description = "Test device role" + manufacturer_id = netbox_dcim_manufacturer.test.id + napalm_driver = "test" + napalm_args = "testing" + + #tag { + # name = netbox_extras_tag.test.name + # slug = netbox_extras_tag.test.slug + #} + {{ end }} + } + ` + data := map[string]string{ + "namesuffix": nameSuffix, + "resourcefull": strconv.FormatBool(resourceFull), + "extraresources": strconv.FormatBool(extraResources), + } + return util.RenderTemplate(template, data) +} diff --git a/netbox/internal/util/nested.go b/netbox/internal/util/nested.go index 909e6bc98..34b4ccc49 100644 --- a/netbox/internal/util/nested.go +++ b/netbox/internal/util/nested.go @@ -12,6 +12,14 @@ func GetNestedIPAddressAddress(nested *models.NestedIPAddress) *string { return nested.Address } +func GetNestedManufacturerID(nested *models.NestedManufacturer) *int64 { + if nested == nil { + return nil + } + + return &nested.ID +} + func GetNestedPlatformID(nested *models.NestedPlatform) *int64 { if nested == nil { return nil diff --git a/netbox/provider.go b/netbox/provider.go index 40ad66844..fbdda81f4 100644 --- a/netbox/provider.go +++ b/netbox/provider.go @@ -163,6 +163,7 @@ func Provider() *schema.Provider { ResourcesMap: map[string]*schema.Resource{ "netbox_dcim_manufacturer": dcim.ResourceNetboxDcimManufacturer(), "netbox_dcim_device_role": dcim.ResourceNetboxDcimDeviceRole(), + "netbox_dcim_platform": dcim.ResourceNetboxDcimPlatform(), "netbox_ipam_aggregate": ipam.ResourceNetboxIpamAggregate(), "netbox_ipam_ip_addresses": ipam.ResourceNetboxIpamIPAddresses(), "netbox_ipam_ip_range": ipam.ResourceNetboxIpamIPRange(), diff --git a/netbox/virtualization/resource_netbox_virtualization_vm_test.go b/netbox/virtualization/resource_netbox_virtualization_vm_test.go index 4421f2257..1b3075685 100644 --- a/netbox/virtualization/resource_netbox_virtualization_vm_test.go +++ b/netbox/virtualization/resource_netbox_virtualization_vm_test.go @@ -106,12 +106,9 @@ func testAccCheckNetboxVirtualizationVMConfig(nameSuffix string, resourceFull, e } {{ if eq .extraresources "true" }} - #resource "netbox_dcim_platform" "test" { - # name = "test-{{ .namesuffix }}" - # slug = "test-{{ .namesuffix }}" - #} - data "netbox_dcim_platform" "platform_test" { - slug = "Debian_10" + resource "netbox_dcim_platform" "test" { + name = "test-{{ .namesuffix }}" + slug = "test-{{ .namesuffix }}" } resource "netbox_dcim_device_role" "test" { @@ -138,8 +135,7 @@ func testAccCheckNetboxVirtualizationVMConfig(nameSuffix string, resourceFull, e {{ if eq .resourcefull "true" }} comments = "VM created by terraform" role_id = netbox_dcim_device_role.test.id - #platform_id = netbox_dcim_platform.test.id - platform_id = data.netbox_dcim_platform.platform_test.id + platform_id = netbox_dcim_platform.test.id tenant_id = netbox_tenancy_tenant.test.id status = "planned" vcpus = 2