Skip to content

feat: add support for status pages [sc-23757] #309

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

Merged
merged 6 commits into from
Apr 9, 2025

Conversation

sorccu
Copy link
Contributor

@sorccu sorccu commented Apr 4, 2025

This PR adds new resources for status pages and status page services.

Needs checkly/checkly-go-sdk#131.

Affected Components

  • Resources
  • Test
  • Docs
  • Tooling
  • Other

Pre-Requisites

  • Terraform code is formatted with terraform fmt
  • Go code is formatted with go fmt
  • plan & apply command of demo/main.tf file do not produce diffs

Notes for the Reviewer

Resolves #[issue-number]

New Dependency Submission

Copy link

coderabbitai bot commented Apr 4, 2025

Walkthrough

This pull request implements new functionality in the Checkly provider by adding two new Terraform resources for managing status pages and associated services. It introduces new Go files that define schemas and CRUD operations along with helper functions. Acceptance tests have been added to validate required fields and behavior for these resources. New documentation files and example configurations are provided to guide users in configuring these resources. Additionally, the Checkly Go SDK dependency is updated to a newer version.

Changes

Files Change Summary
checkly/provider.go Added new resource entries: "checkly_status_page": resourceStatusPage() and "checkly_status_page_service": resourceStatusPageService() to the provider's resources map.
checkly/resource_status_page.go
checkly/resource_status_page_service.go
Introduced two new Go files implementing Terraform resources with schema definitions and CRUD operations (create, read, update, delete) for managing status pages and status page services.
checkly/resource_status_page_test.go
checkly/resource_status_page_service_test.go
Added new acceptance test files to validate required fields, configuration correctness, and error handling for the new resources.
docs/.../status_page.md
docs/.../status_page_service.md
Created new documentation files detailing resource schemas, attributes, and example usage for status pages and status page services.
examples/.../resource.tf (in both checkly_status_page and checkly_status_page_service folders) Added new example Terraform configuration files demonstrating resource usage and inter-resource dependencies for status pages and status page services.
go.mod Updated dependency version of github.com/checkly/checkly-go-sdk from v1.10.0 to v1.11.0.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented Apr 4, 2025

Terraform Format and Style 🖌success

Format Output

@sorccu sorccu marked this pull request as ready for review April 9, 2025 07:59
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (14)
examples/resources/checkly_status_page_service/resource.tf (1)

1-7: Implementation examples are minimal but functional

The example demonstrates basic usage by creating two status page services. This is sufficient for showing how to use the resource with its required attributes.

However, consider enhancing the example to show:

  1. How this resource relates to the checkly_status_page resource
  2. Any optional attributes that might be useful for users
docs/resources/status_page_service.md (1)

11-12: Add additional context about the resource

This section could benefit from a description of what a status page service is, how it's used, and how it relates to other resources like status pages and checks.

Consider adding content like:

Status page services allow you to group related checks under a common service name that will be displayed on your status pages. Each service aggregates the status of its associated checks to show an overall health status.
examples/resources/checkly_status_page/resource.tf (1)

9-25: Good example, but consider showing more optional attributes.

