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

azurerm_portal_dashboard - update dashboard name validation #16406

Merged
merged 12 commits into from
May 26, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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
87 changes: 74 additions & 13 deletions internal/services/portal/portal_dashboard_data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import (
"fmt"
"time"

"github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema"
"github.com/hashicorp/go-azure-helpers/resourcemanager/location"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tags"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)
Expand All @@ -27,8 +29,15 @@ func dataSourcePortalDashboard() *pluginsdk.Resource {
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
Optional: true,
ValidateFunc: validate.DashboardName,
ExactlyOneOf: []string{"name", "display_name"},
},
"display_name": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.StringIsNotEmpty,
ExactlyOneOf: []string{"name", "display_name"},
},
"resource_group_name": commonschema.ResourceGroupNameForDataSource(),
"location": commonschema.LocationComputed(),
Expand All @@ -46,31 +55,83 @@ func dataSourcePortalDashboard() *pluginsdk.Resource {
func dataSourcePortalDashboardRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Portal.DashboardsClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

id := parse.NewDashboardID(subscriptionId, resourceGroup, name)
resp, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("portal dashboard %q was not found in Resource Group %q", id.Name, id.ResourceGroup)
name := d.Get("name").(string)
displayName, displayNameOk := d.GetOk("display_name")
resourceGroup := d.Get("resource_group_name").(string)

var dashboard portal.Dashboard

if !displayNameOk {
var err error
dashboard, err = client.Get(ctx, resourceGroup, name)
if err != nil {
if utils.ResponseWasNotFound(dashboard.Response) {
return fmt.Errorf("portal Dashboard %q was not found in Resource Group %q", name, resourceGroup)
}
return fmt.Errorf("retrieving Portal Dashboard %q (Resource Group %q): %+v", name, resourceGroup, err)
}
} else {
dashboards := make([]portal.Dashboard, 0)

iterator, err := client.ListByResourceGroupComplete(ctx, resourceGroup)
if err != nil {
if utils.ResponseWasNotFound(iterator.Response().Response) {
return fmt.Errorf("no Portal Dashboards were found for Resource Group %q", resourceGroup)
}
return fmt.Errorf("getting list of Portal Dashboards (Resource Group %q): %+v", resourceGroup, err)
}

for iterator.NotDone() {
dashboard = iterator.Value()

found := false
for k, v := range dashboard.Tags {
if k == "hidden-title" && *v == displayName {
found = true
break
}
}

if found {
dashboards = append(dashboards, dashboard)
}
if err := iterator.NextWithContext(ctx); err != nil {
return err
}
}

if 1 > len(dashboards) {
return fmt.Errorf("no Portal Dashboards were found for Resource Group %q", resourceGroup)
}

if len(dashboards) > 1 {
return fmt.Errorf("multiple Portal Dashboards were found for Resource Group %q", resourceGroup)
}
return fmt.Errorf("retrieving Portal Dashboard %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)

dashboard = dashboards[0]
}

if dashboard.Name == nil {
return fmt.Errorf("portal Dashboard name is empty in Resource Group %s", resourceGroup)
}

id := parse.NewDashboardID(subscriptionId, resourceGroup, name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

both the resourceGroup and the name here will be empty when we're filtering by display name - making this ID invalid?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As resourceGroup is required property, so it won't be empty.

For name, while filtering by display_name, name would be empty. So I updated code to use *dashboard.Name since this property always has value when the resource is retrieved.


d.SetId(id.ID())

d.Set("name", id.Name)
d.Set("name", name)
d.Set("display_name", displayName)
d.Set("resource_group_name", id.ResourceGroup)
d.Set("location", location.NormalizeNilable(resp.Location))
d.Set("location", location.NormalizeNilable(dashboard.Location))

props, jsonErr := json.Marshal(resp.DashboardProperties)
props, jsonErr := json.Marshal(dashboard.DashboardProperties)
if jsonErr != nil {
return fmt.Errorf("parsing JSON for Portal Dashboard Properties: %+v", jsonErr)
}
d.Set("dashboard_properties", string(props))

return tags.FlattenAndSet(d, resp.Tags)
return tags.FlattenAndSet(d, dashboard.Tags)
}
31 changes: 31 additions & 0 deletions internal/services/portal/portal_dashboard_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ func TestAccDataSourcePortalDashboard_complete(t *testing.T) {
})
}

func TestAccDataSourcePortalDashboard_displayName(t *testing.T) {
data := acceptance.BuildTestData(t, "data.azurerm_portal_dashboard", "test")
r := PortalDashboardDataSource{}
data.DataSourceTest(t, []acceptance.TestStep{
{
Config: r.displayName(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).Key("display_name").HasValue("Test Display Name"),
),
},
})
}

