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_new_relic_monitor - support monitored_subscription property #28134

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 14 additions & 4 deletions internal/services/newrelic/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ package client
import (
"fmt"

"github.com/hashicorp/go-azure-sdk/resource-manager/newrelic/2024-03-01/monitoredsubscriptions"
"github.com/hashicorp/go-azure-sdk/resource-manager/newrelic/2024-03-01/monitors"
"github.com/hashicorp/go-azure-sdk/resource-manager/newrelic/2024-03-01/tagrules"
"github.com/hashicorp/terraform-provider-azurerm/internal/common"
)

type Client struct {
MonitorsClient *monitors.MonitorsClient
TagRulesClient *tagrules.TagRulesClient
MonitorsClient *monitors.MonitorsClient
MonitoredSubscriptionsClient *monitoredsubscriptions.MonitoredSubscriptionsClient
TagRulesClient *tagrules.TagRulesClient
}

func NewClient(o *common.ClientOptions) (*Client, error) {
Expand All @@ -24,6 +26,13 @@ func NewClient(o *common.ClientOptions) (*Client, error) {

o.Configure(monitorsClient.Client, o.Authorizers.ResourceManager)

monitoredSubscriptionsClient, err := monitoredsubscriptions.NewMonitoredSubscriptionsClientWithBaseURI(o.Environment.ResourceManager)
if err != nil {
return nil, fmt.Errorf("building Monitored Subscriptions client: %+v", err)
}

o.Configure(monitoredSubscriptionsClient.Client, o.Authorizers.ResourceManager)

tagRulesClient, err := tagrules.NewTagRulesClientWithBaseURI(o.Environment.ResourceManager)
if err != nil {
return nil, fmt.Errorf("building TagRules client: %+v", err)
Expand All @@ -32,7 +41,8 @@ func NewClient(o *common.ClientOptions) (*Client, error) {
o.Configure(tagRulesClient.Client, o.Authorizers.ResourceManager)

return &Client{
MonitorsClient: monitorsClient,
TagRulesClient: tagRulesClient,
MonitorsClient: monitorsClient,
MonitoredSubscriptionsClient: monitoredSubscriptionsClient,
TagRulesClient: tagRulesClient,
}, nil
}
145 changes: 132 additions & 13 deletions internal/services/newrelic/new_relic_monitor_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema"
"github.com/hashicorp/go-azure-helpers/resourcemanager/identity"
"github.com/hashicorp/go-azure-helpers/resourcemanager/location"
"github.com/hashicorp/go-azure-sdk/resource-manager/newrelic/2024-03-01/monitoredsubscriptions"
"github.com/hashicorp/go-azure-sdk/resource-manager/newrelic/2024-03-01/monitors"
"github.com/hashicorp/terraform-provider-azurerm/internal/sdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
Expand All @@ -27,17 +28,22 @@ const (
)

type NewRelicMonitorModel struct {
Name string `tfschema:"name"`
ResourceGroupName string `tfschema:"resource_group_name"`
AccountCreationSource monitors.AccountCreationSource `tfschema:"account_creation_source"`
AccountId string `tfschema:"account_id"`
IngestionKey string `tfschema:"ingestion_key"`
Location string `tfschema:"location"`
OrganizationId string `tfschema:"organization_id"`
OrgCreationSource monitors.OrgCreationSource `tfschema:"org_creation_source"`
PlanData []PlanDataModel `tfschema:"plan"`
UserId string `tfschema:"user_id"`
UserInfo []UserInfoModel `tfschema:"user"`
Name string `tfschema:"name"`
ResourceGroupName string `tfschema:"resource_group_name"`
AccountCreationSource monitors.AccountCreationSource `tfschema:"account_creation_source"`
AccountId string `tfschema:"account_id"`
IngestionKey string `tfschema:"ingestion_key"`
Location string `tfschema:"location"`
MonitoredSubscription []NewRelicMonitoredSubscription `tfschema:"monitored_subscription"`
OrganizationId string `tfschema:"organization_id"`
OrgCreationSource monitors.OrgCreationSource `tfschema:"org_creation_source"`
PlanData []PlanDataModel `tfschema:"plan"`
UserId string `tfschema:"user_id"`
UserInfo []UserInfoModel `tfschema:"user"`
}

type NewRelicMonitoredSubscription struct {
SubscriptionId string `tfschema:"subscription_id"`
}

type PlanDataModel struct {
Expand All @@ -56,7 +62,10 @@ type UserInfoModel struct {

type NewRelicMonitorResource struct{}

var _ sdk.Resource = NewRelicMonitorResource{}
var (
_ sdk.Resource = NewRelicMonitorResource{}
_ sdk.ResourceWithUpdate = NewRelicMonitorResource{}
)

func (r NewRelicMonitorResource) ResourceType() string {
return "azurerm_new_relic_monitor"
Expand Down Expand Up @@ -205,6 +214,20 @@ func (r NewRelicMonitorResource) Arguments() map[string]*pluginsdk.Schema {
ValidateFunc: validation.StringIsNotEmpty,
},

"monitored_subscription": {
Type: pluginsdk.TypeList,
Optional: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"subscription_id": {
Copy link
Contributor Author

@teowa teowa Dec 2, 2024

Choose a reason for hiding this comment

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

This is not flattened because there are other properties in the monitoredSubscription but not supported by API for now and they might be supported in the future.

Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.IsUUID,
},
},
},
},

"organization_id": {
Type: pluginsdk.TypeString,
Optional: true,
Expand Down Expand Up @@ -282,7 +305,21 @@ func (r NewRelicMonitorResource) Create() sdk.ResourceFunc {
return fmt.Errorf("creating %s: %+v", id, err)
}

if len(model.MonitoredSubscription) > 0 {
monitoredSubscriptionsProperties := monitoredsubscriptions.MonitoredSubscriptionProperties{
Properties: &monitoredsubscriptions.SubscriptionList{
MonitoredSubscriptionList: expandMonitorSubscriptionList(model.MonitoredSubscription),
},
}

monitorId := monitoredsubscriptions.NewMonitorID(id.SubscriptionId, id.ResourceGroupName, id.MonitorName)
if err := metadata.Client.NewRelic.MonitoredSubscriptionsClient.CreateOrUpdateThenPoll(ctx, monitorId, monitoredSubscriptionsProperties); err != nil {
return fmt.Errorf("creating NewRelic Monitored Subscriptions of %s: %+v", id, err)
}
}

metadata.SetID(id)

return nil
},
}
Expand Down Expand Up @@ -352,11 +389,62 @@ func (r NewRelicMonitorResource) Read() sdk.ResourceFunc {
state.UserInfo = flattenUserInfoModel(properties.UserInfo)
}

monitorId := monitoredsubscriptions.NewMonitorID(id.SubscriptionId, id.ResourceGroupName, id.MonitorName)
monitoredSubscriptionResp, err := metadata.Client.NewRelic.MonitoredSubscriptionsClient.Get(ctx, monitorId)
if err != nil && !response.WasNotFound(monitoredSubscriptionResp.HttpResponse) {
return fmt.Errorf("retrieving NewRelic Monitored Subscriptions of %s: %+v", *id, err)
}
if !response.WasNotFound(monitoredSubscriptionResp.HttpResponse) {
if monitoredSubscriptionResp.Model != nil && monitoredSubscriptionResp.Model.Properties != nil {
state.MonitoredSubscription = flattenMonitorSubscriptionList(monitoredSubscriptionResp.Model.Properties.MonitoredSubscriptionList)
}
}

return metadata.Encode(&state)
},
}
}

