azure-sdk-for-cpp/sdk/keyvault/azure-security-keyvault-secrets/samples/sample2_backup_restore.md
George Arama bd08d226e1
relocate kv samples (#5582)
* relocate kv samples

* temp removal of links
2024-04-30 22:09:49 +00:00

3.1 KiB

Backup and Restore secrets

This sample demonstrates how to backup and restore in Azure Key Vault. To get started, you'll need a URI to an Azure Key Vault.

Creating a SecretClient

To create a new SecretClient to create, get, update, or delete secrets, you need the endpoint to an Azure Key Vault and credentials.

Key Vault Secrets client for C++ currently supports any TokenCredential for authenticating.

In the sample below, you can create a credential by setting the Tenant ID, Client ID and Client Secret as environment variables.

auto credential = std::make_shared<Azure::Identity::DefaultAzureCredential>();

Then, in the sample below, you can set keyVaultUrl based on an environment variable, configuration setting, or any way that works for your application.

SecretClient secretClient(std::getenv("AZURE_KEYVAULT_URL"), credential);

Creating a Secret

Call SetSecret to create a secret with the name and secret value.

std::string secretName("MySampleSecret");
std::string secretValue("my secret value");

secretClient.SetSecret(secretName, secretValue);

Getting a Secret

Call GetSecret to retrieve a secret from Key Vault.

// get secret
KeyVaultSecret secret = secretClient.GetSecret(secretName).Value;

std::string valueString = secret.Value.HasValue() ? secret.Value.Value() : "NONE RETURNED";
std::cout << "Secret is returned with name " << secret.Name << " and value "
          << valueString << std::endl;

Creating a Backup for the secret properties

Call BackupSecret to retrieve the secret backup. BackupSecret will will return a vector of bytes representing the backed up content.

std::cout << "\t-Backup secret" << std::endl;
std::vector<uint8_t> backupSecret(secretClient.BackupSecret(secret.Name).Value.Secret);
backUpSize = backupSecret.size();

Deleting the secret in order to later restore it

Call StartDeleteSecret to delete a secret. This is a long running operation.

// start deleting the secret
DeleteSecretOperation operation = secretClient.StartDeleteSecret(secret.Name);

Purging a deleted secret

If the Azure Key Vault is soft delete-enabled and you want to permanently delete the secret before its ScheduledPurgeDate, the secret needs to be purged.

// You only need to wait for completion if you want to purge or recover the secret.
operation.PollUntilDone(2s);

// purge the deleted secret
secretClient.PurgeDeletedSecret(secret.Name);

Restoring a secret

Call RestoreSecretBackup to restore a secret from a backup obtained at the previous(backup) step.

std::cout << "\t-Restore Secret" << std::endl;
auto restoredSecret = secretClient.RestoreSecretBackup(backedUpSecret).Value;

Source

To see the full example source, see: Source Code