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

New Resource: azurerm_cosmosdb_postgresql_firewall_rule #21599

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
6 changes: 6 additions & 0 deletions internal/services/cosmos/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2022-05-15/managedcassandras"
"github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2022-05-15/sqldedicatedgateway"
"github.com/hashicorp/go-azure-sdk/resource-manager/postgresqlhsc/2022-11-08/clusters"
"github.com/hashicorp/go-azure-sdk/resource-manager/postgresqlhsc/2022-11-08/firewallrules"
"github.com/hashicorp/terraform-provider-azurerm/internal/common"
)

Expand All @@ -14,6 +15,7 @@ type Client struct {
CassandraDatacentersClient *documentdb.CassandraDataCentersClient
ClustersClient *clusters.ClustersClient
DatabaseClient *documentdb.DatabaseAccountsClient
FirewallRulesClient *firewallrules.FirewallRulesClient
GremlinClient *documentdb.GremlinResourcesClient
MongoDbClient *documentdb.MongoDBResourcesClient
NotebookWorkspaceClient *documentdb.NotebookWorkspacesClient
Expand All @@ -40,6 +42,9 @@ func NewClient(o *common.ClientOptions) *Client {
databaseClient := documentdb.NewDatabaseAccountsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&databaseClient.Client, o.ResourceManagerAuthorizer)

firewallRulesClient := firewallrules.NewFirewallRulesClientWithBaseURI(o.ResourceManagerEndpoint)
o.ConfigureClient(&firewallRulesClient.Client, o.ResourceManagerAuthorizer)

gremlinClient := documentdb.NewGremlinResourcesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&gremlinClient.Client, o.ResourceManagerAuthorizer)

Expand Down Expand Up @@ -70,6 +75,7 @@ func NewClient(o *common.ClientOptions) *Client {
CassandraDatacentersClient: &cassandraDatacentersClient,
ClustersClient: &clustersClient,
DatabaseClient: &databaseClient,
FirewallRulesClient: &firewallRulesClient,
GremlinClient: &gremlinClient,
MongoDbClient: &mongoDbClient,
NotebookWorkspaceClient: &notebookWorkspaceClient,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
package cosmos

import (
"context"
"fmt"
"time"

"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-sdk/resource-manager/postgresqlhsc/2022-11-08/firewallrules"
"github.com/hashicorp/terraform-provider-azurerm/internal/sdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/cosmos/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
)

type CosmosDbPostgreSQLFirewallRuleResourceModel struct {
Name string `tfschema:"name"`
ClusterId string `tfschema:"cluster_id"`
EndIPAddress string `tfschema:"end_ip_address"`
StartIPAddress string `tfschema:"start_ip_address"`
}

type CosmosDbPostgreSQLFirewallRuleResource struct{}

var _ sdk.ResourceWithUpdate = CosmosDbPostgreSQLFirewallRuleResource{}

func (r CosmosDbPostgreSQLFirewallRuleResource) ResourceType() string {
return "azurerm_cosmosdb_postgresql_firewall_rule"
}

func (r CosmosDbPostgreSQLFirewallRuleResource) ModelObject() interface{} {
return &CosmosDbPostgreSQLFirewallRuleResourceModel{}
}

func (r CosmosDbPostgreSQLFirewallRuleResource) IDValidationFunc() pluginsdk.SchemaValidateFunc {
return firewallrules.ValidateFirewallRuleID
}

func (r CosmosDbPostgreSQLFirewallRuleResource) Arguments() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.FirewallRuleName,
},

"cluster_id": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: firewallrules.ValidateServerGroupsv2ID,
},

"end_ip_address": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.IsIPv4Address,
},

"start_ip_address": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.IsIPv4Address,
},
}
}

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

func (r CosmosDbPostgreSQLFirewallRuleResource) Create() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
var model CosmosDbPostgreSQLFirewallRuleResourceModel
if err := metadata.Decode(&model); err != nil {
return fmt.Errorf("decoding: %+v", err)
}

client := metadata.Client.Cosmos.FirewallRulesClient
clusterId, err := firewallrules.ParseServerGroupsv2ID(model.ClusterId)
if err != nil {
return err
}

id := firewallrules.NewFirewallRuleID(clusterId.SubscriptionId, clusterId.ResourceGroupName, clusterId.ServerGroupsv2Name, model.Name)
existing, err := client.Get(ctx, id)
if err != nil && !response.WasNotFound(existing.HttpResponse) {
return fmt.Errorf("checking for existing %s: %+v", id, err)
}

if !response.WasNotFound(existing.HttpResponse) {
return metadata.ResourceRequiresImport(r.ResourceType(), id)
}

parameters := firewallrules.FirewallRule{
Properties: firewallrules.FirewallRuleProperties{
EndIPAddress: model.EndIPAddress,
StartIPAddress: model.StartIPAddress,
},
}

if err := client.CreateOrUpdateThenPoll(ctx, id, parameters); err != nil {
return fmt.Errorf("creating %s: %+v", id, err)
}

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

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

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

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

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

parameters := resp.Model
if parameters == nil {
return fmt.Errorf("retrieving %s: model was nil", *id)
}

if metadata.ResourceData.HasChange("end_ip_address") {
parameters.Properties.EndIPAddress = model.EndIPAddress
}

