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_site_recovery_protection_container_mapping - support automatic_update_extension.automatic_update_extensions_enabled and automatic_update_extension.automation_account_id properties #19710

Merged
merged 16 commits into from
Jan 30, 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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema"
"github.com/hashicorp/go-azure-sdk/resource-manager/recoveryservicessiterecovery/2022-10-01/replicationprotectioncontainermappings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-azurerm/helpers/azure"
"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
Expand All @@ -22,7 +23,7 @@ func resourceSiteRecoveryProtectionContainerMapping() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceSiteRecoveryContainerMappingCreate,
Read: resourceSiteRecoveryContainerMappingRead,
Update: nil,
Update: resourceSiteRecoveryContainerMappingUpdate,
Delete: resourceSiteRecoveryServicesContainerMappingDelete,
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.ReplicationProtectionContainerMappingsID(id)
Expand Down Expand Up @@ -77,6 +78,28 @@ func resourceSiteRecoveryProtectionContainerMapping() *pluginsdk.Resource {
ValidateFunc: azure.ValidateResourceID,
DiffSuppressFunc: suppress.CaseDifference,
},
"automatic_update": {
Type: pluginsdk.TypeList,
MinItems: 1,
MaxItems: 1,
Optional: true,
Computed: true, // set it to computed because the service will return it no matter if we have passed it.
Elem: &pluginsdk.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: false,
},
"automation_account_id": {
Type: pluginsdk.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: azure.ValidateResourceID,
},
},
},
},
},
}
}
Expand Down Expand Up @@ -117,16 +140,73 @@ func resourceSiteRecoveryContainerMappingCreate(d *pluginsdk.ResourceData, meta
ProviderSpecificInput: replicationprotectioncontainermappings.A2AContainerMappingInput{},
},
}

autoUpdateEnabledValue, automationAccountArmId := expandAutoUpdateSettings(d.Get("automatic_update").([]interface{}))

if autoUpdateEnabledValue == replicationprotectioncontainermappings.AgentAutoUpdateStatusEnabled {
parameters.Properties.ProviderSpecificInput = replicationprotectioncontainermappings.A2AContainerMappingInput{
AgentAutoUpdateStatus: &autoUpdateEnabledValue,
AutomationAccountArmId: automationAccountArmId,
}
}

err := client.CreateThenPoll(ctx, id, parameters)
if err != nil {
return fmt.Errorf("creating site recovery protection container mapping %s (vault %s): %+v", name, vaultName, err)
}

d.SetId(id.ID())

return resourceSiteRecoveryContainerMappingRead(d, meta)
}

func resourceSiteRecoveryContainerMappingUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).RecoveryServices.ContainerMappingClient
ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()

id, err := replicationprotectioncontainermappings.ParseReplicationProtectionContainerMappingID(d.Id())
if err != nil {
return err
}

resp, err := client.Get(ctx, *id)
if err != nil {
if response.WasNotFound(resp.HttpResponse) {
d.SetId("")
return nil
}
return fmt.Errorf("making Read request on site recovery protection container mapping %s : %+v", id.String(), err)
}

if resp.Model == nil {
return fmt.Errorf("making Read request on site recovery protection container mapping %s : `Model` is nil", id.String())
}

if resp.Model.Properties == nil {
return fmt.Errorf("making Read request on site recovery protection container mapping %s : `Properties` is nil", id.String())
}

update := replicationprotectioncontainermappings.UpdateProtectionContainerMappingInput{
Properties: &replicationprotectioncontainermappings.UpdateProtectionContainerMappingInputProperties{},
}

if d.HasChange("automatic_update") {
autoUpdateEnabledValue, automationAccountArmId := expandAutoUpdateSettings(d.Get("automatic_update").([]interface{}))
updateInput := replicationprotectioncontainermappings.A2AUpdateContainerMappingInput{
AgentAutoUpdateStatus: &autoUpdateEnabledValue,
AutomationAccountArmId: automationAccountArmId,
}
update.Properties.ProviderSpecificInput = updateInput
}

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

return resourceSiteRecoveryContainerMappingRead(d, meta)
}

