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

Report: Add org_id attribute #923

Merged
merged 2 commits into from
Jun 2, 2023
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 docs/resources/report.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ resource "grafana_report" "test" {
- `include_table_csv` (Boolean) Whether to include a CSV file of table panel data. Defaults to `false`.
- `layout` (String) Layout of the report. Allowed values: `simple`, `grid`. Defaults to `grid`.
- `message` (String) Message to be sent in the report.
- `org_id` (String) The Organization ID. If not set, the Org ID defined in the provider block will be used.
- `orientation` (String) Orientation of the report. Allowed values: `landscape`, `portrait`. Defaults to `landscape`.
- `reply_to` (String) Reply-to email address of the report.
- `time_range` (Block List, Max: 1) Time range of the report. (see [below for nested schema](#nestedblock--time_range))
Expand Down
24 changes: 13 additions & 11 deletions internal/resources/grafana/resource_report.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func ResourceReport() *schema.Resource {
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"org_id": orgIDAttribute(),
"id": {
Type: schema.TypeString,
Computed: true,
Expand Down Expand Up @@ -226,7 +227,7 @@ func ResourceReport() *schema.Resource {
}

func CreateReport(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*common.Client).GrafanaAPI
client, orgID := ClientFromNewOrgResource(meta, d)

report, err := schemaToReport(client, d)
if err != nil {
Expand All @@ -238,13 +239,13 @@ func CreateReport(ctx context.Context, d *schema.ResourceData, meta interface{})
data, _ := json.Marshal(report)
return diag.Errorf("error creating the following report:\n%s\n%v", string(data), err)
}
d.SetId(strconv.FormatInt(id, 10))
d.SetId(MakeOrgResourceID(orgID, id))
return ReadReport(ctx, d, meta)
}

func ReadReport(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*common.Client).GrafanaAPI
id, err := strconv.ParseInt(d.Id(), 10, 64)
client, _, idStr := ClientFromExistingOrgResource(meta, d.Id())
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
return diag.FromErr(err)
}
Expand All @@ -270,6 +271,7 @@ func ReadReport(ctx context.Context, d *schema.ResourceData, meta interface{}) d
d.Set("include_table_csv", r.EnableCSV)
d.Set("layout", r.Options.Layout)
d.Set("orientation", r.Options.Orientation)
d.Set("org_id", strconv.FormatInt(r.OrgID, 10))

timeRange := r.Dashboards[0].TimeRange
if timeRange.From != "" {
Expand Down Expand Up @@ -304,17 +306,17 @@ func ReadReport(ctx context.Context, d *schema.ResourceData, meta interface{}) d
}

func UpdateReport(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*common.Client).GrafanaAPI

report, err := schemaToReport(client, d)
client, _, idStr := ClientFromExistingOrgResource(meta, d.Id())
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
return diag.FromErr(err)
}
id, err := strconv.Atoi(d.Id())

report, err := schemaToReport(client, d)
if err != nil {
return diag.FromErr(err)
}
report.ID = int64(id)
report.ID = id

if err := client.UpdateReport(report); err != nil {
data, _ := json.Marshal(report)
Expand All @@ -324,8 +326,8 @@ func UpdateReport(ctx context.Context, d *schema.ResourceData, meta interface{})
}

func DeleteReport(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*common.Client).GrafanaAPI
id, err := strconv.ParseInt(d.Id(), 10, 64)
client, _, idStr := ClientFromExistingOrgResource(meta, d.Id())
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
return diag.FromErr(err)
}
Expand Down
76 changes: 70 additions & 6 deletions internal/resources/grafana/resource_report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (

gapi "github.com/grafana/grafana-api-golang-client"
"github.com/grafana/terraform-provider-grafana/internal/common"
"github.com/grafana/terraform-provider-grafana/internal/resources/grafana"
"github.com/grafana/terraform-provider-grafana/internal/testutils"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
Expand Down Expand Up @@ -49,7 +51,7 @@ func TestAccResourceReport(t *testing.T) {
// Check that the ID and dashboard ID are the same as the first run
// This is a custom function to delay the report ID evaluation, because it is generated after the first run
return resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("grafana_report.test", "id", strconv.FormatInt(report.ID, 10)),
resource.TestCheckResourceAttr("grafana_report.test", "id", "0:"+strconv.FormatInt(report.ID, 10)), // <orgid>:<reportid> (0 being the default org)
resource.TestCheckResourceAttr("grafana_report.test", "dashboard_id", strconv.FormatInt(report.Dashboards[0].Dashboard.ID, 10)),
)(s)
},
Expand Down Expand Up @@ -118,6 +120,33 @@ func TestAccResourceReport_CreateFromDashboardID(t *testing.T) {
})
}

func TestAccResourceReport_InOrg(t *testing.T) {
testutils.CheckEnterpriseTestsEnabled(t)

var report gapi.Report
var org gapi.Org
name := acctest.RandStringFromCharSet(10, acctest.CharSetAlpha)

resource.ParallelTest(t, resource.TestCase{
ProviderFactories: testutils.ProviderFactories,
CheckDestroy: testAccReportCheckDestroy(&report),
Steps: []resource.TestStep{
{
Config: testAccReportCreateInOrg(name),
Check: resource.ComposeTestCheckFunc(
testAccReportCheckExists("grafana_report.test", &report),
resource.TestCheckResourceAttr("grafana_report.test", "dashboard_uid", "report-in-org"),

// Check that the dashboard is in the correct organization
resource.TestMatchResourceAttr("grafana_report.test", "id", nonDefaultOrgIDRegexp),
testAccOrganizationCheckExists("grafana_organization.test", &org),
checkResourceIsInOrg("grafana_report.test", "grafana_organization.test"),
),
},
},
})
}

func testAccReportCheckExists(rn string, report *gapi.Report) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[rn]
Expand All @@ -130,17 +159,24 @@ func testAccReportCheckExists(rn string, report *gapi.Report) resource.TestCheck
}

client := testutils.Provider.Meta().(*common.Client).GrafanaAPI
id, err := strconv.ParseInt(rs.Primary.ID, 10, 64)
orgID, reportIDStr := grafana.SplitOrgResourceID(rs.Primary.ID)
reportID, err := strconv.ParseInt(reportIDStr, 10, 64)
if err != nil {
return err
}

if id == 0 {
return fmt.Errorf("got a report id of 0")
// If the org ID is set, check that the report doesn't exist in the default org
if orgID > 0 {
report, err := client.Report(reportID)
if err == nil || report != nil {
return fmt.Errorf("expected no report with ID %s in default org but found one", reportIDStr)
}
client = client.WithOrgID(orgID)
}
gotReport, err := client.Report(id)

gotReport, err := client.Report(reportID)
if err != nil {
return fmt.Errorf("error getting report: %s", err)
return fmt.Errorf("error getting report: %w", err)
}

*report = *gotReport
Expand Down Expand Up @@ -180,3 +216,31 @@ resource "grafana_dashboard" "test" {
}
}
`

func testAccReportCreateInOrg(name string) string {
return fmt.Sprintf(`
resource "grafana_organization" "test" {
name = "%s"
}

resource "grafana_dashboard" "test" {
org_id = grafana_organization.test.id
config_json = <<EOD
{
"title": "Dashboard for report in org",
"uid": "report-in-org"
}
EOD
message = "initial commit."
}

resource "grafana_report" "test" {
org_id = grafana_organization.test.id
name = "my report"
dashboard_uid = grafana_dashboard.test.uid
recipients = ["some@email.com"]
schedule {
frequency = "hourly"
}
}`, name)
}