func (PortalDashboardDataSource) basic(data acceptance.TestData) string {
resourceName := "azurerm_portal_dashboard"
if !features.ThreePointOhBeta() {
Expand Down Expand Up @@ -73,3 +86,21 @@ data "azurerm_portal_dashboard" "test" {
}
`, PortalDashboardResource{}.complete(data), resourceName)
}

func (PortalDashboardDataSource) displayName(data acceptance.TestData) string {
resourceName := "azurerm_portal_dashboard"
if !features.ThreePointOhBeta() {
resourceName = "azurerm_dashboard"
}
neil-yechenwei marked this conversation as resolved.
Show resolved Hide resolved
return fmt.Sprintf(`

%s

data "azurerm_portal_dashboard" "test" {
display_name = "Test Display Name"
resource_group_name = azurerm_resource_group.test.name

depends_on = ["%s.test"]
}
`, PortalDashboardResource{}.hiddenTitle(data), resourceName)
}
69 changes: 69 additions & 0 deletions internal/services/portal/portal_dashboard_resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ func TestAccPortalDashboard_complete(t *testing.T) {
})
}

func TestAccPortalDashboard_hiddenTitle(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_portal_dashboard", "test")
r := PortalDashboardResource{}
data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.hiddenTitle(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func (PortalDashboardResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := parse.DashboardID(state.ID)
if err != nil {
Expand Down Expand Up @@ -161,3 +175,58 @@ DASH
}
`, data.RandomInteger, data.Locations.Primary)
}

func (PortalDashboardResource) hiddenTitle(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}

resource "azurerm_resource_group" "test" {
name = "acctestRG-%d"
location = "%s"
}

resource "azurerm_portal_dashboard" "test" {
name = "my-test-dashboard"
resource_group_name = azurerm_resource_group.test.name
location = azurerm_resource_group.test.location
dashboard_properties = <<DASH
{
"lenses": {
"0": {
"order": 0,
"parts": {
"0": {
"position": {
"x": 0,
"y": 0,
"rowSpan": 2,
"colSpan": 3
},
"metadata": {
"inputs": [],
"type": "Extension/HubsExtension/PartType/MarkdownPart",
"settings": {
"content": {
"settings": {
"content": "## This is only a test :)",
"subtitle": "",
"title": "Test MD Tile"
}
}
}
}
}
}
}
}
}
DASH
neil-yechenwei marked this conversation as resolved.
Show resolved Hide resolved

tags = {
hidden-title = "Test Display Name"
}
}
`, data.RandomInteger, data.Locations.Primary)
}
4 changes: 2 additions & 2 deletions internal/services/portal/validate/dashboard_name.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import (
func DashboardName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)

if len(value) > 64 {
errors = append(errors, fmt.Errorf("%q may not exceed 64 characters in length", k))
if len(value) > 160 {
errors = append(errors, fmt.Errorf("%q may not exceed 160 characters in length", k))
}

// only alpanumeric and hyphens
Expand Down
60 changes: 60 additions & 0 deletions internal/services/portal/validate/dashboard_name_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package validate

import (
"strings"
"testing"
)

func TestDashboardName(t *testing.T) {
testData := []struct {
input string
expected bool
}{
{
input: "",
expected: false,
},
{
input: "hello",
expected: true,
},
{
input: "hello#",
expected: false,
},
{
input: "hello-",
expected: true,
},
{
input: "hello-world",
expected: true,
},
{
input: "hello9",
expected: true,
},
{
input: strings.Repeat("s", 159),
expected: true,
},
{
input: strings.Repeat("s", 160),
expected: true,
},
{
input: strings.Repeat("s", 161),
expected: false,
},
}

for _, v := range testData {
t.Logf("[DEBUG] Testing %q..", v.input)

_, errors := DashboardName(v.input, "name")
actual := len(errors) == 0
if v.expected != actual {
t.Fatalf("Expected %t but got %t", v.expected, actual)
}
}
}
6 changes: 4 additions & 2 deletions website/docs/d/portal_dashboard.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@ output "id" {

The following arguments are supported:

* `name` - (Required) Specifies the name of the shared Azure Portal Dashboard.

* `resource_group_name` - (Required) Specifies the name of the resource group the shared Azure Portal Dashboard is located in.

* `name` - (Optional) Specifies the name of the shared Azure Portal Dashboard.

* `display_name` - (Optional) Specifies the display name of the shared Azure Portal Dashboard.

## Attributes Reference

In addition to the Arguments listed above - the following Attributes are exported:
Expand Down