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_cost_anomaly_alert - New resource #19899

Merged
merged 9 commits into from
Jan 9, 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
245 changes: 245 additions & 0 deletions internal/services/costmanagement/anomaly_alert_resource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
package costmanagement

import (
"context"
"fmt"
"time"

"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-sdk/resource-manager/costmanagement/2022-06-01-preview/scheduledactions"
"github.com/hashicorp/terraform-provider-azurerm/internal/sdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/costmanagement/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/costmanagement/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)

var _ sdk.Resource = AnomalyAlertResource{}

type AnomalyAlertResource struct{}

func (AnomalyAlertResource) Arguments() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.CostAnomalyAlertName,
// action names can contain only alphanumeric characters and hyphens.
},

"display_name": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},

"email_subject": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 70),
},

"email_addresses": {
Type: pluginsdk.TypeSet,
Required: true,
MinItems: 1,
Elem: &pluginsdk.Schema{
Type: pluginsdk.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
},

"message": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 250),
},
}
}

func (AnomalyAlertResource) Attributes() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{}
}

func (AnomalyAlertResource) ModelObject() interface{} {
return nil
}

func (AnomalyAlertResource) ResourceType() string {
return "azurerm_cost_anomaly_alert"
}

func (r AnomalyAlertResource) Create() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
client := metadata.Client.CostManagement.ScheduledActionsClient
subscriptionId := metadata.Client.Account.SubscriptionId
id := scheduledactions.NewScopedScheduledActionID(fmt.Sprint("/subscriptions/", subscriptionId), metadata.ResourceData.Get("name").(string))

existing, err := client.GetByScope(ctx, id)
if err != nil && !response.WasNotFound(existing.HttpResponse) {
return fmt.Errorf("checking for presence of existing %s: %+v", id, err)
}
if !response.WasNotFound(existing.HttpResponse) {
return metadata.ResourceRequiresImport(r.ResourceType(), id)
}

emailAddressesRaw := metadata.ResourceData.Get("email_addresses").(*pluginsdk.Set).List()
emailAddresses := utils.ExpandStringSlice(emailAddressesRaw)

viewId := parse.NewAnomalyAlertViewID(subscriptionId, "ms:DailyAnomalyByResourceGroup")

schedule := scheduledactions.ScheduleProperties{
Frequency: scheduledactions.ScheduleFrequencyDaily,
}
schedule.SetEndDateAsTime(time.Now().AddDate(1, 0, 0))
schedule.SetStartDateAsTime(time.Now())

param := scheduledactions.ScheduledAction{
Kind: utils.ToPtr(scheduledactions.ScheduledActionKindInsightAlert),
Properties: &scheduledactions.ScheduledActionProperties{
DisplayName: metadata.ResourceData.Get("display_name").(string),
Status: scheduledactions.ScheduledActionStatusEnabled,
ViewId: viewId.ID(),
FileDestination: &scheduledactions.FileDestination{
FileFormats: &[]scheduledactions.FileFormat{},
},
Notification: scheduledactions.NotificationProperties{
Subject: metadata.ResourceData.Get("email_subject").(string),
Message: utils.String(metadata.ResourceData.Get("message").(string)),
To: *emailAddresses,
},
Schedule: schedule,
},
}
if _, err := client.CreateOrUpdateByScope(ctx, id, param); err != nil {
return fmt.Errorf("creating %s: %+v", id, err)
}

metadata.SetID(id)
return nil
},
}
}

func (r AnomalyAlertResource) Update() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
client := metadata.Client.CostManagement.ScheduledActionsClient

id, err := scheduledactions.ParseScopedScheduledActionID(metadata.ResourceData.Id())
if err != nil {
return err
}

resp, err := client.GetByScope(ctx, *id)
if err != nil {
return fmt.Errorf("reading %s: %+v", id, err)
}

if model := resp.Model; model != nil {
if model.ETag == nil {
return fmt.Errorf("add %s: etag was nil", *id)
}
}

emailAddressesRaw := metadata.ResourceData.Get("email_addresses").(*pluginsdk.Set).List()
emailAddresses := utils.ExpandStringSlice(emailAddressesRaw)

subscriptionId := metadata.Client.Account.SubscriptionId
viewId := parse.NewAnomalyAlertViewID(subscriptionId, "ms:DailyAnomalyByResourceGroup")

schedule := scheduledactions.ScheduleProperties{
Frequency: scheduledactions.ScheduleFrequencyDaily,
}
schedule.SetEndDateAsTime(time.Now().AddDate(1, 0, 0))
schedule.SetStartDateAsTime(time.Now())

param := scheduledactions.ScheduledAction{
Kind: utils.ToPtr(scheduledactions.ScheduledActionKindInsightAlert),
ETag: resp.Model.ETag,
Properties: &scheduledactions.ScheduledActionProperties{
DisplayName: metadata.ResourceData.Get("display_name").(string),
Status: scheduledactions.ScheduledActionStatusEnabled,
ViewId: viewId.ID(),
Notification: scheduledactions.NotificationProperties{
Subject: metadata.ResourceData.Get("email_subject").(string),
Message: utils.String(metadata.ResourceData.Get("message").(string)),
To: *emailAddresses,
},
Schedule: schedule,
},
}
if _, err := client.CreateOrUpdateByScope(ctx, *id, param); err != nil {
return fmt.Errorf("creating %s: %+v", id, err)
}

metadata.SetID(id)
return nil
},
}
}