if metadata.ResourceData.HasChange("start_ip_address") {
parameters.Properties.StartIPAddress = model.StartIPAddress
}

if err := client.CreateOrUpdateThenPoll(ctx, *id, *parameters); err != nil {
return fmt.Errorf("updating %s: %+v", *id, err)
}

return nil
},
}
}

func (r CosmosDbPostgreSQLFirewallRuleResource) Read() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 5 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
client := metadata.Client.Cosmos.FirewallRulesClient

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

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

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

model := resp.Model
if model == nil {
return fmt.Errorf("retrieving %s: model was nil", id)
}

state := CosmosDbPostgreSQLFirewallRuleResourceModel{
Name: id.FirewallRuleName,
ClusterId: firewallrules.NewServerGroupsv2ID(id.SubscriptionId, id.ResourceGroupName, id.ServerGroupsv2Name).ID(),
}

properties := &model.Properties
state.EndIPAddress = properties.EndIPAddress
state.StartIPAddress = properties.StartIPAddress

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

func (r CosmosDbPostgreSQLFirewallRuleResource) Delete() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 30 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
client := metadata.Client.Cosmos.FirewallRulesClient

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

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

return nil
},
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package cosmos_test

import (
"context"
"fmt"
"testing"

"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-sdk/resource-manager/postgresqlhsc/2022-11-08/firewallrules"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
"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 CosmosDbPostgreSQLFirewallRuleResource struct{}

func TestCosmosDbPostgreSQLFirewallRule_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_cosmosdb_postgresql_firewall_rule", "test")
r := CosmosDbPostgreSQLFirewallRuleResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data, "10.0.17.62", "10.0.17.64"),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func TestCosmosDbPostgreSQLFirewallRule_requiresImport(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_cosmosdb_postgresql_firewall_rule", "test")
r := CosmosDbPostgreSQLFirewallRuleResource{}
startIPAddress := "10.0.17.62"
endIPAddress := "10.0.17.64"

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data, startIPAddress, endIPAddress),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.RequiresImportErrorStep(func(data acceptance.TestData) string {
return r.requiresImport(data, startIPAddress, endIPAddress)
}),
})
}

func TestCosmosDbPostgreSQLFirewallRule_update(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_cosmosdb_postgresql_firewall_rule", "test")
r := CosmosDbPostgreSQLFirewallRuleResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data, "10.0.17.62", "10.0.17.64"),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
{
Config: r.basic(data, "10.0.17.65", "10.0.17.67"),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func (r CosmosDbPostgreSQLFirewallRuleResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := firewallrules.ParseFirewallRuleID(state.ID)
if err != nil {
return nil, err
}

client := clients.Cosmos.FirewallRulesClient
resp, err := client.Get(ctx, *id)
if err != nil {
if response.WasNotFound(resp.HttpResponse) {
return utils.Bool(false), nil
}
return nil, fmt.Errorf("retrieving %s: %+v", id, err)
}
return utils.Bool(resp.Model != nil), nil
}

func (r CosmosDbPostgreSQLFirewallRuleResource) template(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}

resource "azurerm_resource_group" "test" {
name = "acctestRG-pshscfwr-%d"
location = "%s"
}

resource "azurerm_cosmosdb_postgresql_cluster" "test" {
name = "acctestcluster%d"
resource_group_name = azurerm_resource_group.test.name
location = azurerm_resource_group.test.location
administrator_login_password = "H@Sh1CoR3!"
coordinator_storage_quota_in_mb = 131072
coordinator_vcore_count = 2
node_count = 0
}
`, data.RandomInteger, data.Locations.Primary, data.RandomInteger)
}

func (r CosmosDbPostgreSQLFirewallRuleResource) basic(data acceptance.TestData, startIPAddress, endIPAddress string) string {
return fmt.Sprintf(`
%s

resource "azurerm_cosmosdb_postgresql_firewall_rule" "test" {
name = "acctest-pshscfwr-%d"
cluster_id = azurerm_cosmosdb_postgresql_cluster.test.id
start_ip_address = "%s"
end_ip_address = "%s"
}
`, r.template(data), data.RandomInteger, startIPAddress, endIPAddress)
}

func (r CosmosDbPostgreSQLFirewallRuleResource) requiresImport(data acceptance.TestData, startIPAddress, endIPAddress string) string {
return fmt.Sprintf(`
%s

resource "azurerm_cosmosdb_postgresql_firewall_rule" "import" {
name = azurerm_cosmosdb_postgresql_firewall_rule.test.name
cluster_id = azurerm_cosmosdb_postgresql_firewall_rule.test.cluster_id
start_ip_address = azurerm_cosmosdb_postgresql_firewall_rule.test.start_ip_address
end_ip_address = azurerm_cosmosdb_postgresql_firewall_rule.test.end_ip_address
}
`, r.basic(data, startIPAddress, endIPAddress))
}
1 change: 1 addition & 0 deletions internal/services/cosmos/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func (r Registration) DataSources() []sdk.DataSource {
func (r Registration) Resources() []sdk.Resource {
return []sdk.Resource{
CosmosDbPostgreSQLClusterResource{},
CosmosDbPostgreSQLFirewallRuleResource{},
CosmosDbSqlDedicatedGatewayResource{},
}
}
Expand Down
Loading