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

Added prometheus rule group namespace #21470

Merged
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
3 changes: 3 additions & 0 deletions .changelog/21470.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_prometheus_rule_group_namespace
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,7 @@ func Provider() *schema.Provider {

"aws_prometheus_workspace": prometheus.ResourceWorkspace(),
"aws_prometheus_alert_manager_definition": prometheus.ResourceAlertManagerDefinition(),
"aws_prometheus_rule_group_namespace": prometheus.ResourceRuleGroupNamespace(),

"aws_qldb_ledger": qldb.ResourceLedger(),

Expand Down
41 changes: 41 additions & 0 deletions internal/service/prometheus/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package prometheus

import (
"context"
"fmt"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/prometheusservice"
Expand Down Expand Up @@ -34,3 +36,42 @@ func FindAlertManagerDefinitionByID(ctx context.Context, conn *prometheusservice

return output.AlertManagerDefinition, nil
}

func nameAndWorkspaceIdFromRuleGroupNamespaceArn(arn string) (string, string, error) {
parts := strings.Split(arn, "/")
if len(parts) != 3 {
return "", "", fmt.Errorf("error reading Prometheus Rule Group Namespace expected the arn to be like: arn:PARTITION:aps:REGION:ACCOUNT:rulegroupsnamespace/IDstring/namespace_name but got: %s", arn)
}
return parts[2], parts[1], nil
}

func FindRuleGroupNamespaceByArn(ctx context.Context, conn *prometheusservice.PrometheusService, arn string) (*prometheusservice.RuleGroupsNamespaceDescription, error) {
name, workspaceId, err := nameAndWorkspaceIdFromRuleGroupNamespaceArn(arn)
if err != nil {
return nil, err
}

input := &prometheusservice.DescribeRuleGroupsNamespaceInput{
Name: aws.String(name),
WorkspaceId: aws.String(workspaceId),
}

output, err := conn.DescribeRuleGroupsNamespaceWithContext(ctx, input)

if tfawserr.ErrCodeEquals(err, prometheusservice.ErrCodeResourceNotFoundException) {
return nil, &resource.NotFoundError{
LastError: err,
LastRequest: input,
}
}

if err != nil {
return nil, err
}

if output == nil || output.RuleGroupsNamespace == nil {
return nil, tfresource.NewEmptyResultError(input)
}

return output.RuleGroupsNamespace, nil
}
144 changes: 144 additions & 0 deletions internal/service/prometheus/rule_group_namespace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package prometheus

import (
"context"
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/prometheusservice"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

func ResourceRuleGroupNamespace() *schema.Resource {
return &schema.Resource{
CreateContext: resourceRuleGroupNamespaceCreate,
ReadContext: resourceRuleGroupNamespaceRead,
UpdateContext: resourceRuleGroupNamespaceUpdate,
DeleteContext: resourceRuleGroupNamespaceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"data": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"workspace_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}

func resourceRuleGroupNamespaceCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).PrometheusConn

workspaceID := d.Get("workspace_id").(string)
name := d.Get("name").(string)
input := &prometheusservice.CreateRuleGroupsNamespaceInput{
Name: aws.String(name),
Data: []byte(d.Get("data").(string)),
WorkspaceId: aws.String(workspaceID),
}

log.Printf("[DEBUG] Creating Prometheus Rule Group Namespace: %s", input)
output, err := conn.CreateRuleGroupsNamespaceWithContext(ctx, input)

if err != nil {
return diag.FromErr(fmt.Errorf("error creating Prometheus Rule Group Namespace (%s) for workspace (%s): %w", name, workspaceID, err))
}

d.SetId(aws.StringValue(output.Arn))

if _, err := waitRuleGroupNamespaceCreated(ctx, conn, d.Id()); err != nil {
return diag.FromErr(fmt.Errorf("error waiting for Prometheus Rule Group Namespace (%s) create: %w", d.Id(), err))
}

return resourceRuleGroupNamespaceRead(ctx, d, meta)
}

func resourceRuleGroupNamespaceUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).PrometheusConn

input := &prometheusservice.PutRuleGroupsNamespaceInput{
Name: aws.String(d.Get("name").(string)),
Data: []byte(d.Get("data").(string)),
WorkspaceId: aws.String(d.Get("workspace_id").(string)),
}

log.Printf("[DEBUG] Updating Prometheus Rule Group Namespace: %s", input)
_, err := conn.PutRuleGroupsNamespaceWithContext(ctx, input)

if err != nil {
return diag.FromErr(fmt.Errorf("error updating Prometheus Rule Group Namespace (%s): %w", d.Id(), err))
}

if _, err := waitRuleGroupNamespaceUpdated(ctx, conn, d.Id()); err != nil {
return diag.FromErr(fmt.Errorf("error waiting for Prometheus Rule Group Namespace (%s) update: %w", d.Id(), err))
}

return resourceRuleGroupNamespaceRead(ctx, d, meta)
}

func resourceRuleGroupNamespaceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).PrometheusConn

rgn, err := FindRuleGroupNamespaceByArn(ctx, conn, d.Id())

if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] Prometheus Rule Group Namespace (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

if err != nil {
return diag.FromErr(fmt.Errorf("error reading Prometheus Rule Group Namespace (%s): %w", d.Id(), err))
}

d.Set("data", string(rgn.Data))
d.Set("name", rgn.Name)
_, workspaceID, err := nameAndWorkspaceIdFromRuleGroupNamespaceArn(d.Id())
if err != nil {
return diag.FromErr(err)
}
d.Set("workspace_id", workspaceID)

return nil
}

func resourceRuleGroupNamespaceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).PrometheusConn

log.Printf("[DEBUG] Deleting Prometheus Rule Group Namespace: (%s)", d.Id())
_, err := conn.DeleteRuleGroupsNamespaceWithContext(ctx, &prometheusservice.DeleteRuleGroupsNamespaceInput{
Name: aws.String(d.Get("name").(string)),
WorkspaceId: aws.String(d.Get("workspace_id").(string)),
})

if tfawserr.ErrCodeEquals(err, prometheusservice.ErrCodeResourceNotFoundException) {
return nil
}

if err != nil {
return diag.FromErr(fmt.Errorf("error deleting Prometheus Rule Group Namespace (%s): %w", d.Id(), err))
}

if _, err := waitRuleGroupNamespaceDeleted(ctx, conn, d.Id()); err != nil {
return diag.FromErr(fmt.Errorf("error waiting for Prometheus Rule Group Namespace (%s) delete: %w", d.Id(), err))
}

return nil
}
158 changes: 158 additions & 0 deletions internal/service/prometheus/rule_group_namespace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package prometheus_test

import (
"context"
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/prometheusservice"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tfprometheus "github.com/hashicorp/terraform-provider-aws/internal/service/prometheus"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

func TestAccPrometheusRuleGroupNamespace_basic(t *testing.T) {
resourceName := "aws_prometheus_rule_group_namespace.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(prometheusservice.EndpointsID, t) },
ErrorCheck: acctest.ErrorCheck(t, prometheusservice.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckAMPRuleGroupNamespaceDestroy,
Steps: []resource.TestStep{
{
Config: testAccAMPRuleGroupNamespace(defaultRuleGroupNamespace()),
Check: resource.ComposeTestCheckFunc(
testAccCheckRuleGroupNamespaceExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "data", defaultRuleGroupNamespace()),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccAMPRuleGroupNamespace(anotherRuleGroupNamespace()),
Check: resource.ComposeTestCheckFunc(
testAccCheckRuleGroupNamespaceExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "data", anotherRuleGroupNamespace()),
),
},
{
Config: testAccAMPRuleGroupNamespace(defaultRuleGroupNamespace()),
Check: resource.ComposeTestCheckFunc(
testAccCheckRuleGroupNamespaceExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "data", defaultRuleGroupNamespace()),
),
},
},
})
}

func TestAccPrometheusRuleGroupNamespace_disappears(t *testing.T) {
resourceName := "aws_prometheus_rule_group_namespace.test"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(prometheusservice.EndpointsID, t) },
ErrorCheck: acctest.ErrorCheck(t, prometheusservice.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckAMPRuleGroupNamespaceDestroy,
Steps: []resource.TestStep{
{
Config: testAccAMPRuleGroupNamespace(defaultRuleGroupNamespace()),
Check: resource.ComposeTestCheckFunc(
testAccCheckRuleGroupNamespaceExists(resourceName),
acctest.CheckResourceDisappears(acctest.Provider, tfprometheus.ResourceRuleGroupNamespace(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckRuleGroupNamespaceExists(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("No Prometheus Rule Group namspace ID is set")
}

conn := acctest.Provider.Meta().(*conns.AWSClient).PrometheusConn

_, err := tfprometheus.FindRuleGroupNamespaceByArn(context.TODO(), conn, rs.Primary.ID)

if err != nil {
return err
}

return nil
}
}

func testAccCheckAMPRuleGroupNamespaceDestroy(s *terraform.State) error {
conn := acctest.Provider.Meta().(*conns.AWSClient).PrometheusConn

for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_prometheus_rule_group_namespace" {
continue
}

_, err := tfprometheus.FindRuleGroupNamespaceByArn(context.TODO(), conn, rs.Primary.ID)

if tfresource.NotFound(err) {
continue
}

if err != nil {
return err
}

return fmt.Errorf("Prometheus Rule Group Namespace %s still exists", rs.Primary.ID)
}

return nil
}

func defaultRuleGroupNamespace() string {
return `
groups:
- name: test
rules:
- record: metric:recording_rule
expr: avg(rate(container_cpu_usage_seconds_total[5m]))
- name: alert-test
rules:
- alert: metric:alerting_rule
expr: avg(rate(container_cpu_usage_seconds_total[5m])) > 0
for: 2m
`
}

func anotherRuleGroupNamespace() string {
return `
groups:
- name: test
rules:
- record: metric:recording_rule
expr: avg(rate(container_cpu_usage_seconds_total[5m]))
`
}

func testAccAMPRuleGroupNamespace(data string) string {
return fmt.Sprintf(`
resource "aws_prometheus_workspace" "test" {
}
resource "aws_prometheus_rule_group_namespace" "test" {
workspace_id = aws_prometheus_workspace.test.id
name = "rules"
data = %[1]q
}
`, data)
}
16 changes: 16 additions & 0 deletions internal/service/prometheus/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@ func statusAlertManagerDefinition(ctx context.Context, conn *prometheusservice.P
}
}

func statusRuleGroupNamespace(ctx context.Context, conn *prometheusservice.PrometheusService, arn string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
output, err := FindRuleGroupNamespaceByArn(ctx, conn, arn)

if tfresource.NotFound(err) {
return nil, "", nil
}

if err != nil {
return nil, "", err
}

return output, aws.StringValue(output.Status.StatusCode), nil
}
}

// statusWorkspaceCreated fetches the Workspace and its Status.
func statusWorkspaceCreated(ctx context.Context, conn *prometheusservice.PrometheusService, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
Expand Down
Loading