Поделиться через


Back up Azure Database for PostgreSQL - Flexible Server using Azure CLI

This article describes how to back up Azure Database for PostgreSQL - Flexible Server using Azure CLI.

Предпосылки

Before you back up Azure Database for PostgreSQL - Flexible Server, review the supported scenarios and limitations for backing up Azure Database for PostgreSQL - Flexible Servers.

Create a Backup vault

Backup vault is a storage entity in Azure. This stores the backup data for new workloads that Azure Backup supports. For example, Azure Database for PostgreSQL – Flexible servers, blobs in a storage account, and Azure Disks. Backup vaults help to organize your backup data, while minimizing management overhead. Backup vaults are based on the Azure Resource Manager model of Azure, which provides enhanced capabilities to help secure backup data.

Before you create a Backup vault, choose the storage redundancy of the data within the vault. Then proceed to create the Backup vault with that storage redundancy and the location.

В этой статье мы создадим хранилище TestBkpVaultрезервных копий в регионе westusв группе testBkpVaultRGресурсов. az dataprotection vault create Используйте команду для создания хранилища резервных копий. Learn more about creating a Backup vault.

az dataprotection backup-vault create -g testBkpVaultRG --vault-name TestBkpVault -l westus --type SystemAssigned --storage-settings datastore-type="VaultStore" type="LocallyRedundant"

{
  "eTag": null,
  "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/testBkpVaultRG/providers/Microsoft.DataProtection/BackupVaults/TestBkpVault",
  "identity": {
    "principalId": "aaaaaaaa-bbbb-cccc-1111-222222222222",
    "tenantId": "aaaabbbb-0000-cccc-1111-dddd2222eeee",
    "type": "SystemAssigned"
  },
  "location": "westus",
  "name": "TestBkpVault",
  "properties": {
    "provisioningState": "Succeeded",
    "storageSettings": [
      {
        "datastoreType": "VaultStore",
        "type": "LocallyRedundant"
      }
    ]
  },
  "resourceGroup": "testBkpVaultRG",
  "systemData": null,
  "tags": null,
  "type": "Microsoft.DataProtection/backupVaults"
}

Configure backup

Перед настройкой защиты базы данных убедитесь, что вы создадите политику резервного копирования. После создания хранилища и политики защитите базу данных Azure для PostgreSQL — гибкий сервер, выполнив следующие действия:

  • Fetch the ARM ID of the PostgreSQL - Flexible Server to be protected
  • Предоставление доступа к хранилищу резервных копий
  • Подготовка запроса конфигурации резервного копирования

Fetch the ARM ID of the PostgreSQL - Flexible Server to be protected

Получите идентификатор Azure Resource Manager (ARM ID) гибкого сервера PostgreSQL, который нужно защитить. Этот идентификатор служит идентификатором базы данных. Давайте рассмотрим пример базы данных с именем empdb11, находящейся на гибком сервере PostgreSQL под именем testposgresql, который присутствует в группе ресурсов ossrg в другой подписке.

The following example uses bash.

ossId="/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/ossrg/providers/Microsoft.DBforPostgreSQL/flexibleServers/archive-postgresql-ccy/databases/empdb11"

Предоставление доступа к хранилищу резервных копий

Хранилищу резервных копий необходимо подключиться к серверу PostgreSQL – Flexible Server, а затем получить доступ к базе данных с помощью ключей из хранилища. So, it requires access to the PostgreSQL – Flexible server and the key vault. Grant access to the Backup vault's Managed-Service Identity (MSI).

Check the permissions required for the Backup vault's Managed-Service Identity (MSI) on the PostgreSQL – Flexible Server and Azure Key vault that stores keys to the database.

Подготовка запроса конфигурации резервного копирования

Once all the relevant permissions are set, configure the backup by running the following commands:

  1. Prepare the relevant request by using the relevant vault, policy, PostgreSQL – Flexible server database using the az dataprotection backup-instance initialize command.

    az dataprotection backup-instance initialize --datasource-id $ossId --datasource-type AzureDatabaseForPostgreSQLFlexibleServer -l <vault-location> --policy-id <policy_arm_id>  --secret-store-type AzureKeyVault --secret-store-uri $keyURI > OSSBkpInstance.JSON
    
  2. Submit the request to protect the database using the az dataprotection backup-instance create command.

    az dataprotection backup-instance create --resource-group testBkpVaultRG --vault-name TestBkpVault TestBkpvault --backup-instance .\OSSBkpInstance.JSON
    