The status page resource example clearly demonstrates the core structure with required attributes and the card/service_attachment relationship. However, it could be more informative to showcase additional optional attributes like custom_domain, logo, or favicon that are mentioned in the documentation.

 resource "checkly_status_page" "example" {
   name          = "Example Application"
   url           = "my-example-status-page"
   default_theme = "DARK"
+  logo          = "https://example.org/logo.png"
+  favicon       = "https://example.org/favicon.png"
+  redirect_to   = "https://example.org"

   card {
     name = "Services"
checkly/resource_status_page_service_test.go (1)

20-37: Consider adding update/delete test scenarios.

The happy path test effectively verifies that a properly configured resource works as expected. However, to ensure complete coverage, consider adding test cases for resource updates and deletions. This would validate the full CRUD lifecycle.

 func TestAccStatusPageServiceHappyPath(t *testing.T) {
 	accTestCase(t, []resource.TestStep{
 		{
 			Config: `
 				resource "checkly_status_page_service" "test" {
 					name = "foo"
 				}
 			`,
 			Check: resource.ComposeTestCheckFunc(
 				resource.TestCheckResourceAttr(
 					"checkly_status_page_service.test",
 					"name",
 					"foo",
 				),
 			),
 		},
+		{
+			Config: `
+				resource "checkly_status_page_service" "test" {
+					name = "bar"
+				}
+			`,
+			Check: resource.ComposeTestCheckFunc(
+				resource.TestCheckResourceAttr(
+					"checkly_status_page_service.test",
+					"name",
+					"bar",
+				),
+			),
+		},
 	})
 }
docs/resources/status_page.md (2)

1-7: Add a meaningful description in the frontmatter.

The description field in the frontmatter is empty. Consider adding a concise description that explains the purpose of status pages within the Checkly ecosystem.

 description: |-
-  
+  Manages a Checkly status page that displays the health of your monitored services.

56-56: Enhance the documentation of allowed values.

For the default_theme attribute, the possible values (AUTO, DARK, and LIGHT) are mentioned, but it would be helpful to explain what each theme represents and how the AUTO option behaves.

- `default_theme` (String) Possible values are `AUTO`, `DARK`, and `LIGHT`. (Default `AUTO`).
+ `default_theme` (String) Sets the color theme of the status page. Possible values are `AUTO` (adapts to user's system preferences), `DARK` (dark mode regardless of system settings), and `LIGHT` (light mode regardless of system settings). Defaults to `AUTO`.
checkly/resource_status_page_service.go (3)

13-30: Resource schema definition looks solid.

You have properly defined the schema with a required name field. Consider whether additional validations or constraints (e.g., minimum length or a regex pattern) are necessary to prevent invalid values for the name field.


59-73: Fragile 404 detection logic.

Using strings.Contains(err.Error(), "404") to detect a 404 might be brittle if the error message changes. Consider using a typed or status code-based check from the checkly-go-sdk (if available), or verifying the error type to reliably detect 404 conditions.


90-98: Delete function is standard.

If DeleteStatusPageService returns a 404 for already-deleted items, you can optionally handle that scenario similarly to the Read function to avoid errors for missing resources.

checkly/resource_status_page.go (5)

13-32: Schema definition for name and url is well-structured.

Both fields are required, which is logical for a status page. Consider adding a light URL validation function for "url" to guard against invalid inputs.


33-52: Custom domain validation is mostly sufficient.

Though blocking domains ending with example.com and related TLDs may be a placeholder, consider exploring a more robust domain pattern check if needed.


88-120: Card schema requires at least one card.

If allowing zero cards is a possibility, consider making the field optional or setting MinItems to zero. Otherwise, this is a valid approach if at least one card is mandatory in all status pages.


220-234: Similar 404 detection concern.

Like the service resource, this code checks strings.Contains(err.Error(), "404"). Consider using a more robust typed error check if the SDK or standard library supports it.


251-259: Delete function may benefit from consistent 404 logic.

You might optionally catch a 404 error and allow Terraform to treat it as a successful delete.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c213e3d and b8133f6.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (10)
  • checkly/provider.go (1 hunks)
  • checkly/resource_status_page.go (1 hunks)
  • checkly/resource_status_page_service.go (1 hunks)
  • checkly/resource_status_page_service_test.go (1 hunks)
  • checkly/resource_status_page_test.go (1 hunks)
  • docs/resources/status_page.md (1 hunks)
  • docs/resources/status_page_service.md (1 hunks)
  • examples/resources/checkly_status_page/resource.tf (1 hunks)
  • examples/resources/checkly_status_page_service/resource.tf (1 hunks)
  • go.mod (1 hunks)
🔇 Additional comments (26)
go.mod (1)

7-7:

✅ Verification successful

Dependency update to support status page functionality

The update to checkly-go-sdk v1.11.0 is necessary to support the new status page resources being added in this PR. Since the PR description mentions this work is dependent on checkly-go-sdk PR #131, we should ensure that PR has been merged and the v1.11.0 release is published before merging this PR.


🏁 Script executed:

#!/bin/bash
# Verify that the v1.11.0 tag exists in the checkly-go-sdk repository
curl -s https://api.github.com/repos/checkly/checkly-go-sdk/tags | grep -A 2 "v1.11.0"

# Check if PR #131 has been merged
curl -s https://api.github.com/repos/checkly/checkly-go-sdk/pulls/131 | grep -E '"state": "(open|closed)"'

Length of output: 512


Status page dependency verified: checkly-go-sdk v1.11.0 confirmed

This dependency update is valid and supports the new status page functionality as described in the PR.

docs/resources/status_page_service.md (1)

25-34:

✅ Verification successful

Schema documentation is minimal

The schema only documents the required name attribute and the read-only id. If there are any optional attributes or relations to other resources, they should be documented here as well.


🏁 Script executed:

#!/bin/bash
# Check for additional attributes in the resource implementation
grep -r "Schema:" -A 50 checkly/resource_status_page_service.go | grep -A 5 "\".*\": {"

Length of output: 213


Schema documentation accuracy verified

After reviewing the resource implementation in checkly/resource_status_page_service.go, only the required name attribute (with its corresponding properties) is defined—the read-only id is documented separately in the generated schema. There are no optional attributes or relationships present that require additional documentation. The current documentation in docs/resources/status_page_service.md accurately reflects the implemented schema.

checkly/provider.go (1)

47-48:

✅ Verification successful

Successfully added new resources to the provider

The new status page resources have been properly added to the ResourcesMap, making them available for use in Terraform configurations.

We should verify that the referenced resource functions (resourceStatusPage() and resourceStatusPageService()) are properly implemented in their respective files.


🏁 Script executed:

#!/bin/bash
# Verify that the resource functions exist
grep -r "func resourceStatusPage()" --include="*.go" .
grep -r "func resourceStatusPageService()" --include="*.go" .

# Check for the schemas and CRUD functions in the implementation
grep -r "Create:" --include="resource_status_page*.go" .
grep -r "Read:" --include="resource_status_page*.go" .
grep -r "Update:" --include="resource_status_page*.go" .
grep -r "Delete:" --include="resource_status_page*.go" .

Length of output: 2258


Resource Implementation Verified: New Status Page Resources are Correctly Added

The verification confirms that the resource functions exist and their respective implementations correctly include all necessary CRUD operations.

  • checkly/resource_status_page.go: Contains the resourceStatusPage() implementation with valid definitions for Create, Read, Update, and Delete.
  • checkly/resource_status_page_service.go: Contains the resourceStatusPageService() implementation along with all CRUD functions.

The new status page resources are properly integrated and available for use in Terraform configurations.

examples/resources/checkly_status_page/resource.tf (1)

1-7: Clear and concise service definitions.

The service resource definitions are simple and straightforward, demonstrating the minimal required configuration. This helps users understand the basic usage pattern.

checkly/resource_status_page_service_test.go (2)

1-9: LGTM: Standard imports setup.

The package declaration and imports follow Go standard practices.


10-18: Required field validation test is properly implemented.

The test correctly verifies that the resource requires a "name" attribute by expecting an appropriate error message when it's missing.

docs/resources/status_page.md (1)

15-41: Complete and helpful usage example.

The example in the documentation provides clear guidance on how to create and configure status page resources, demonstrating the relationship between status pages and services.

checkly/resource_status_page_test.go (4)

10-27: Well-structured test for required fields.

This test properly validates that all required fields (name, url, and at least one card block) are enforced by the resource.


29-50: Effective test for nested required fields.

The test correctly validates that the service_id attribute is required in service attachments, ensuring proper configuration of nested blocks.


52-191: Comprehensive happy path testing with all attributes.

This test thoroughly validates both minimal and complete configurations of the status page resource, including all optional attributes. The step-based approach effectively tests updates as well.


193-232: Domain validation test is well-implemented, but documentation should be improved.

The test for unsupported custom domains is comprehensive and uses a clean approach to test multiple domains. However, these domain restrictions are not clearly documented in the schema section of the documentation.

Please update the documentation to clearly indicate which domains are not supported. You can add this information to the custom_domain attribute description in the documentation.

- `custom_domain` (String) A custom user domain, e.g. "status.example.com". See the docs on updating your DNS and SSL usage.
+ `custom_domain` (String) A custom user domain, e.g. "status.mycompany.com". Common domains like example.com, example.net, example.org, and their subdomains are not supported. See the docs on updating your DNS and SSL usage.
checkly/resource_status_page_service.go (5)

1-12: No issues found at file initialization.

The package declaration and imports follow standard Go conventions for a Terraform provider.


32-45: Create function aligns with Terraform patterns.

The creation logic includes a translation from schema to the SDK type and ends with a Read call to refresh the state. This is a standard and correct Terraform pattern.


47-52: Mapping resource data is straightforward.

The function accurately extracts the single name field. No further action needed.


54-57: Resource data population is correct.

Properly assigns the name field back to Terraform’s state, and no issues stand out.


75-88: Update function looks good.

Similar to the create function, you correctly translate resource data and call the Read function afterward. This approach is consistent with Terraform’s best practices.

checkly/resource_status_page.go (10)

1-12: Initial declarations are fine.

No concerns regarding package naming or imports.


53-87: Optional fields and default theme are correctly handled.

Setting "AUTO" as the default theme with validation for "DARK" and "LIGHT" is properly implemented.


122-135: Create function follows standard Terraform patterns.

Mapping data, making the API call, and finalizing with Read is the expected Terraform workflow.


137-149: Resource data translation is clear.

All fields are mapped directly from Terraform to the Checkly SDK. If the API enforces a specific format for URLs, consider adding a validation function or verifying through a typed error.


151-166: Status page cards mapping is straightforward.

Each card includes a list of service attachments. No issues identified.


168-179: List conversion function is correct.

Populating the Terraform schema from the native SDK structure is well-formatted and consistent with a typical Terraform approach.


181-194: Service attachments successfully translated.

Mapping the service_id from Terraform to the SDK is simple and effective.


196-206: Reverse conversion of service attachments is fine.

Again, consistent approach for bridging the Terraform schema with the Checkly SDK.


208-218: Resource data population is properly handled.

All relevant fields, including theme and cards, are updated in the state after reading from the API.


236-249: Update function approach is correct.

The resource is re-read into state post-update, in line with Terraform norms.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
checkly/resource_status_page_service.go (3)

49-54: Consider adding validation for the name field.

The translation function looks good, but consider adding validation for the name field if there are specific constraints on what constitutes a valid name for a status page service.

func statusPageServiceFromResourceData(d *schema.ResourceData) (checkly.StatusPageService, error) {
+	name := d.Get("name").(string)
+	if name == "" {
+		return checkly.StatusPageService{}, fmt.Errorf("name cannot be empty")
+	}
	return checkly.StatusPageService{
		ID:   d.Id(),
-		Name: d.Get("name").(string),
+		Name: name,
	}, nil
}

61-75: Improve error handling for resource not found.

The current approach of checking for "404" in the error message is brittle and may break if error message formats change. Consider using a more robust method if the SDK provides one.

func resourceStatusPageServiceRead(d *schema.ResourceData, client interface{}) error {
	ctx, cancel := context.WithTimeout(context.Background(), apiCallTimeout())
	defer cancel()
	service, err := client.(checkly.Client).GetStatusPageService(ctx, d.Id())
	if err != nil {
-		if strings.Contains(err.Error(), "404") {
+		// Check if the SDK provides a more robust way to check for not found errors
+		// For example: if errors.Is(err, checkly.ErrNotFound) {
+		if strings.Contains(err.Error(), "404") {
			//if resource is deleted remotely, then mark it as
			//successfully gone by unsetting it's ID
			d.SetId("")
			return nil
		}
		return fmt.Errorf("resourceStatusPageServiceRead: API error: %w", err)
	}
	return resourceDataFromStatusPageService(service, d)
}

77-90: Setting ID in update may be redundant.

The update function sets the ID in the Terraform state, which might be redundant since it should already be set from creation or import. Consider removing this line unless there's a specific reason to keep it.

func resourceStatusPageServiceUpdate(d *schema.ResourceData, client interface{}) error {
	service, err := statusPageServiceFromResourceData(d)
	if err != nil {
		return fmt.Errorf("resourceStatusPageServiceUpdate: translation error: %w", err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), apiCallTimeout())
	defer cancel()
	_, err = client.(checkly.Client).UpdateStatusPageService(ctx, service.ID, service)
	if err != nil {
		return fmt.Errorf("resourceStatusPageServiceUpdate: API error: %w", err)
	}
-	d.SetId(service.ID)
	return resourceStatusPageServiceRead(d, client)
}
checkly/resource_status_page.go (1)

39-53: Consider expanding custom domain validation logic.

Currently, there is only a check for specific “example.*” suffixes. You might consider a more robust validation approach (e.g., via regex or domain syntax checks) if you want to ensure valid user-provided domains and prevent potential misconfigurations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b8133f6 and 64f2611.

📒 Files selected for processing (4)
  • checkly/resource_status_page.go (1 hunks)
  • checkly/resource_status_page_service.go (1 hunks)
  • docs/resources/status_page.md (1 hunks)
  • docs/resources/status_page_service.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/resources/status_page_service.md
  • docs/resources/status_page.md
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Matrix test (1.1.*)
  • GitHub Check: Matrix test (0.15.*)
  • GitHub Check: Analyze (go)
🔇 Additional comments (8)
checkly/resource_status_page_service.go (3)

13-32: Good resource schema implementation with clear description.

This resource schema for status page services is well-structured with appropriate CRUD functions and a clear description. The schema correctly defines the required 'name' field.


34-47: Resource creation function looks good.

The create function follows best practices with proper error wrapping, timeout management, and calling Read at the end to ensure state consistency.


92-100: Delete function implementation is clean and concise.

The delete function correctly handles the API call with proper timeout and error handling.

checkly/resource_status_page.go (5)

70-89: Validation for default_theme is clear and concise.

Your approach to restricting the default_theme values to AUTO, DARK, or LIGHT is well-structured and user-friendly. This ensures that only supported themes are passed to the API. Good job!


90-119: Validate the requirement of at least one card.

Requiring at least one card (MinItems: 1) is a strong constraint. Verify that this aligns with real usage scenarios. If users need the option to create an empty status page with no cards, consider removing or relaxing this requirement.


124-137: Creation logic looks solid.

The resource creation flow appears compliant with Terraform patterns, featuring an immediate read to synchronize state. Good use of timeouts and error handling ensures resilience against API delays.


139-151: Data translation utility is straightforward.

Your statusPageFromResourceData function cleanly transforms Terraform input into the SDK struct. This approach eases debugging and keeps your resource methods concise.


253-261: Deletion logic properly clears the Terraform resource ID.

Setting the resource ID to empty upon successful deletion is aligned with Terraform conventions, ensuring Terraform no longer tracks the resource.

@sorccu sorccu merged commit 24d52fa into main Apr 9, 2025
8 checks passed
@sorccu sorccu deleted the simokinnunen/sc-23757/tf-status-pages branch April 9, 2025 08:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant