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_backup_protected_vm - split create and update function to fix lifecycle - ignore #26583

Merged
merged 2 commits into from
Jul 10, 2024
Merged
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
196 changes: 141 additions & 55 deletions internal/services/recoveryservices/backup_protected_vm_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ import (

func resourceRecoveryServicesBackupProtectedVM() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceRecoveryServicesBackupProtectedVMCreateUpdate,
Create: resourceRecoveryServicesBackupProtectedVMCreate,
Read: resourceRecoveryServicesBackupProtectedVMRead,
Update: resourceRecoveryServicesBackupProtectedVMCreateUpdate,
Update: resourceRecoveryServicesBackupProtectedVMUpdate,
Delete: resourceRecoveryServicesBackupProtectedVMDelete,

Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
Expand All @@ -59,28 +59,25 @@ func resourceRecoveryServicesBackupProtectedVM() *pluginsdk.Resource {
}
}

func resourceRecoveryServicesBackupProtectedVMCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
func resourceRecoveryServicesBackupProtectedVMCreate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).RecoveryServices.ProtectedItemsClient
opClient := meta.(*clients.Client).RecoveryServices.ProtectedItemOperationResultsClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()

resourceGroup := d.Get("resource_group_name").(string)

vaultName := d.Get("recovery_vault_name").(string)