Run an on-demand backup

Specify a retention rule while you trigger backup. To view the retention rules in policy, go to the policy JSON file for retention rules. In the following example, there are two retention rules with names Default and Monthly. Let's use the Monthly rule for the on-demand backup.

az dataprotection backup-policy show  -g ossdemorg --vault-name ossdemovault-1 --subscription e3d2d341-4ddb-4c5d-9121-69b7e719485e --name osspol5

{
  "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e-69b7e719485e/resourceGroups/ossdemorg/providers/Microsoft.DataProtection/backupVaults/ossdemovault-1/backupPolicies/osspol5",
  "name": "osspol5",
  "properties": {
    "datasourceTypes": [
      " Microsoft.DBforPostgreSQL/flexibleServers/databases" 
    ],
    "objectType": "BackupPolicy",
    "policyRules": [
      {
        "backupParameters": {
          "backupType": "Full",
          "objectType": "AzureBackupParams"
        },
        "dataStore": {
          "dataStoreType": "VaultStore",
          "objectType": "DataStoreInfoBase"
        },
        "name": "BackupWeekly",
        "objectType": "AzureBackupRule",
        "trigger": {
          "objectType": "ScheduleBasedTriggerContext",
          "schedule": {
            "repeatingTimeIntervals": [
              "R/2020-04-04T20:00:00+00:00/P1W",
              "R/2020-04-01T20:00:00+00:00/P1W"
            ],
            "timeZone": "UTC"
          },
          "taggingCriteria": [
            {
              "criteria": [
                {
                  "absoluteCriteria": [
                    "FirstOfMonth"
                  ],
                  "daysOfMonth": null,
                  "daysOfTheWeek": null,
                  "monthsOfYear": null,
                  "objectType": "ScheduleBasedBackupCriteria",
                  "scheduleTimes": null,
                  "weeksOfTheMonth": null
                }
              ],
              "isDefault": false,
              "tagInfo": {
                "eTag": null,
                "id": "Monthly_",
                "tagName": "Monthly"
              },
              "taggingPriority": 15
            },
            {
              "criteria": null,
              "isDefault": true,
              "tagInfo": {
                "eTag": null,
                "id": "Default_",
                "tagName": "Default"
              },
              "taggingPriority": 99
            }
          ]
        }
      },
      {
        "isDefault": false,
        "lifecycles": [
          {
            "deleteAfter": {
              "duration": "P10Y",
              "objectType": "AbsoluteDeleteOption"
            },
            "sourceDataStore": {
              "dataStoreType": "VaultStore",
              "objectType": "DataStoreInfoBase"
            },
            "targetDataStoreCopySettings": []
          }
        ],
        "name": "Monthly",
        "objectType": "AzureRetentionRule"
      },
      {
        "isDefault": true,
        "lifecycles": [
          {
            "deleteAfter": {
              "duration": "P1Y",
              "objectType": "AbsoluteDeleteOption"
            },
            "sourceDataStore": {
              "dataStoreType": "VaultStore",
              "objectType": "DataStoreInfoBase"
            },
            "targetDataStoreCopySettings": []
          }
        ],
        "name": "Default",
        "objectType": "AzureRetentionRule"
      }
    ]
  },
  "resourceGroup": "ossdemorg",
  "systemData": null,
  "type": "Microsoft.DataProtection/backupVaults/backupPolicies"
}

Чтобы активировать резервную копию по запросу az dataprotection backup-instance adhoc-backup , используйте команду.

az dataprotection backup-instance adhoc-backup --name "ossrg-empdb11" --rule-name "Monthly" --resource-group testBkpVaultRG --vault-name TestBkpVault

Track jobs

Отслеживайте все задания с помощью az dataprotection job list команды. You can list all jobs and fetch a particular job detail.

Для отслеживания всех заданий во всех хранилищах Backup можно также использовать Az.ResourceGraph. Используйте команду az dataprotection job list-from-resourcegraph для получения соответствующих заданий, распределенных по хранилищам резервных копий.

az dataprotection job list-from-resourcegraph --datasource-type AzureDatabaseForPostgreSQLFlexibleServer --status Completed

Next steps