-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Aris van Ommeren
committed
Jan 7, 2023
1 parent
e31740a
commit 3f87d8a
Showing
36 changed files
with
2,474 additions
and
2 deletions.
There are no files selected for viewing
220 changes: 220 additions & 0 deletions
220
internal/services/costmanagement/anomaly_alert_resource.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,220 @@ | ||
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/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, | ||
}, | ||
|
||
"email_subject": { | ||
Type: pluginsdk.TypeString, | ||
Required: true, | ||
}, | ||
|
||
"email_addresses": { | ||
Type: pluginsdk.TypeSet, | ||
Required: true, | ||
MinItems: 1, | ||
Elem: &pluginsdk.Schema{ | ||
Type: pluginsdk.TypeString, | ||
ValidateFunc: validation.StringIsNotEmpty, | ||
}, | ||
}, | ||
|
||
"message": { | ||
Type: pluginsdk.TypeString, | ||
Optional: true, | ||
}, | ||
} | ||
} | ||
|
||
func (AnomalyAlertResource) Attributes() map[string]*pluginsdk.Schema { | ||
return map[string]*pluginsdk.Schema{} | ||
} | ||
|
||
func (AnomalyAlertResource) ModelObject() interface{} { | ||
return nil | ||
} | ||
|
||
func (AnomalyAlertResource) ResourceType() string { | ||
return "azurerm_costmanagement_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), "dailyanomalybyresourcegroup") | ||
|
||
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.NewAnomalyAlertViewIdID(subscriptionId, "ms:DailyAnomalyByResourceGroup") | ||
schedule := scheduledactions.ScheduleProperties{ | ||
Frequency: scheduledactions.ScheduleFrequencyDaily, | ||
HourOfDay: utils.Int64(int64(12)), | ||
DayOfMonth: utils.Int64(int64(0)), | ||
} | ||
schedule.SetEndDateAsTime(time.Now().AddDate(1, 0, 0)) | ||
schedule.SetStartDateAsTime(time.Now()) | ||
param := scheduledactions.ScheduledAction{ | ||
Kind: utils.ToPtr(scheduledactions.ScheduledActionKindInsightAlert), | ||
Type: utils.String("Microsoft.CostManagement/ScheduledActions"), | ||
Properties: &scheduledactions.ScheduledActionProperties{ | ||
DisplayName: metadata.ResourceData.Get("name").(string), | ||
Status: scheduledactions.ScheduledActionStatusEnabled, | ||
ViewId: viewId.ID(), | ||
Scope: utils.String(fmt.Sprint("/subscriptions/", subscriptionId)), | ||
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.Get("id").(string)) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
emailAddressesRaw := metadata.ResourceData.Get("email_addresses").(*pluginsdk.Set).List() | ||
emailAddresses := utils.ExpandStringSlice(emailAddressesRaw) | ||
|
||
subscriptionId := metadata.Client.Account.SubscriptionId | ||
viewId := parse.NewAnomalyAlertViewIdID(subscriptionId, "ms:DailyAnomalyByResourceGroup") | ||
|
||
schedule := scheduledactions.ScheduleProperties{ | ||
Frequency: scheduledactions.ScheduleFrequencyDaily, | ||
HourOfDay: utils.Int64(int64(12)), | ||
DayOfMonth: utils.Int64(int64(0)), | ||
} | ||
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("name").(string), | ||
Scope: utils.String(fmt.Sprint("/subscriptions/", subscriptionId)), | ||
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) | ||
} | ||
|
||
metadata.ResourceData.Set("name", resp.Model.Properties.DisplayName) | ||
metadata.ResourceData.Set("email_subject", resp.Model.Properties.Notification.Subject) | ||
metadata.ResourceData.Set("email_addresses", resp.Model.Properties.Notification.To) | ||
metadata.ResourceData.Set("message", resp.Model.Properties.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 | ||
} |
55 changes: 55 additions & 0 deletions
55
internal/services/costmanagement/anomaly_alert_resource_test.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
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_basic(t *testing.T) { | ||
data := acceptance.BuildTestData(t, "azurerm_costmanagement_anomaly_alert", "test") | ||
testResource := AnomalyAlertResource{} | ||
data.ResourceTest(t, testResource, []acceptance.TestStep{ | ||
data.ApplyStep(testResource.basicConfig, testResource), | ||
data.ImportStep(), | ||
}) | ||
} | ||
|
||
// go install && make acctests SERVICE='costmanagement' TESTARGS='-run=TestAccResourceAnomalyAlert_basic' | ||
|
||
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_costmanagement_anomaly_alert" "test" { | ||
name = "acctestRG-%d" | ||
email_subject = "Hi" | ||
email_addresses = ["[email protected]", "[email protected]"] | ||
message = "Oops, cost anomaly" | ||
} | ||
`, data.RandomInteger) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
61 changes: 61 additions & 0 deletions
61
internal/services/costmanagement/parse/anomaly_alert_view_id.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package parse | ||
|
||
// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" | ||
) | ||
|
||
type AnomalyAlertViewIdId struct { | ||
SubscriptionId string | ||
ViewName string | ||
} | ||
|
||
func NewAnomalyAlertViewIdID(subscriptionId, viewName string) AnomalyAlertViewIdId { | ||
return AnomalyAlertViewIdId{ | ||
SubscriptionId: subscriptionId, | ||
ViewName: viewName, | ||
} | ||
} | ||
|
||
func (id AnomalyAlertViewIdId) String() string { | ||
segments := []string{ | ||
fmt.Sprintf("View Name %q", id.ViewName), | ||
} | ||
segmentsStr := strings.Join(segments, " / ") | ||
return fmt.Sprintf("%s: (%s)", "Anomaly Alert View Id", segmentsStr) | ||
} | ||
|
||
func (id AnomalyAlertViewIdId) ID() string { | ||
fmtString := "/subscriptions/%s/providers/Microsoft.CostManagement/views/%s" | ||
return fmt.Sprintf(fmtString, id.SubscriptionId, id.ViewName) | ||
} | ||
|
||
// AnomalyAlertViewIdID parses a AnomalyAlertViewId ID into an AnomalyAlertViewIdId struct | ||
func AnomalyAlertViewIdID(input string) (*AnomalyAlertViewIdId, error) { | ||
id, err := resourceids.ParseAzureResourceID(input) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
resourceId := AnomalyAlertViewIdId{ | ||
SubscriptionId: id.SubscriptionID, | ||
} | ||
|
||
if resourceId.SubscriptionId == "" { | ||
return nil, fmt.Errorf("ID was missing the 'subscriptions' element") | ||
} | ||
|
||
if resourceId.ViewName, err = id.PopSegment("views"); err != nil { | ||
return nil, err | ||
} | ||
|
||
if err := id.ValidateNoEmptySegments(input); err != nil { | ||
return nil, err | ||
} | ||
|
||
return &resourceId, nil | ||
} |
Oops, something went wrong.