func (AnomalyAlertResource) Read() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 5 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
client := metadata.Client.CostManagement.ScheduledActionsClient

id, err := scheduledactions.ParseScopedScheduledActionID(metadata.ResourceData.Id())
if err != nil {
return err
}

resp, err := client.GetByScope(ctx, *id)
if err != nil {
if response.WasNotFound(resp.HttpResponse) {
return metadata.MarkAsGone(id)
}

return fmt.Errorf("retrieving %s: %+v", id, err)
}

if model := resp.Model; model != nil {
metadata.ResourceData.Set("name", model.Name)
if props := model.Properties; props != nil {
metadata.ResourceData.Set("display_name", props.DisplayName)
metadata.ResourceData.Set("email_subject", props.Notification.Subject)
metadata.ResourceData.Set("email_addresses", props.Notification.To)
metadata.ResourceData.Set("message", props.Notification.Message)
}
}

return nil
},
}
}

func (AnomalyAlertResource) Delete() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
client := metadata.Client.CostManagement.ScheduledActionsClient

id, err := scheduledactions.ParseScopedScheduledActionID(metadata.ResourceData.Id())
if err != nil {
return err
}

_, err = client.DeleteByScope(ctx, *id)
if err != nil {
return fmt.Errorf("deleting %s: %+v", *id, err)
}

return nil
},
}
}

func (AnomalyAlertResource) IDValidationFunc() pluginsdk.SchemaValidateFunc {
return scheduledactions.ValidateScopedScheduledActionID
}
98 changes: 98 additions & 0 deletions internal/services/costmanagement/anomaly_alert_resource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package costmanagement_test

import (
"context"
"fmt"
"testing"

"github.com/hashicorp/go-azure-sdk/resource-manager/costmanagement/2022-06-01-preview/scheduledactions"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)

type AnomalyAlertResource struct{}

func TestAccResourceAnomalyAlert_update(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_cost_anomaly_alert", "test")
testResource := AnomalyAlertResource{}
data.ResourceTest(t, testResource, []acceptance.TestStep{
data.ApplyStep(testResource.basicConfig, testResource),
data.ImportStep(),
data.ApplyStep(testResource.updateConfig, testResource),
data.ImportStep(),
data.ApplyStep(testResource.basicConfig, testResource),
data.ImportStep(),
})
}

func TestAccResourceAnomalyAlert_requiresImport(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_cost_anomaly_alert", "test")
testResource := AnomalyAlertResource{}
data.ResourceTest(t, testResource, []acceptance.TestStep{
data.ApplyStep(testResource.basicConfig, testResource),
data.RequiresImportErrorStep(testResource.requiresImportConfig),
})
}

func (AnomalyAlertResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := scheduledactions.ParseScopedScheduledActionID(state.ID)
if err != nil {
return nil, err
}

resp, err := client.CostManagement.ScheduledActionsClient.GetByScope(ctx, *id)
if err != nil {
return nil, fmt.Errorf("retrieving %s: %+v", *id, err)
}

return utils.Bool(resp.Model.Properties != nil), nil
}

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

resource "azurerm_cost_anomaly_alert" "test" {
name = "-acctest-%d"
display_name = "acctest %d"
email_subject = "Hi"
email_addresses = ["[email protected]", "[email protected]"]
message = "Oops, cost anomaly"
}
`, data.RandomInteger, data.RandomInteger)
}

func (r AnomalyAlertResource) requiresImportConfig(data acceptance.TestData) string {
template := r.basicConfig(data)
return fmt.Sprintf(`
%s

resource "azurerm_cost_anomaly_alert" "import" {
name = azurerm_cost_anomaly_alert.test.name
display_name = azurerm_cost_anomaly_alert.test.display_name
email_subject = azurerm_cost_anomaly_alert.test.email_subject
email_addresses = azurerm_cost_anomaly_alert.test.email_addresses
message = azurerm_cost_anomaly_alert.test.message
}
`, template)
}

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

resource "azurerm_cost_anomaly_alert" "test" {
name = "-acctest-%d"
display_name = "acctest name update %d"
email_subject = "Hi you!"
email_addresses = ["[email protected]", "[email protected]"]
message = "An updated cost anomaly for you"
}
`, data.RandomInteger, data.RandomInteger)
}
10 changes: 8 additions & 2 deletions internal/services/costmanagement/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@ package client

import (
"github.com/hashicorp/go-azure-sdk/resource-manager/costmanagement/2021-10-01/exports"
"github.com/hashicorp/go-azure-sdk/resource-manager/costmanagement/2022-06-01-preview/scheduledactions"
"github.com/hashicorp/terraform-provider-azurerm/internal/common"
)

type Client struct {
ExportClient *exports.ExportsClient
ExportClient *exports.ExportsClient
ScheduledActionsClient *scheduledactions.ScheduledActionsClient
}

func NewClient(o *common.ClientOptions) *Client {
ExportClient := exports.NewExportsClientWithBaseURI(o.ResourceManagerEndpoint)
o.ConfigureClient(&ExportClient.Client, o.ResourceManagerAuthorizer)

ScheduledActionsClient := scheduledactions.NewScheduledActionsClientWithBaseURI(o.ResourceManagerEndpoint)
o.ConfigureClient(&ScheduledActionsClient.Client, o.ResourceManagerAuthorizer)

return &Client{
ExportClient: &ExportClient,
ExportClient: &ExportClient,
ScheduledActionsClient: &ScheduledActionsClient,
}
}
Loading