// source_vm_id must be specified at creation time but can be removed during update
if d.IsNewResource() {
if _, ok := d.GetOk("source_vm_id"); !ok {
return fmt.Errorf("`source_vm_id` must be specified when creating")
}
if _, ok := d.GetOk("source_vm_id"); !ok {
return fmt.Errorf("`source_vm_id` must be specified when creating")
Copy link
Member

Choose a reason for hiding this comment

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

I can't comment on the line, but there's a d.IsNewResource() check on line 81 which can be removed as well.

}

vmId := d.Get("source_vm_id").(string)
policyId := d.Get("backup_policy_id").(string)

if d.IsNewResource() && policyId == "" {
if policyId == "" {
return fmt.Errorf("`backup_policy_id` must be specified during creation")
}

Expand All @@ -93,42 +90,39 @@ func resourceRecoveryServicesBackupProtectedVMCreateUpdate(d *pluginsdk.Resource
protectedItemName := fmt.Sprintf("VM;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroupName, parsedVmId.VirtualMachineName)
containerName := fmt.Sprintf("iaasvmcontainer;iaasvmcontainerv2;%s;%s", parsedVmId.ResourceGroupName, parsedVmId.VirtualMachineName)

log.Printf("[DEBUG] Creating/updating Azure Backup Protected VM %s (resource group %q)", protectedItemName, resourceGroup)
log.Printf("[DEBUG] Creating Azure Backup Protected VM %s (resource group %q)", protectedItemName, resourceGroup)

id := protecteditems.NewProtectedItemID(subscriptionId, resourceGroup, vaultName, "Azure", containerName, protectedItemName)

if d.IsNewResource() {
existing, err := client.Get(ctx, id, protecteditems.GetOperationOptions{})
if err != nil {
if !response.WasNotFound(existing.HttpResponse) {
return fmt.Errorf("checking for presence of existing %s: %+v", id, err)
}
existing, err := client.Get(ctx, id, protecteditems.GetOperationOptions{})
if err != nil {
if !response.WasNotFound(existing.HttpResponse) {
return fmt.Errorf("checking for presence of existing %s: %+v", id, err)
}
}

if !response.WasNotFound(existing.HttpResponse) {
isSoftDeleted := false
if existing.Model != nil && existing.Model.Properties != nil {
if prop, ok := existing.Model.Properties.(protecteditems.AzureIaaSComputeVMProtectedItem); ok {
isSoftDeleted = pointer.From(prop.IsScheduledForDeferredDelete)
}
if !response.WasNotFound(existing.HttpResponse) {
isSoftDeleted := false
if existing.Model != nil && existing.Model.Properties != nil {
if prop, ok := existing.Model.Properties.(protecteditems.AzureIaaSComputeVMProtectedItem); ok {
isSoftDeleted = pointer.From(prop.IsScheduledForDeferredDelete)
}
}

if isSoftDeleted {
if meta.(*clients.Client).Features.RecoveryServicesVault.RecoverSoftDeletedBackupProtectedVM {
err = resourceRecoveryServicesVaultBackupProtectedVMRecoverSoftDeleted(ctx, client, opClient, id)
if err != nil {
return fmt.Errorf("recovering soft deleted %s: %+v", id, err)
}
} else {
return fmt.Errorf(optedOutOfRecoveringSoftDeletedBackupProtectedVMFmt(parsedVmId.ID(), vaultName))
if isSoftDeleted {
if meta.(*clients.Client).Features.RecoveryServicesVault.RecoverSoftDeletedBackupProtectedVM {
err = resourceRecoveryServicesVaultBackupProtectedVMRecoverSoftDeleted(ctx, client, opClient, id)
if err != nil {
return fmt.Errorf("recovering soft deleted %s: %+v", id, err)
}
}

if !isSoftDeleted {
return tf.ImportAsExistsError("azurerm_backup_protected_vm", id.ID())
} else {
return fmt.Errorf(optedOutOfRecoveringSoftDeletedBackupProtectedVMFmt(parsedVmId.ID(), vaultName))
}
}

if !isSoftDeleted {
return tf.ImportAsExistsError("azurerm_backup_protected_vm", id.ID())
}
}

item := protecteditems.ProtectedItemResource{
Expand All @@ -145,27 +139,23 @@ func resourceRecoveryServicesBackupProtectedVMCreateUpdate(d *pluginsdk.Resource
protectionState, ok := d.GetOk("protection_state")
protectionStopped := strings.EqualFold(protectionState.(string), string(protecteditems.ProtectionStateProtectionStopped))
requireUpdateProtectionState := ok && protectionStopped
skipNormalUpdate := protectionStopped && !d.IsNewResource()

// stopped protected item has no `backup_policy_id`, though we can update it before stopping we can not read it.
if !skipNormalUpdate {
resp, err := client.CreateOrUpdate(ctx, id, item)
if err != nil {
return fmt.Errorf("creating/updating Azure Backup Protected VM %q (Resource Group %q): %+v", protectedItemName, resourceGroup, err)
}

operationId, err := parseBackupOperationId(resp.HttpResponse)
if err != nil {
return fmt.Errorf("issuing creating/updating request for %s: %+v", id, err)
}
resp, err := client.CreateOrUpdate(ctx, id, item)
if err != nil {
return fmt.Errorf("creating %s: %+v", id, err)
}

if err = resourceRecoveryServicesBackupProtectedVMWaitForStateCreateUpdate(ctx, opClient, id, operationId); err != nil {
return err
}
operationId, err := parseBackupOperationId(resp.HttpResponse)
if err != nil {
return fmt.Errorf("issuing create request for %s: %+v", id, err)
}

d.SetId(id.ID())
if err = resourceRecoveryServicesBackupProtectedVMWaitForStateCreateUpdate(ctx, opClient, id, operationId); err != nil {
return err
}

d.SetId(id.ID())

// the protection state will be updated in the additional update.
if requireUpdateProtectionState {
p := protecteditems.ProtectionState(protectionState.(string))
Expand All @@ -176,14 +166,14 @@ func resourceRecoveryServicesBackupProtectedVMCreateUpdate(d *pluginsdk.Resource
},
}

resp, err := client.CreateOrUpdate(ctx, id, updateInput)
resp, err = client.CreateOrUpdate(ctx, id, updateInput)
if err != nil {
return fmt.Errorf("creating/updating %s: %+v", id, err)
return fmt.Errorf("creating %s: %+v", id, err)
}

operationId, err := parseBackupOperationId(resp.HttpResponse)
operationId, err = parseBackupOperationId(resp.HttpResponse)
if err != nil {
return fmt.Errorf("issuing creating/updating request for %s: %+v", id, err)
return fmt.Errorf("issuing create request for %s: %+v", id, err)
}

if err = resourceRecoveryServicesBackupProtectedVMWaitForStateCreateUpdate(ctx, opClient, id, operationId); err != nil {
Expand Down Expand Up @@ -258,6 +248,102 @@ func resourceRecoveryServicesBackupProtectedVMRead(d *pluginsdk.ResourceData, me
return nil
}

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

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

existing, err := client.Get(ctx, *id, protecteditems.GetOperationOptions{})
if err != nil {
return err
}

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

if existing.Model.Properties == nil {
return fmt.Errorf("retrieving %s: `properties` was nil", id)
}

if _, ok := existing.Model.Properties.(protecteditems.AzureIaaSComputeVMProtectedItem); !ok {
return fmt.Errorf("retrieving %s: `properties` was not a VM Protected Item", id)
}

model := *existing.Model
properties := existing.Model.Properties.(protecteditems.AzureIaaSComputeVMProtectedItem)
updateProtectedBackup := false

if d.HasChange("backup_policy_id") {
properties.PolicyId = pointer.To(d.Get("backup_policy_id").(string))
updateProtectedBackup = true
}

if d.HasChange("exclude_disk_luns") || d.HasChange("include_disk_luns") {
properties.ExtendedProperties = expandDiskExclusion(d)
updateProtectedBackup = true
}

model.Properties = properties

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

operationId, err := parseBackupOperationId(resp.HttpResponse)
if err != nil {
return fmt.Errorf("issuing update request for %s: %+v", id, err)
}

if err = resourceRecoveryServicesBackupProtectedVMWaitForStateCreateUpdate(ctx, opClient, *id, operationId); err != nil {
return err
}
}

protectionState := string(pointer.From(properties.ProtectionState))
protectionStopped := false
if d.HasChange("protection_state") {
protectionState = d.Get("protection_state").(string)
protectionStopped = strings.EqualFold(protectionState, string(protecteditems.ProtectionStateProtectionStopped))
}

// the protection state will be updated in the additional update.
if protectionStopped {
p := protecteditems.ProtectionState(protectionState)
vmId := d.Get("source_vm_id").(string)
updateInput := protecteditems.ProtectedItemResource{
Properties: &protecteditems.AzureIaaSComputeVMProtectedItem{
ProtectionState: &p,
SourceResourceId: utils.String(vmId),
},
}

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

operationId, err := parseBackupOperationId(resp.HttpResponse)
if err != nil {
return fmt.Errorf("issuing update request for %s: %+v", id, err)
}

if err = resourceRecoveryServicesBackupProtectedVMWaitForStateCreateUpdate(ctx, opClient, *id, operationId); err != nil {
return err
}
}

return resourceRecoveryServicesBackupProtectedVMRead(d, meta)
}

func resourceRecoveryServicesBackupProtectedVMDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).RecoveryServices.ProtectedItemsClient
opResultClient := meta.(*clients.Client).RecoveryServices.BackupOperationResultsClient
Expand Down
Loading