func resourceSiteRecoveryContainerMappingRead(d *pluginsdk.ResourceData, meta interface{}) error {
id, err := replicationprotectioncontainermappings.ParseReplicationProtectionContainerMappingID(d.Id())
if err != nil {
Expand Down Expand Up @@ -159,6 +239,12 @@ func resourceSiteRecoveryContainerMappingRead(d *pluginsdk.ResourceData, meta in
d.Set("recovery_source_protection_container_name", model.Properties.SourceProtectionContainerFriendlyName)
d.Set("recovery_replication_policy_id", model.Properties.PolicyId)
d.Set("recovery_target_protection_container_id", model.Properties.TargetProtectionContainerId)

if detail, ok := prop.ProviderSpecificDetails.(replicationprotectioncontainermappings.A2AProtectionContainerMappingDetails); ok {
d.Set("automatic_update", flattenAutoUpdateSettings(&detail))
} else {
d.Set("automatic_update", flattenAutoUpdateSettings(nil))
}
}

return nil
Expand Down Expand Up @@ -191,3 +277,36 @@ func resourceSiteRecoveryServicesContainerMappingDelete(d *pluginsdk.ResourceDat

return nil
}

func expandAutoUpdateSettings(input []interface{}) (enabled replicationprotectioncontainermappings.AgentAutoUpdateStatus, automationAccountId *string) {
if len(input) == 0 {
return replicationprotectioncontainermappings.AgentAutoUpdateStatusDisabled, nil
}
autoUpdateSettingMap := input[0].(map[string]interface{})

autoUpdateEnabledValue := replicationprotectioncontainermappings.AgentAutoUpdateStatusDisabled
if autoUpdateSettingMap["enabled"].(bool) {
autoUpdateEnabledValue = replicationprotectioncontainermappings.AgentAutoUpdateStatusEnabled
}

var accountIdOutput *string
accountId := autoUpdateSettingMap["automation_account_id"].(string)
if accountId == "" {
accountIdOutput = nil
} else {
accountIdOutput = &accountId
}

return autoUpdateEnabledValue, accountIdOutput
}

func flattenAutoUpdateSettings(input *replicationprotectioncontainermappings.A2AProtectionContainerMappingDetails) []interface{} {
output := map[string]interface{}{}
if input == nil {
output["enabled"] = false
return []interface{}{output}
}
output["enabled"] = *input.AgentAutoUpdateStatus == replicationprotectioncontainermappings.AgentAutoUpdateStatusEnabled
output["automation_account_id"] = input.AutomationAccountArmId
return []interface{}{output}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,35 @@ func TestAccSiteRecoveryProtectionContainerMapping_basic(t *testing.T) {
})
}

func TestAccSiteRecoveryProtectionContainerMapping_withAutoUpdateExtension(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_site_recovery_protection_container_mapping", "test")
r := SiteRecoveryProtectionContainerMappingResource{}

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

func (SiteRecoveryProtectionContainerMappingResource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
Expand Down Expand Up @@ -99,6 +128,91 @@ resource "azurerm_site_recovery_protection_container_mapping" "test" {
`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.Locations.Secondary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger)
}

func (SiteRecoveryProtectionContainerMappingResource) autoUpdateExtension(data acceptance.TestData, enabled bool) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}

resource "azurerm_resource_group" "test1" {
name = "acctestRG-recovery-%d-1"
location = "%s"
}

resource "azurerm_automation_account" "test" {
name = "acctestAutomation-%d"
location = azurerm_resource_group.test1.location
resource_group_name = azurerm_resource_group.test1.name

sku_name = "Basic"

tags = {
Environment = "Test"
}
}

resource "azurerm_recovery_services_vault" "test" {
name = "acctest-vault-%d"
location = azurerm_resource_group.test1.location
resource_group_name = azurerm_resource_group.test1.name
sku = "Standard"

soft_delete_enabled = false
}

resource "azurerm_site_recovery_fabric" "test1" {
resource_group_name = azurerm_resource_group.test1.name
recovery_vault_name = azurerm_recovery_services_vault.test.name
name = "acctest-fabric1-%d"
location = azurerm_resource_group.test1.location
}

resource "azurerm_site_recovery_fabric" "test2" {
resource_group_name = azurerm_resource_group.test1.name
recovery_vault_name = azurerm_recovery_services_vault.test.name
name = "acctest-fabric2-%d"
location = "%s"
depends_on = [azurerm_site_recovery_fabric.test1]
}

resource "azurerm_site_recovery_protection_container" "test1" {
resource_group_name = azurerm_resource_group.test1.name
recovery_vault_name = azurerm_recovery_services_vault.test.name
recovery_fabric_name = azurerm_site_recovery_fabric.test1.name
name = "acctest-protection-cont1-%d"
}

resource "azurerm_site_recovery_protection_container" "test2" {
resource_group_name = azurerm_resource_group.test1.name
recovery_vault_name = azurerm_recovery_services_vault.test.name
recovery_fabric_name = azurerm_site_recovery_fabric.test2.name
name = "acctest-protection-cont2-%d"
}

resource "azurerm_site_recovery_replication_policy" "test" {
resource_group_name = azurerm_resource_group.test1.name
recovery_vault_name = azurerm_recovery_services_vault.test.name
name = "acctest-policy-%d"
recovery_point_retention_in_minutes = 24 * 60
application_consistent_snapshot_frequency_in_minutes = 4 * 60
}

resource "azurerm_site_recovery_protection_container_mapping" "test" {
resource_group_name = azurerm_resource_group.test1.name
recovery_vault_name = azurerm_recovery_services_vault.test.name
recovery_fabric_name = azurerm_site_recovery_fabric.test1.name
recovery_source_protection_container_name = azurerm_site_recovery_protection_container.test1.name
recovery_target_protection_container_id = azurerm_site_recovery_protection_container.test2.id
recovery_replication_policy_id = azurerm_site_recovery_replication_policy.test.id
name = "mapping-%d"
automatic_update {
enabled = %v
automation_account_id = azurerm_automation_account.test.id
}
}
`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.Locations.Secondary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, enabled)
}

func (t SiteRecoveryProtectionContainerMappingResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := replicationprotectioncontainermappings.ParseReplicationProtectionContainerMappingID(state.ID)
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,20 @@ The following arguments are supported:

* `recovery_replication_policy_id` - (Required) Id of the policy to use for this mapping. Changing this forces a new resource to be created.

* `automatic_update` - (Optional) a `automatic_update` block defined as below.

---

An `automatic_update` block supports the following:

* `enabled` - (Optional) Should the Mobility service installed on Azure virtual machines be automatically updated. Defaults to `false`.

~> **Note:** The setting applies to all Azure VMs protected in the same container. For more details see [this document](https://learn.microsoft.com/en-us/azure/site-recovery/azure-to-azure-autoupdate#enable-automatic-updates)

* `automation_account_id` - (Optional) The automation account ID which holds the automatic update runbook and authenticates to Azure resources.

~> **Note:** `automation_account_id` is required when `enabled` is set to `true`.

## Attributes Reference

In addition to the arguments above, the following attributes are exported:
Expand Down