NKDev
NKDev

Reputation: 474

Creating Azure Key Vault using .NET assembly (Microsoft.Azure.KeyVault)

I am writing a .Net console application to create Key Vault but not able to find class/method in Microsoft.Azure.KeyVault assembly that allows creating Vault and setting service principal to that vault.

Can someone please point me to the assembly/class that i can use to create vault.

Thanks

Upvotes: 0

Views: 965

Answers (2)

Rick Rainey
Rick Rainey

Reputation: 11246

The class you are looking for is the KeyVaultManagementClient in the Microsoft.Azure.Management.KeyVault namespace. This is defined in the management KeyVault assembly you can get from NuGet.

enter image description here

The main parts of the code to do this are shown below. However, be advised that I have abbreviated some things (properties, subscription credentials, etc.) that you will have to further define and initialize. If you want to see a complete solution check out the samples in the .NET Azure SDK, in particular, the KeyVaultManagement.Tests project.

        // The resource group to create the vault in.
        const string resourceGroupName = "Vaults-Resource-Group";

        // The name of the vault to create.
        const string vaultName = "web-app-01-vault";

        // Define access policies to keys and secrets (abbreviated just to illustrate...)
        var accessPolicy = new AccessPolicyEntry
        {
            ApplicationId = sp, 
            PermissionsToKeys = new string[] { "all" }, 
            PermissionsToSecrets = new string[] { "backup", "create", "delete" } //etc.  just to name a few
        };

        // Define vault properties (abbreviated just to illustrate...)
        VaultProperties vaultProps = new VaultProperties()
        {
            EnabledForTemplateDeployment = true,
            AccessPolicies = new List<AccessPolicyEntry>()
            {
                accessPolicy
            }
        };

        // Initialize 'create parameters' to create the vault in "West US"
        VaultCreateOrUpdateParameters vaultParams = new VaultCreateOrUpdateParameters(vaultProps, "westus");

        // Initialize an instance to the mgmt client
        // NOTE: Need to initialize creds derived from SubscriptionCloudCredentials
        KeyVaultManagementClient mgmtClient = new KeyVaultManagementClient(creds);

        // Create the vault
        mgmtClient.Vaults.CreateOrUpdateAsync(resourceGroupName, vaultName, vaultParams);

Upvotes: 2

Alex Belotserkovskiy
Alex Belotserkovskiy

Reputation: 4062

For some reason, there is no such functionality in the client SDK (or, at least, i was not able to find that as well even by going through the code placed on the Github repo of the SDK). There is the REST API for Create/Update key vault, so you may create that by using that. Or PowerShell - it is possible to execute Powershell from C# and i tried to do that - it works, but should be tested.

Upvotes: 0

Related Questions