From d0f0efa42459310c005153e6a13e419edaf7078f Mon Sep 17 00:00:00 2001 From: Kuba Mazurkiewicz <132581633+kuba-mazurkiewicz@users.noreply.github.com> Date: Thu, 8 Aug 2024 11:15:07 +0200 Subject: [PATCH] Add fabric l2 handoff resource and data source (#112) --- CHANGELOG.md | 1 + docs/data-sources/fabric_l2_handoff.md | 36 +++ docs/guides/changelog.md | 1 + docs/resources/fabric_l2_handoff.md | 46 +++ .../data-source.tf | 5 + .../import.sh | 1 + .../resource.tf | 7 + gen/definitions/fabric_l2_handoff.yaml | 67 +++++ gen/templates/resource.go | 2 +- ...source_catalystcenter_fabric_l2_handoff.go | 128 ++++++++ ...e_catalystcenter_fabric_l2_handoff_test.go | 91 ++++++ .../model_catalystcenter_fabric_l2_handoff.go | 159 ++++++++++ internal/provider/provider.go | 2 + ...source_catalystcenter_fabric_l2_handoff.go | 277 ++++++++++++++++++ ...e_catalystcenter_fabric_l2_handoff_test.go | 104 +++++++ templates/guides/changelog.md.tmpl | 1 + 16 files changed, 927 insertions(+), 1 deletion(-) create mode 100644 docs/data-sources/fabric_l2_handoff.md create mode 100644 docs/resources/fabric_l2_handoff.md create mode 100644 examples/data-sources/catalystcenter_fabric_l2_handoff/data-source.tf create mode 100644 examples/resources/catalystcenter_fabric_l2_handoff/import.sh create mode 100644 examples/resources/catalystcenter_fabric_l2_handoff/resource.tf create mode 100644 gen/definitions/fabric_l2_handoff.yaml create mode 100644 internal/provider/data_source_catalystcenter_fabric_l2_handoff.go create mode 100644 internal/provider/data_source_catalystcenter_fabric_l2_handoff_test.go create mode 100644 internal/provider/model_catalystcenter_fabric_l2_handoff.go create mode 100644 internal/provider/resource_catalystcenter_fabric_l2_handoff.go create mode 100644 internal/provider/resource_catalystcenter_fabric_l2_handoff_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f9a3c01..d727e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## 0.1.10 (unreleased) +- Add `fabric_l2_handoff` resource and data source - BREAKING CHANGE: Modified `wireless_profile` resource to use `/intent/api/v1/wirelessProfiles` API endpoint, this resource now only works with Catalyst Center version 2.3.7.6+ - Add `wireless_device_provision` resource - Add `fabric_provision_device` resource and data source diff --git a/docs/data-sources/fabric_l2_handoff.md b/docs/data-sources/fabric_l2_handoff.md new file mode 100644 index 0000000..2418ad6 --- /dev/null +++ b/docs/data-sources/fabric_l2_handoff.md @@ -0,0 +1,36 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_fabric_l2_handoff Data Source - terraform-provider-catalystcenter" +subcategory: "SDA" +description: |- + This data source can read the Fabric L2 Handoff. +--- + +# catalystcenter_fabric_l2_handoff (Data Source) + +This data source can read the Fabric L2 Handoff. + +## Example Usage + +```terraform +data "catalystcenter_fabric_l2_handoff" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" + network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1" + fabric_id = "c4b85bb2-ce3f-4db9-a32b-e439a388ac2f" +} +``` + + +## Schema + +### Required + +- `fabric_id` (String) ID of the fabric this device belongs to +- `id` (String) The id of the object +- `network_device_id` (String) Network device ID of the fabric device + +### Read-Only + +- `external_vlan_id` (Number) External VLAN number into which the fabric must be extended. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094) +- `interface_name` (String) Interface name of the layer 2 handoff. E.g., GigabitEthernet1/0/4 +- `internal_vlan_id` (Number) VLAN number associated with this fabric. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094) diff --git a/docs/guides/changelog.md b/docs/guides/changelog.md index f399dd5..1e0bc24 100644 --- a/docs/guides/changelog.md +++ b/docs/guides/changelog.md @@ -9,6 +9,7 @@ description: |- ## 0.1.10 (unreleased) +- Add `fabric_l2_handoff` resource and data source - BREAKING CHANGE: Modified `wireless_profile` resource to use `/intent/api/v1/wirelessProfiles` API endpoint, this resource now only works with Catalyst Center version 2.3.7.6+ - Add `wireless_device_provision` resource - Add `fabric_provision_device` resource and data source diff --git a/docs/resources/fabric_l2_handoff.md b/docs/resources/fabric_l2_handoff.md new file mode 100644 index 0000000..0ee5f14 --- /dev/null +++ b/docs/resources/fabric_l2_handoff.md @@ -0,0 +1,46 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_fabric_l2_handoff Resource - terraform-provider-catalystcenter" +subcategory: "SDA" +description: |- + Manages Layer 2 Handoffs in Fabric Devices +--- + +# catalystcenter_fabric_l2_handoff (Resource) + +Manages Layer 2 Handoffs in Fabric Devices + +## Example Usage + +```terraform +resource "catalystcenter_fabric_l2_handoff" "example" { + network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1" + fabric_id = "c4b85bb2-ce3f-4db9-a32b-e439a388ac2f" + interface_name = "GigabitEthernet1/0/4" + internal_vlan_id = 300 + external_vlan_id = 400 +} +``` + + +## Schema + +### Required + +- `external_vlan_id` (Number) External VLAN number into which the fabric must be extended. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094) +- `fabric_id` (String) ID of the fabric this device belongs to +- `interface_name` (String) Interface name of the layer 2 handoff. E.g., GigabitEthernet1/0/4 +- `internal_vlan_id` (Number) VLAN number associated with this fabric. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094) +- `network_device_id` (String) Network device ID of the fabric device + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_fabric_l2_handoff.example ",," +``` diff --git a/examples/data-sources/catalystcenter_fabric_l2_handoff/data-source.tf b/examples/data-sources/catalystcenter_fabric_l2_handoff/data-source.tf new file mode 100644 index 0000000..f42ba2e --- /dev/null +++ b/examples/data-sources/catalystcenter_fabric_l2_handoff/data-source.tf @@ -0,0 +1,5 @@ +data "catalystcenter_fabric_l2_handoff" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" + network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1" + fabric_id = "c4b85bb2-ce3f-4db9-a32b-e439a388ac2f" +} diff --git a/examples/resources/catalystcenter_fabric_l2_handoff/import.sh b/examples/resources/catalystcenter_fabric_l2_handoff/import.sh new file mode 100644 index 0000000..fbf9f27 --- /dev/null +++ b/examples/resources/catalystcenter_fabric_l2_handoff/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_fabric_l2_handoff.example ",," diff --git a/examples/resources/catalystcenter_fabric_l2_handoff/resource.tf b/examples/resources/catalystcenter_fabric_l2_handoff/resource.tf new file mode 100644 index 0000000..4d014cd --- /dev/null +++ b/examples/resources/catalystcenter_fabric_l2_handoff/resource.tf @@ -0,0 +1,7 @@ +resource "catalystcenter_fabric_l2_handoff" "example" { + network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1" + fabric_id = "c4b85bb2-ce3f-4db9-a32b-e439a388ac2f" + interface_name = "GigabitEthernet1/0/4" + internal_vlan_id = 300 + external_vlan_id = 400 +} diff --git a/gen/definitions/fabric_l2_handoff.yaml b/gen/definitions/fabric_l2_handoff.yaml new file mode 100644 index 0000000..5434832 --- /dev/null +++ b/gen/definitions/fabric_l2_handoff.yaml @@ -0,0 +1,67 @@ +--- +name: Fabric L2 Handoff +rest_endpoint: /dna/intent/api/v1/sda/fabricDevices/layer2Handoffs +res_description: Manages Layer 2 Handoffs in Fabric Devices +id_from_query_path: response +id_from_query_path_attribute: id +put_id_include_path: 0.id +get_from_all: true +put_no_id: true +doc_category: SDA +test_tags: [SDA] +attributes: + - model_name: networkDeviceId + query_param: true + requires_replace: true + data_path: '0' + response_data_path: networkDeviceId + mandatory: true + description: Network device ID of the fabric device + type: String + example: 5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1 + - model_name: fabricId + requires_replace: true + query_param: true + data_path: '0' + response_data_path: fabricId + type: String + mandatory: true + description: ID of the fabric this device belongs to + example: c4b85bb2-ce3f-4db9-a32b-e439a388ac2f + test_value: catalystcenter_fabric_site.test.id + - model_name: interfaceName + requires_replace: true + data_path: '0' + response_data_path: interfaceName + type: String + mandatory: true + description: Interface name of the layer 2 handoff. E.g., GigabitEthernet1/0/4 + example: GigabitEthernet1/0/4 + - model_name: internalVlanId + data_path: '0' + requires_replace: true + response_data_path: internalVlanId + type: Int64 + match_id: true + mandatory: true + description: VLAN number associated with this fabric. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094) + example: 300 + - model_name: externalVlanId + data_path: '0' + requires_replace: true + response_data_path: externalVlanId + mandatory: true + type: Int64 + description: External VLAN number into which the fabric must be extended. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094) + example: 400 +test_prerequisites: | + resource "catalystcenter_area" "test" { + name = "Area1" + parent_name = "Global" + } + resource "catalystcenter_fabric_site" "test" { + site_id = catalystcenter_area.test.id + pub_sub_enabled = false + authentication_profile_name = "No Authentication" + depends_on = [catalystcenter_area.test] + } diff --git a/gen/templates/resource.go b/gen/templates/resource.go index d2dfcc5..ecbc78a 100644 --- a/gen/templates/resource.go +++ b/gen/templates/resource.go @@ -459,7 +459,7 @@ func (r *{{camelCase .Name}}Resource) Create(ctx context.Context, req resource.C {{- if and .IdFromQueryPathAttribute .IdFromQueryPath (not .GetExtraQueryParams) (not .GetFromAll) }} plan.Id = types.StringValue(res.Get("{{if eq .IdFromQueryPath "." }}{{else}}{{.IdFromQueryPath}}.{{end}}{{.IdFromQueryPathAttribute}}").String()) {{- else}} - plan.Id = types.StringValue(res.Get("{{.IdFromQueryPath}}.#({{if $id.ResponseModelName}}{{$id.ResponseModelName}}{{else}}{{$id.ModelName}}{{end}}==\""+ plan.{{toGoName $id.TfName}}.Value{{$id.Type}}() +"\").{{if .IdFromQueryPathAttribute}}{{.IdFromQueryPathAttribute}}{{else}}id{{end}}").String()) + plan.Id = types.StringValue(res.Get("{{.IdFromQueryPath}}.#({{if $id.ResponseModelName}}{{$id.ResponseModelName}}{{else}}{{$id.ModelName}}{{end}}==\""+ {{if eq $id.Type "Int64"}}strconv.FormatInt(plan.{{toGoName $id.TfName}}.ValueInt64(), 10){{else}}plan.{{toGoName $id.TfName}}.Value{{$id.Type}}(){{end}} +"\").{{if .IdFromQueryPathAttribute}}{{.IdFromQueryPathAttribute}}{{else}}id{{end}}").String()) {{- end}} {{- /* If we have an id attribute we will use that as id */}} {{- else if hasId .Attributes}} diff --git a/internal/provider/data_source_catalystcenter_fabric_l2_handoff.go b/internal/provider/data_source_catalystcenter_fabric_l2_handoff.go new file mode 100644 index 0000000..229f08b --- /dev/null +++ b/internal/provider/data_source_catalystcenter_fabric_l2_handoff.go @@ -0,0 +1,128 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package provider + +// Section below is generated&owned by "gen/generator.go". //template:begin imports +import ( + "context" + "fmt" + "net/url" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +// End of section. //template:end imports + +// Section below is generated&owned by "gen/generator.go". //template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &FabricL2HandoffDataSource{} + _ datasource.DataSourceWithConfigure = &FabricL2HandoffDataSource{} +) + +func NewFabricL2HandoffDataSource() datasource.DataSource { + return &FabricL2HandoffDataSource{} +} + +type FabricL2HandoffDataSource struct { + client *cc.Client +} + +func (d *FabricL2HandoffDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_fabric_l2_handoff" +} + +func (d *FabricL2HandoffDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Fabric L2 Handoff.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "network_device_id": schema.StringAttribute{ + MarkdownDescription: "Network device ID of the fabric device", + Required: true, + }, + "fabric_id": schema.StringAttribute{ + MarkdownDescription: "ID of the fabric this device belongs to", + Required: true, + }, + "interface_name": schema.StringAttribute{ + MarkdownDescription: "Interface name of the layer 2 handoff. E.g., GigabitEthernet1/0/4", + Computed: true, + }, + "internal_vlan_id": schema.Int64Attribute{ + MarkdownDescription: "VLAN number associated with this fabric. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094)", + Computed: true, + }, + "external_vlan_id": schema.Int64Attribute{ + MarkdownDescription: "External VLAN number into which the fabric must be extended. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094)", + Computed: true, + }, + }, + } +} + +func (d *FabricL2HandoffDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +// End of section. //template:end model + +// Section below is generated&owned by "gen/generator.go". //template:begin read +func (d *FabricL2HandoffDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config FabricL2Handoff + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + params += "?networkDeviceId=" + url.QueryEscape(config.NetworkDeviceId.ValueString()) + "&fabricId=" + url.QueryEscape(config.FabricId.ValueString()) + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + res = res.Get("response.#(id==\"" + config.Id.ValueString() + "\")") + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +// End of section. //template:end read diff --git a/internal/provider/data_source_catalystcenter_fabric_l2_handoff_test.go b/internal/provider/data_source_catalystcenter_fabric_l2_handoff_test.go new file mode 100644 index 0000000..76f1486 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_fabric_l2_handoff_test.go @@ -0,0 +1,91 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package provider + +// Section below is generated&owned by "gen/generator.go". //template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +// End of section. //template:end imports + +// Section below is generated&owned by "gen/generator.go". //template:begin testAccDataSource +func TestAccDataSourceCcFabricL2Handoff(t *testing.T) { + if os.Getenv("SDA") == "" { + t.Skip("skipping test, set environment variable SDA") + } + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_fabric_l2_handoff.test", "network_device_id", "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_fabric_l2_handoff.test", "interface_name", "GigabitEthernet1/0/4")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_fabric_l2_handoff.test", "internal_vlan_id", "300")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_fabric_l2_handoff.test", "external_vlan_id", "400")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcFabricL2HandoffPrerequisitesConfig + testAccDataSourceCcFabricL2HandoffConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +// End of section. //template:end testAccDataSource + +// Section below is generated&owned by "gen/generator.go". //template:begin testPrerequisites +const testAccDataSourceCcFabricL2HandoffPrerequisitesConfig = ` +resource "catalystcenter_area" "test" { + name = "Area1" + parent_name = "Global" +} +resource "catalystcenter_fabric_site" "test" { + site_id = catalystcenter_area.test.id + pub_sub_enabled = false + authentication_profile_name = "No Authentication" + depends_on = [catalystcenter_area.test] +} + +` + +// End of section. //template:end testPrerequisites + +// Section below is generated&owned by "gen/generator.go". //template:begin testAccDataSourceConfig +func testAccDataSourceCcFabricL2HandoffConfig() string { + config := `resource "catalystcenter_fabric_l2_handoff" "test" {` + "\n" + config += ` network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1"` + "\n" + config += ` fabric_id = catalystcenter_fabric_site.test.id` + "\n" + config += ` interface_name = "GigabitEthernet1/0/4"` + "\n" + config += ` internal_vlan_id = 300` + "\n" + config += ` external_vlan_id = 400` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_fabric_l2_handoff" "test" { + id = catalystcenter_fabric_l2_handoff.test.id + network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1" + fabric_id = catalystcenter_fabric_site.test.id + } + ` + return config +} + +// End of section. //template:end testAccDataSourceConfig diff --git a/internal/provider/model_catalystcenter_fabric_l2_handoff.go b/internal/provider/model_catalystcenter_fabric_l2_handoff.go new file mode 100644 index 0000000..f58c28a --- /dev/null +++ b/internal/provider/model_catalystcenter_fabric_l2_handoff.go @@ -0,0 +1,159 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package provider + +// Section below is generated&owned by "gen/generator.go". //template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// End of section. //template:end imports + +// Section below is generated&owned by "gen/generator.go". //template:begin types +type FabricL2Handoff struct { + Id types.String `tfsdk:"id"` + NetworkDeviceId types.String `tfsdk:"network_device_id"` + FabricId types.String `tfsdk:"fabric_id"` + InterfaceName types.String `tfsdk:"interface_name"` + InternalVlanId types.Int64 `tfsdk:"internal_vlan_id"` + ExternalVlanId types.Int64 `tfsdk:"external_vlan_id"` +} + +// End of section. //template:end types + +// Section below is generated&owned by "gen/generator.go". //template:begin getPath +func (data FabricL2Handoff) getPath() string { + return "/dna/intent/api/v1/sda/fabricDevices/layer2Handoffs" +} + +// End of section. //template:end getPath + +// Section below is generated&owned by "gen/generator.go". //template:begin getPathDelete + +// End of section. //template:end getPathDelete + +// Section below is generated&owned by "gen/generator.go". //template:begin toBody +func (data FabricL2Handoff) toBody(ctx context.Context, state FabricL2Handoff) string { + body := "" + put := false + if state.Id.ValueString() != "" { + put = true + body, _ = sjson.Set(body, "0.id", state.Id.ValueString()) + } + _ = put + if !data.NetworkDeviceId.IsNull() { + body, _ = sjson.Set(body, "0.networkDeviceId", data.NetworkDeviceId.ValueString()) + } + if !data.FabricId.IsNull() { + body, _ = sjson.Set(body, "0.fabricId", data.FabricId.ValueString()) + } + if !data.InterfaceName.IsNull() { + body, _ = sjson.Set(body, "0.interfaceName", data.InterfaceName.ValueString()) + } + if !data.InternalVlanId.IsNull() { + body, _ = sjson.Set(body, "0.internalVlanId", data.InternalVlanId.ValueInt64()) + } + if !data.ExternalVlanId.IsNull() { + body, _ = sjson.Set(body, "0.externalVlanId", data.ExternalVlanId.ValueInt64()) + } + return body +} + +// End of section. //template:end toBody + +// Section below is generated&owned by "gen/generator.go". //template:begin fromBody +func (data *FabricL2Handoff) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("networkDeviceId"); value.Exists() { + data.NetworkDeviceId = types.StringValue(value.String()) + } else { + data.NetworkDeviceId = types.StringNull() + } + if value := res.Get("fabricId"); value.Exists() { + data.FabricId = types.StringValue(value.String()) + } else { + data.FabricId = types.StringNull() + } + if value := res.Get("interfaceName"); value.Exists() { + data.InterfaceName = types.StringValue(value.String()) + } else { + data.InterfaceName = types.StringNull() + } + if value := res.Get("internalVlanId"); value.Exists() { + data.InternalVlanId = types.Int64Value(value.Int()) + } else { + data.InternalVlanId = types.Int64Null() + } + if value := res.Get("externalVlanId"); value.Exists() { + data.ExternalVlanId = types.Int64Value(value.Int()) + } else { + data.ExternalVlanId = types.Int64Null() + } +} + +// End of section. //template:end fromBody + +// Section below is generated&owned by "gen/generator.go". //template:begin updateFromBody +func (data *FabricL2Handoff) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("networkDeviceId"); value.Exists() && !data.NetworkDeviceId.IsNull() { + data.NetworkDeviceId = types.StringValue(value.String()) + } else { + data.NetworkDeviceId = types.StringNull() + } + if value := res.Get("fabricId"); value.Exists() && !data.FabricId.IsNull() { + data.FabricId = types.StringValue(value.String()) + } else { + data.FabricId = types.StringNull() + } + if value := res.Get("interfaceName"); value.Exists() && !data.InterfaceName.IsNull() { + data.InterfaceName = types.StringValue(value.String()) + } else { + data.InterfaceName = types.StringNull() + } + if value := res.Get("internalVlanId"); value.Exists() && !data.InternalVlanId.IsNull() { + data.InternalVlanId = types.Int64Value(value.Int()) + } else { + data.InternalVlanId = types.Int64Null() + } + if value := res.Get("externalVlanId"); value.Exists() && !data.ExternalVlanId.IsNull() { + data.ExternalVlanId = types.Int64Value(value.Int()) + } else { + data.ExternalVlanId = types.Int64Null() + } +} + +// End of section. //template:end updateFromBody + +// Section below is generated&owned by "gen/generator.go". //template:begin isNull +func (data *FabricL2Handoff) isNull(ctx context.Context, res gjson.Result) bool { + if !data.InterfaceName.IsNull() { + return false + } + if !data.InternalVlanId.IsNull() { + return false + } + if !data.ExternalVlanId.IsNull() { + return false + } + return true +} + +// End of section. //template:end isNull diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 10c126e..4f4db7d 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -256,6 +256,7 @@ func (p *CcProvider) Resources(ctx context.Context) []func() resource.Resource { NewDiscoveryResource, NewFabricAuthenticationProfileResource, NewFabricDeviceResource, + NewFabricL2HandoffResource, NewFabricL3HandoffIPTransitResource, NewFabricProvisionDeviceResource, NewFabricSiteResource, @@ -308,6 +309,7 @@ func (p *CcProvider) DataSources(ctx context.Context) []func() datasource.DataSo NewDiscoveryDataSource, NewFabricAuthenticationProfileDataSource, NewFabricDeviceDataSource, + NewFabricL2HandoffDataSource, NewFabricL3HandoffIPTransitDataSource, NewFabricProvisionDeviceDataSource, NewFabricSiteDataSource, diff --git a/internal/provider/resource_catalystcenter_fabric_l2_handoff.go b/internal/provider/resource_catalystcenter_fabric_l2_handoff.go new file mode 100644 index 0000000..e76770c --- /dev/null +++ b/internal/provider/resource_catalystcenter_fabric_l2_handoff.go @@ -0,0 +1,277 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package provider + +// Section below is generated&owned by "gen/generator.go". //template:begin imports +import ( + "context" + "fmt" + "net/url" + "strconv" + "strings" + + "github.com/CiscoDevNet/terraform-provider-catalystcenter/internal/provider/helpers" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +// End of section. //template:end imports + +// Section below is generated&owned by "gen/generator.go". //template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &FabricL2HandoffResource{} +var _ resource.ResourceWithImportState = &FabricL2HandoffResource{} + +func NewFabricL2HandoffResource() resource.Resource { + return &FabricL2HandoffResource{} +} + +type FabricL2HandoffResource struct { + client *cc.Client +} + +func (r *FabricL2HandoffResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_fabric_l2_handoff" +} + +func (r *FabricL2HandoffResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("Manages Layer 2 Handoffs in Fabric Devices").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "network_device_id": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Network device ID of the fabric device").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "fabric_id": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("ID of the fabric this device belongs to").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "interface_name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Interface name of the layer 2 handoff. E.g., GigabitEthernet1/0/4").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "internal_vlan_id": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("VLAN number associated with this fabric. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094)").String, + Required: true, + PlanModifiers: []planmodifier.Int64{ + int64planmodifier.RequiresReplace(), + }, + }, + "external_vlan_id": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("External VLAN number into which the fabric must be extended. Allowed VLAN range is 2-4094 except for reserved vlans (1, 1002-1005, 2046, 4094)").String, + Required: true, + PlanModifiers: []planmodifier.Int64{ + int64planmodifier.RequiresReplace(), + }, + }, + }, + } +} + +func (r *FabricL2HandoffResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +// End of section. //template:end model + +// Section below is generated&owned by "gen/generator.go". //template:begin create +func (r *FabricL2HandoffResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan FabricL2Handoff + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, FabricL2Handoff{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + params += "?networkDeviceId=" + url.QueryEscape(plan.NetworkDeviceId.ValueString()) + "&fabricId=" + url.QueryEscape(plan.FabricId.ValueString()) + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.#(internalVlanId==\"" + strconv.FormatInt(plan.InternalVlanId.ValueInt64(), 10) + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +// End of section. //template:end create + +// Section below is generated&owned by "gen/generator.go". //template:begin read +func (r *FabricL2HandoffResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state FabricL2Handoff + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + params += "?networkDeviceId=" + url.QueryEscape(state.NetworkDeviceId.ValueString()) + "&fabricId=" + url.QueryEscape(state.FabricId.ValueString()) + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + res = res.Get("response.#(id==\"" + state.Id.ValueString() + "\")") + + // If every attribute is set to null we are dealing with an import operation and therefore reading all attributes + if state.isNull(ctx, res) { + state.fromBody(ctx, res) + } else { + state.updateFromBody(ctx, res) + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +// End of section. //template:end read + +// Section below is generated&owned by "gen/generator.go". //template:begin update +func (r *FabricL2HandoffResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state FabricL2Handoff + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + res, err := r.client.Put(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +// End of section. //template:end update + +// Section below is generated&owned by "gen/generator.go". //template:begin delete +func (r *FabricL2HandoffResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state FabricL2Handoff + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + url.QueryEscape(state.Id.ValueString())) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +// End of section. //template:end delete + +// Section below is generated&owned by "gen/generator.go". //template:begin import +func (r *FabricL2HandoffResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + idParts := strings.Split(req.ID, ",") + + if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { + resp.Diagnostics.AddError( + "Unexpected Import Identifier", + fmt.Sprintf("Expected import identifier with format: ,,. Got: %q", req.ID), + ) + return + } + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("network_device_id"), idParts[0])...) + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("fabric_id"), idParts[1])...) + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), idParts[2])...) +} + +// End of section. //template:end import diff --git a/internal/provider/resource_catalystcenter_fabric_l2_handoff_test.go b/internal/provider/resource_catalystcenter_fabric_l2_handoff_test.go new file mode 100644 index 0000000..7606554 --- /dev/null +++ b/internal/provider/resource_catalystcenter_fabric_l2_handoff_test.go @@ -0,0 +1,104 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package provider + +// Section below is generated&owned by "gen/generator.go". //template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +// End of section. //template:end imports + +// Section below is generated&owned by "gen/generator.go". //template:begin testAcc +func TestAccCcFabricL2Handoff(t *testing.T) { + if os.Getenv("SDA") == "" { + t.Skip("skipping test, set environment variable SDA") + } + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_fabric_l2_handoff.test", "network_device_id", "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_fabric_l2_handoff.test", "interface_name", "GigabitEthernet1/0/4")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_fabric_l2_handoff.test", "internal_vlan_id", "300")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_fabric_l2_handoff.test", "external_vlan_id", "400")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcFabricL2HandoffPrerequisitesConfig + testAccCcFabricL2HandoffConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcFabricL2HandoffPrerequisitesConfig + testAccCcFabricL2HandoffConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +// End of section. //template:end testAcc + +// Section below is generated&owned by "gen/generator.go". //template:begin testPrerequisites +const testAccCcFabricL2HandoffPrerequisitesConfig = ` +resource "catalystcenter_area" "test" { + name = "Area1" + parent_name = "Global" +} +resource "catalystcenter_fabric_site" "test" { + site_id = catalystcenter_area.test.id + pub_sub_enabled = false + authentication_profile_name = "No Authentication" + depends_on = [catalystcenter_area.test] +} + +` + +// End of section. //template:end testPrerequisites + +// Section below is generated&owned by "gen/generator.go". //template:begin testAccConfigMinimal +func testAccCcFabricL2HandoffConfig_minimum() string { + config := `resource "catalystcenter_fabric_l2_handoff" "test" {` + "\n" + config += ` network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1"` + "\n" + config += ` fabric_id = catalystcenter_fabric_site.test.id` + "\n" + config += ` interface_name = "GigabitEthernet1/0/4"` + "\n" + config += ` internal_vlan_id = 300` + "\n" + config += ` external_vlan_id = 400` + "\n" + config += `}` + "\n" + return config +} + +// End of section. //template:end testAccConfigMinimal + +// Section below is generated&owned by "gen/generator.go". //template:begin testAccConfigAll +func testAccCcFabricL2HandoffConfig_all() string { + config := `resource "catalystcenter_fabric_l2_handoff" "test" {` + "\n" + config += ` network_device_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1"` + "\n" + config += ` fabric_id = catalystcenter_fabric_site.test.id` + "\n" + config += ` interface_name = "GigabitEthernet1/0/4"` + "\n" + config += ` internal_vlan_id = 300` + "\n" + config += ` external_vlan_id = 400` + "\n" + config += `}` + "\n" + return config +} + +// End of section. //template:end testAccConfigAll diff --git a/templates/guides/changelog.md.tmpl b/templates/guides/changelog.md.tmpl index f399dd5..1e0bc24 100644 --- a/templates/guides/changelog.md.tmpl +++ b/templates/guides/changelog.md.tmpl @@ -9,6 +9,7 @@ description: |- ## 0.1.10 (unreleased) +- Add `fabric_l2_handoff` resource and data source - BREAKING CHANGE: Modified `wireless_profile` resource to use `/intent/api/v1/wirelessProfiles` API endpoint, this resource now only works with Catalyst Center version 2.3.7.6+ - Add `wireless_device_provision` resource - Add `fabric_provision_device` resource and data source