func (r NewRelicMonitorResource) Update() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
id, err := monitors.ParseMonitorID(metadata.ResourceData.Id())
if err != nil {
return err
}

var originalModel NewRelicMonitorModel
if err = metadata.Decode(&originalModel); err != nil {
return fmt.Errorf("decoding: %+v", err)
}

if metadata.ResourceData.HasChange("monitored_subscription") {
monitoredSubscriptionsClient := metadata.Client.NewRelic.MonitoredSubscriptionsClient
monitorId := monitoredsubscriptions.NewMonitorID(id.SubscriptionId, id.ResourceGroupName, id.MonitorName)

if len(originalModel.MonitoredSubscription) == 0 {
if _, err := monitoredSubscriptionsClient.Delete(ctx, monitorId); err != nil {
return fmt.Errorf("deleting NewRelic Monitored Subscriptions of %s: %+v", *id, err)
}
} else {
monitoredSubscriptionsProperties := monitoredsubscriptions.MonitoredSubscriptionProperties{
Properties: &monitoredsubscriptions.SubscriptionList{
MonitoredSubscriptionList: expandMonitorSubscriptionList(originalModel.MonitoredSubscription),
},
}

if err := monitoredSubscriptionsClient.CreateOrUpdateThenPoll(ctx, monitorId, monitoredSubscriptionsProperties); err != nil {
return fmt.Errorf("updating NewRelic Monitored Subscriptions of %s: %+v", *id, err)
}
}
}

