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_app_configuration_replica #21689

Closed
wants to merge 5 commits into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package appconfiguration

import (
"context"
"fmt"
"time"

"github.com/hashicorp/go-azure-helpers/lang/pointer"
"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema"
"github.com/hashicorp/go-azure-helpers/resourcemanager/location"
"github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2023-03-01/configurationstores"
"github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2023-03-01/replicas"
"github.com/hashicorp/terraform-provider-azurerm/internal/locks"
"github.com/hashicorp/terraform-provider-azurerm/internal/sdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
)

var _ sdk.Resource = ReplicaResource{}

type ReplicaResource struct{}

func (r ReplicaResource) ModelObject() interface{} {
return &ReplicaResourceSchema{}
}

type ReplicaResourceSchema struct {
ConfigurationStoreId string `tfschema:"configuration_store_id"`
Endpoint string `tfschema:"endpoint"`
Location string `tfschema:"location"`
Name string `tfschema:"name"`
}

func (r ReplicaResource) IDValidationFunc() pluginsdk.SchemaValidateFunc {
return replicas.ValidateReplicaID
}
func (r ReplicaResource) ResourceType() string {
return "azurerm_app_configuration_replica"
}
func (r ReplicaResource) Arguments() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"configuration_store_id": {
ForceNew: true,
Required: true,
Type: pluginsdk.TypeString,
ValidateFunc: configurationstores.ValidateConfigurationStoreID,
},
"location": commonschema.Location(),
"name": {
ForceNew: true,
Required: true,
Type: pluginsdk.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
}
}

func (r ReplicaResource) Attributes() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"endpoint": {
Computed: true,
Type: pluginsdk.TypeString,
},
}
}

func (r ReplicaResource) Create() sdk.ResourceFunc {
Copy link
Contributor

Choose a reason for hiding this comment

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

rather than being a separate resource, this likely should be embedded within the App Configuration resource as a replica block, in the same way we've done for CosmosDB, since when making changes to the primary it can be necessary to make changes to the replicas too?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The replica resource has its own API endpoint to create/delete, and it only rely on the resource ID of App Configuration resource, so I think it's better we create a new resource for this? If we put this inline, it might have issue when App Configuration is successfully created but the Replica fail.

Copy link
Collaborator

Choose a reason for hiding this comment

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

@teowa, it is a 1:1 mapping, so unless there is a reason it needs to be separate, ie permissions / policy need updating with the created resource id before replication, it should be within the parent resource. also, as tom mentioned it simplifies the situations when the primary/secondary needs to be updated before/after a change

Copy link
Contributor Author

@teowa teowa May 22, 2023

Choose a reason for hiding this comment

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

This should be 1:n mapping, the API supports creating 1 replica per azure location, so there may be multiple replicas under one app configuration.
image

Copy link
Contributor Author

@teowa teowa May 22, 2023

Choose a reason for hiding this comment

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

If we make the replica a inline block inside the azurerm_app_configuration, but in create/update if the replica fails to create but its parent resource is successfully created, we still need to write parent resource to state? if we don't write the parent resource into state, there will be tf.ImportAsExistsError error. So how can we write partial state under current design(we call read function to write the state only if the whole create/update successfully)?

Copy link
Collaborator

Choose a reason for hiding this comment

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

in create/update if the replica fails to create but its parent resource is successfully created, we still need to write parent resource to state

we would fail creation then.

this is much like the cosmosdb resource with its replication locations property. As tom said this shouljd be part of the parent resource we should mimic the way cosmos db does it?

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

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

configurationStoreId, err := configurationstores.ParseConfigurationStoreID(config.ConfigurationStoreId)
if err != nil {
return fmt.Errorf("parsing configuration store id %s: %+v", config.ConfigurationStoreId, err)
}

id := replicas.NewReplicaID(configurationStoreId.SubscriptionId, configurationStoreId.ResourceGroupName, configurationStoreId.ConfigurationStoreName, config.Name)

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

payload := replicas.Replica{
Location: pointer.To(config.Location),
Name: pointer.To(config.Name),
}

// concurrent creation of replicas under one configuration store will fail
locks.ByName(id.ConfigurationStoreName, r.ResourceType())
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The API has limitation that we cannot create two replica under one Configuration Store at the same time, here a lock is added.

defer locks.UnlockByName(id.ConfigurationStoreName, r.ResourceType())

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

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

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

id, err := replicas.ParseReplicaID(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)
}

if resp.Model == nil {
return fmt.Errorf("unexpected nil model for %s", *id)
}
if resp.Model.Properties == nil {
return fmt.Errorf("unexpected nil properties for %s", *id)
}
if resp.Model.Location == nil {
return fmt.Errorf("unexpected nil location for %s", *id)
}

schema := ReplicaResourceSchema{
ConfigurationStoreId: configurationstores.NewConfigurationStoreID(id.SubscriptionId, id.ResourceGroupName, id.ConfigurationStoreName).ID(),
Endpoint: pointer.From(resp.Model.Properties.Endpoint),
Location: location.Normalize(*resp.Model.Location),
Name: id.ReplicaName,
}

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

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

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

locks.ByName(id.ConfigurationStoreName, r.ResourceType())
defer locks.UnlockByName(id.ConfigurationStoreName, r.ResourceType())

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,145 @@
package appconfiguration_test

import (
"context"
"fmt"
"testing"

"github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2023-03-01/replicas"
"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 AppConfigurationReplicaTestResource struct{}

func TestAccAppConfigurationReplica_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_app_configuration_replica", "test")
r := AppConfigurationReplicaTestResource{}

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

func TestAccAppConfigurationReplica_multiple(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_app_configuration_replica", "test")
r := AppConfigurationReplicaTestResource{}

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

func TestAccAppConfigurationReplica_requiresImport(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_app_configuration_replica", "test")
r := AppConfigurationReplicaTestResource{}

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

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

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

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

func (r AppConfigurationReplicaTestResource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
%s

resource "azurerm_app_configuration_replica" "test" {
configuration_store_id = azurerm_app_configuration.test.id
location = local.secondary_location
name = "replica1"
}
`, r.template(data))
}

func (r AppConfigurationReplicaTestResource) multiple(data acceptance.TestData) string {
return fmt.Sprintf(`
%s

resource "azurerm_app_configuration_replica" "test" {
configuration_store_id = azurerm_app_configuration.test.id
location = local.secondary_location
name = "replica1"
}

resource "azurerm_app_configuration_replica" "test1" {
configuration_store_id = azurerm_app_configuration.test.id
location = local.ternary_location
name = "replica2"
}
`, r.template(data))
}

func (r AppConfigurationReplicaTestResource) requiresImport(data acceptance.TestData) string {
return fmt.Sprintf(`
%s

resource "azurerm_app_configuration_replica" "import" {
configuration_store_id = azurerm_app_configuration_replica.test.configuration_store_id
location = azurerm_app_configuration_replica.test.location
name = azurerm_app_configuration_replica.test.name
}
`, r.basic(data))
}

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

locals {
random_integer = %[1]d
primary_location = %[2]q
secondary_location = %[3]q
ternary_location = %[4]q
}

resource "azurerm_resource_group" "test" {
name = "acctestRG-appconfig-replica-${local.random_integer}"
location = local.primary_location
}

resource "azurerm_app_configuration" "test" {
name = "testappconf${local.random_integer}"
resource_group_name = azurerm_resource_group.test.name
location = azurerm_resource_group.test.location
sku = "standard"
soft_delete_retention_days = 1
}
`, data.RandomInteger, data.Locations.Primary, data.Locations.Secondary, data.Locations.Ternary)
}
Loading