| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
DOCUMENTATION = \ |
| 11 |
''' |
| 12 |
--- |
| 13 |
module: azure_rm_backupazurevm |
| 14 |
version_added: '1.1.0' |
| 15 |
short_description: Back up an Azure Virtual Machine using Azure Backup |
| 16 |
description: |
| 17 |
- Back up an Azure VM using Azure Backup. |
| 18 |
- Enabling/Updating protection for the Azure VM. |
| 19 |
- Trigger an on-demand backup for a protected Azure VM. |
| 20 |
- Stop protection but retain existing data. |
| 21 |
- Stop protection and delete data. |
| 22 |
options: |
| 23 |
resource_group: |
| 24 |
description: |
| 25 |
- The name of the resource group. |
| 26 |
required: true |
| 27 |
type: str |
| 28 |
recovery_vault_name: |
| 29 |
description: |
| 30 |
- The name of the Azure Recovery Service Vault. |
| 31 |
required: true |
| 32 |
type: str |
| 33 |
resource_id: |
| 34 |
description: |
| 35 |
- Azure Virtual Machine Resource ID. |
| 36 |
required: true |
| 37 |
type: str |
| 38 |
backup_policy_id: |
| 39 |
description: |
| 40 |
- Backup Policy ID present under Recovery Service Vault mentioned in recovery_vault_name field. |
| 41 |
required: true |
| 42 |
type: str |
| 43 |
recovery_point_expiry_time: |
| 44 |
description: |
| 45 |
- Recovery Point Expiry Time in UTC. |
| 46 |
- This used if C(state) parameter is C(backup). |
| 47 |
required: false |
| 48 |
type: str |
| 49 |
version_added: '1.15.0' |
| 50 |
state: |
| 51 |
description: |
| 52 |
- Assert the state of the protection item. |
| 53 |
- Use C(create) for enabling protection for the Azure VM. |
| 54 |
- Use C(update) for changing the policy of protection. |
| 55 |
- Use C(stop) for stop protection but retain existing data. |
| 56 |
- Use C(delete) for stop protection and delete data. |
| 57 |
- Use C(backup) for on-demand backup. |
| 58 |
default: create |
| 59 |
type: str |
| 60 |
choices: |
| 61 |
- create |
| 62 |
- update |
| 63 |
- delete |
| 64 |
- stop |
| 65 |
- backup |
| 66 |
extends_documentation_fragment: |
| 67 |
- azure.azcollection.azure |
| 68 |
- azure.azcollection.azure_tags |
| 69 |
author: |
| 70 |
- Suyeb Ansari (@suyeb786) |
| 71 |
- Pallavi Chaudhari (@PallaviC2510) |
| 72 |
|
| 73 |
''' |
| 74 |
|
| 75 |
EXAMPLES = \ |
| 76 |
''' |
| 77 |
- name: Enabling/Updating protection for the Azure VM |
| 78 |
azure_rm_backupazurevm: |
| 79 |
resource_group: 'myResourceGroup' |
| 80 |
recovery_vault_name: 'testVault' |
| 81 |
resource_id: '/subscriptions/<sub-id>/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/testVM' |
| 82 |
backup_policy_id: '/subscriptions/<sub-id>/resourceGroups/my-rg/providers/microsoft.recoveryservices/vaults/testVault/backupPolicies/ProdPolicy' |
| 83 |
state: 'create' |
| 84 |
- name: Stop protection but retain existing data |
| 85 |
azure_rm_backupazurevm: |
| 86 |
resource_group: 'my-rg' |
| 87 |
recovery_vault_name: 'testVault' |
| 88 |
resource_id: '/subscriptions/<sub-id>/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/testVM' |
| 89 |
state: 'stop' |
| 90 |
- name: Stop protection and delete data |
| 91 |
azure_rm_backupazurevm: |
| 92 |
resource_group: 'my-rg' |
| 93 |
recovery_vault_name: 'testVault' |
| 94 |
resource_id: '/subscriptions/<sub-id>/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/testVM' |
| 95 |
state: 'delete' |
| 96 |
- name: Trigger an on-demand backup for a protected Azure VM |
| 97 |
azure_rm_backupazurevm: |
| 98 |
resource_group: 'my-rg' |
| 99 |
recovery_vault_name: 'testVault' |
| 100 |
resource_id: '/subscriptions/<sub-id>/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/testVM' |
| 101 |
backup_policy_id: '/subscriptions/<sub-id>/resourceGroups/my-rg/providers/microsoft.recoveryservices/vaults/testVault/backupPolicies/ProdPolicy' |
| 102 |
recovery_point_expiry_time: '2023-02-09T06:00:00Z' |
| 103 |
state: 'backup' |
| 104 |
''' |
| 105 |
|
| 106 |
RETURN = \ |
| 107 |
''' |
| 108 |
id: |
| 109 |
description: |
| 110 |
- VM backup protection details. |
| 111 |
returned: always |
| 112 |
type: str |
| 113 |
sample: '{"response":{"id":"protection_id","name":"protection_item_name","properties":{}}}' |
| 114 |
''' |
| 115 |
|
| 116 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_rest import GenericRestClient |
| 117 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt |
| 118 |
import json |
| 119 |
|
| 120 |
|
| 121 |
class Actions: |
| 122 |
(NoAction, Create, Update, Delete) = range(4) |
| 123 |
|
| 124 |
|
| 125 |
class BackupAzureVM(AzureRMModuleBaseExt): |
| 126 |
def __init__(self): |
| 127 |
self.module_arg_spec = dict( |
| 128 |
resource_group=dict( |
| 129 |
type='str', |
| 130 |
required=True |
| 131 |
), |
| 132 |
recovery_vault_name=dict( |
| 133 |
type='str', |
| 134 |
required=True |
| 135 |
), |
| 136 |
resource_id=dict( |
| 137 |
type='str', |
| 138 |
required=True |
| 139 |
), |
| 140 |
backup_policy_id=dict( |
| 141 |
type='str', |
| 142 |
required=True |
| 143 |
), |
| 144 |
recovery_point_expiry_time=dict( |
| 145 |
type='str' |
| 146 |
), |
| 147 |
state=dict( |
| 148 |
type='str', |
| 149 |
default='create', |
| 150 |
choices=['create', 'update', 'delete', 'stop', 'backup'] |
| 151 |
) |
| 152 |
) |
| 153 |
|
| 154 |
self.resource_group = None |
| 155 |
self.recovery_vault_name = None |
| 156 |
self.resource_id = None |
| 157 |
self.backup_policy_id = None |
| 158 |
self.recovery_point_expiry_time = None |
| 159 |
self.state = None |
| 160 |
|
| 161 |
self.results = dict(changed=False) |
| 162 |
self.mgmt_client = None |
| 163 |
self.url = None |
| 164 |
self.status_code = [200, 201, 202, 204] |
| 165 |
self.to_do = Actions.NoAction |
| 166 |
|
| 167 |
self.body = {} |
| 168 |
self.query_parameters = {} |
| 169 |
self.query_parameters['api-version'] = None |
| 170 |
self.header_parameters = {} |
| 171 |
self.header_parameters['Content-Type'] = 'application/json; charset=utf-8' |
| 172 |
|
| 173 |
super(BackupAzureVM, self).__init__(derived_arg_spec=self.module_arg_spec, |
| 174 |
supports_check_mode=True, |
| 175 |
supports_tags=True) |
| 176 |
|
| 177 |
def get_api_version(self): |
| 178 |
return '2019-05-13' if self.state == 'create' or self.state == 'update' or self.state == 'delete' or self.state == 'stop' else '2016-12-01' |
| 179 |
|
| 180 |
def get_url(self): |
| 181 |
sub_id = self.subscription_id |
| 182 |
if self.module.params.get('subscription_id'): |
| 183 |
sub_id = self.module.params.get('subscription_id') |
| 184 |
if self.state == 'create' or self.state == 'update' or self.state == 'delete' or self.state == 'stop': |
| 185 |
return '/subscriptions' + '/' + sub_id \ |
| 186 |
+ '/resourceGroups' + '/' + self.resource_group + '/providers' \ |
| 187 |
+ '/Microsoft.RecoveryServices' + '/vaults' + '/' \ |
| 188 |
+ self.recovery_vault_name \ |
| 189 |
+ '/backupFabrics/Azure/protectionContainers/' \ |
| 190 |
+ 'iaasvmcontainer;iaasvmcontainerv2;' + self.parse_resource_to_dict(self.resource_id)['resource_group']\ |
| 191 |
+ ';' + self.parse_resource_to_dict(self.resource_id)['name'] + '/protectedItems/' \ |
| 192 |
+ 'vm;iaasvmcontainerv2;' + self.parse_resource_to_dict(self.resource_id)['resource_group'] + ';' \ |
| 193 |
+ self.parse_resource_to_dict(self.resource_id)['name'] |
| 194 |
if self.state == 'backup': |
| 195 |
return '/subscriptions' + '/' + sub_id \ |
| 196 |
+ '/resourceGroups' + '/' + self.resource_group + '/providers' \ |
| 197 |
+ '/Microsoft.RecoveryServices' + '/vaults' + '/' \ |
| 198 |
+ self.recovery_vault_name \ |
| 199 |
+ '/backupFabrics/Azure/protectionContainers/' \ |
| 200 |
+ 'iaasvmcontainer;iaasvmcontainerv2;' + self.parse_resource_to_dict(self.resource_id)['resource_group'] \ |
| 201 |
+ ';' + self.parse_resource_to_dict(self.resource_id)['name'] + '/protectedItems/' \ |
| 202 |
+ 'vm;iaasvmcontainerv2;' + self.parse_resource_to_dict(self.resource_id)['resource_group'] + ';' \ |
| 203 |
+ self.parse_resource_to_dict(self.resource_id)['name'] + '/backup' |
| 204 |
|
| 205 |
def get_body(self): |
| 206 |
if self.state == 'create' or self.state == 'update': |
| 207 |
return { |
| 208 |
'properties': |
| 209 |
{ |
| 210 |
'protectedItemType': 'Microsoft.Compute/virtualMachines', |
| 211 |
'sourceResourceId': self.resource_id, |
| 212 |
'policyId': self.backup_policy_id |
| 213 |
} |
| 214 |
} |
| 215 |
elif self.state == 'backup': |
| 216 |
body = { |
| 217 |
"properties": { |
| 218 |
"objectType": "IaasVMBackupRequest" |
| 219 |
} |
| 220 |
} |
| 221 |
if self.recovery_point_expiry_time: |
| 222 |
body["properties"]["recoveryPointExpiryTimeInUTC"] = self.recovery_point_expiry_time |
| 223 |
|
| 224 |
return body |
| 225 |
elif self.state == 'stop': |
| 226 |
return { |
| 227 |
"properties": { |
| 228 |
"protectedItemType": "Microsoft.Compute/virtualMachines", |
| 229 |
"sourceResourceId": self.resource_id, |
| 230 |
"protectionState": "ProtectionStopped" |
| 231 |
} |
| 232 |
} |
| 233 |
else: |
| 234 |
return {} |
| 235 |
|
| 236 |
def exec_module(self, **kwargs): |
| 237 |
for key in list(self.module_arg_spec.keys()): |
| 238 |
if hasattr(self, key): |
| 239 |
setattr(self, key, kwargs[key]) |
| 240 |
elif kwargs[key] is not None: |
| 241 |
self.body[key] = kwargs[key] |
| 242 |
|
| 243 |
self.inflate_parameters(self.module_arg_spec, self.body, 0) |
| 244 |
|
| 245 |
self.query_parameters['api-version'] = self.get_api_version() |
| 246 |
self.url = self.get_url() |
| 247 |
self.body = self.get_body() |
| 248 |
old_response = None |
| 249 |
response = None |
| 250 |
|
| 251 |
self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient, |
| 252 |
base_url=self._cloud_environment.endpoints.resource_manager) |
| 253 |
|
| 254 |
changed = False |
| 255 |
if self.state == 'create' or self.state == 'update': |
| 256 |
changed = True |
| 257 |
response = self.enable_update_protection_for_azure_vm() |
| 258 |
if self.state == 'delete': |
| 259 |
changed = True |
| 260 |
response = self.stop_protection_and_delete_data() |
| 261 |
if self.state == 'stop': |
| 262 |
changed = True |
| 263 |
response = self.stop_protection_but_retain_existing_data() |
| 264 |
if self.state == 'backup': |
| 265 |
changed = True |
| 266 |
response = self.trigger_on_demand_backup() |
| 267 |
self.results['response'] = response |
| 268 |
self.results['changed'] = changed |
| 269 |
|
| 270 |
return self.results |
| 271 |
|
| 272 |
def enable_update_protection_for_azure_vm(self): |
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
try: |
| 277 |
response = self.mgmt_client.query( |
| 278 |
self.url, |
| 279 |
'PUT', |
| 280 |
self.query_parameters, |
| 281 |
self.header_parameters, |
| 282 |
self.body, |
| 283 |
self.status_code, |
| 284 |
600, |
| 285 |
30, |
| 286 |
) |
| 287 |
except Exception as e: |
| 288 |
self.log('Error in enabling/updating protection for Azure VM.') |
| 289 |
self.fail( |
| 290 |
'Error in creating/updating protection for Azure VM {0}'.format(str(e))) |
| 291 |
|
| 292 |
if hasattr(response, 'body'): |
| 293 |
response = json.loads(response.body()) |
| 294 |
elif hasattr(response, 'context'): |
| 295 |
response = response.context['deserialized_data'] |
| 296 |
else: |
| 297 |
self.fail("Create or Updating fail, no match message return, return info as {0}".format(response)) |
| 298 |
|
| 299 |
return response |
| 300 |
|
| 301 |
def stop_protection_but_retain_existing_data(self): |
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
try: |
| 306 |
response = self.mgmt_client.query( |
| 307 |
self.url, |
| 308 |
'PUT', |
| 309 |
self.query_parameters, |
| 310 |
self.header_parameters, |
| 311 |
self.body, |
| 312 |
self.status_code, |
| 313 |
600, |
| 314 |
30, |
| 315 |
) |
| 316 |
except Exception as e: |
| 317 |
self.log('Error attempting to stop protection.') |
| 318 |
self.fail('Error in disabling the protection: {0}'.format(str(e))) |
| 319 |
|
| 320 |
if hasattr(response, 'body'): |
| 321 |
response = json.loads(response.body()) |
| 322 |
elif hasattr(response, 'context'): |
| 323 |
response = response.context['deserialized_data'] |
| 324 |
else: |
| 325 |
self.fail("Create or Updating fail, no match message return, return info as {0}".format(response)) |
| 326 |
|
| 327 |
return response |
| 328 |
|
| 329 |
def stop_protection_and_delete_data(self): |
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
try: |
| 334 |
response = self.mgmt_client.query( |
| 335 |
self.url, |
| 336 |
'DELETE', |
| 337 |
self.query_parameters, |
| 338 |
self.header_parameters, |
| 339 |
None, |
| 340 |
self.status_code, |
| 341 |
600, |
| 342 |
30, |
| 343 |
) |
| 344 |
except Exception as e: |
| 345 |
self.log('Error attempting to delete backup.') |
| 346 |
self.fail('Error deleting the azure backup: {0}'.format(str(e))) |
| 347 |
|
| 348 |
if hasattr(response, 'body'): |
| 349 |
response = json.loads(response.body()) |
| 350 |
elif hasattr(response, 'context'): |
| 351 |
response = response.context['deserialized_data'] |
| 352 |
else: |
| 353 |
self.fail("Create or Updating fail, no match message return, return info as {0}".format(response)) |
| 354 |
|
| 355 |
return response |
| 356 |
|
| 357 |
def trigger_on_demand_backup(self): |
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
try: |
| 362 |
response = self.mgmt_client.query( |
| 363 |
self.url, |
| 364 |
'POST', |
| 365 |
self.query_parameters, |
| 366 |
self.header_parameters, |
| 367 |
self.body, |
| 368 |
self.status_code, |
| 369 |
600, |
| 370 |
30, |
| 371 |
) |
| 372 |
except Exception as e: |
| 373 |
self.log('Error attempting to backup azure vm.') |
| 374 |
self.fail( |
| 375 |
'Error while taking on-demand backup: {0}'.format(str(e))) |
| 376 |
|
| 377 |
response = dict(msg='The backup has been successfully triggered, please monitor the backup process on the Backup Jobs page') |
| 378 |
return response |
| 379 |
|
| 380 |
|
| 381 |
def main(): |
| 382 |
BackupAzureVM() |
| 383 |
|
| 384 |
|
| 385 |
if __name__ == '__main__': |
| 386 |
main() |