return nil
},
}
}

func (r NewRelicMonitorResource) Delete() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Expand All @@ -377,7 +465,7 @@ func (r NewRelicMonitorResource) Delete() sdk.ResourceFunc {
}

if err = client.DeleteThenPoll(ctx, *id, monitors.DeleteOperationOptions{UserEmail: &model.UserInfo[0].EmailAddress}); err != nil {
return fmt.Errorf("deleting %s: %+v", id, err)
return fmt.Errorf("deleting %s: %+v", *id, err)
}

return nil
Expand Down Expand Up @@ -537,3 +625,34 @@ func flattenUserInfoModel(input *monitors.UserInfo) []UserInfoModel {

return append(outputList, output)
}

func expandMonitorSubscriptionList(input []NewRelicMonitoredSubscription) *[]monitoredsubscriptions.MonitoredSubscription {
results := make([]monitoredsubscriptions.MonitoredSubscription, 0)
if len(input) == 0 {
return &results
}

for _, v := range input {
results = append(results, monitoredsubscriptions.MonitoredSubscription{
SubscriptionId: pointer.To(v.SubscriptionId),
})
}

return &results
}

func flattenMonitorSubscriptionList(input *[]monitoredsubscriptions.MonitoredSubscription) []NewRelicMonitoredSubscription {
results := make([]NewRelicMonitoredSubscription, 0)
if input == nil {
return results
}

for _, v := range *input {
results = append(results, NewRelicMonitoredSubscription{
// The returned subscription UUID is in upper case
SubscriptionId: strings.ToLower(pointer.From(v.SubscriptionId)),
})
}

return results
}
78 changes: 78 additions & 0 deletions internal/services/newrelic/new_relic_monitor_resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,52 @@ func TestAccNewRelicMonitor_identity(t *testing.T) {
})
}

func TestAccNewRelicMonitor_monitoredSubscription(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_new_relic_monitor", "test")
r := NewRelicMonitorResource{}
effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339)
email := "[email protected]"
data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.monitoredSubscription(data, effectiveDate, email),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func TestAccNewRelicMonitor_monitoredSubscriptionUpdate(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_new_relic_monitor", "test")
r := NewRelicMonitorResource{}
effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339)
email := "[email protected]"
data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data, effectiveDate, email),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
{
Config: r.monitoredSubscription(data, effectiveDate, email),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
{
Config: r.basic(data, effectiveDate, email),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func (r NewRelicMonitorResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := monitors.ParseMonitorID(state.ID)
if err != nil {
Expand Down Expand Up @@ -247,3 +293,35 @@ resource "azurerm_role_assignment" "test" {
}
`, template, data.RandomInteger, data.Locations.Primary, effectiveDate, email)
}

func (r NewRelicMonitorResource) monitoredSubscription(data acceptance.TestData, effectiveDate string, email string) string {
template := r.template(data)
return fmt.Sprintf(`
%s

data "azurerm_subscription" "test" {
subscription_id = "%s"
}

resource "azurerm_new_relic_monitor" "test" {
name = "acctest-nrm-%d"
resource_group_name = azurerm_resource_group.test.name
location = "%s"
plan {
effective_date = "%s"
}
user {
email = "%s"
first_name = "first"
last_name = "last"
phone_number = "123456"
}
identity {
type = "SystemAssigned"
}
monitored_subscription {
subscription_id = data.azurerm_subscription.test.subscription_id
}
}
`, template, data.Subscriptions.Secondary, data.RandomInteger, data.Locations.Primary, effectiveDate, email)
}
Loading
Loading