Azure DevOps - ARM deployment - Key Vault and Managed Identities - azure

I am seeking some clarity on the best way to integrate Key Vault in ARM deployments within Azure DevOps.
For example, deploying an App Service and creating a Managed Service Identity so that it can get secrets from the key vault for a pre-existing Database.
1) In the Azure portal, I have manually created a new Service Principal for the App service with "Get" and "List" permissions in the access policy.
2) In My DevOps Project under the project settings I have created a service connection.
3) I have created a Variable group in DevOps with relevant Key Vault Secrets.
4) In my App Service ARM template i have referenced the Service Identity with reference to the Variable Parameters.
Is this the correct way to integrate Key Vault with a DevOps Deployment?
Whenever I need to deploy a new service to the environment (say now I want to deploy an API), do I need to manually create another Managed Identity in Azure for the Key Vault Access or is there a way to create it as part of the initial deployment of the API service?
Thank you in advance for your assistance.

If you are using MSI it is recommend to set this in the ARM template by putting
"identity": {
"type": "SystemAssigned"
},
In defining the app service. This will recreate the MSI with every deployment. It will be named the same but will have a different thumbprint in AD after each deployment. For purposes with Key Vault this is perfectly fine.
Within your Key Vault ARM template (if it's not all in the same template) The access policy can reference the MSI by:
"tenantID": "[subscription().tenantId]",
"objectId": "[reference(resourceId('Microsoft.Web/sites', INSERT APP SERVICE NAME), '2018-02-01', 'Full').identity.principalId]",
This will reference the ID being created by the App Service deployment.
If using this be sure to have the App Service config depend on the Key Vault and secrets (if referencing secrets in the ARM template), the Access Policy depends on the Key Vault and App Service creation, and any secret being created set to depend on the Key Vault as well to ensure assignments happen in the right order.

Related

Provision Secrets from Azure Key Vault to Azure App Service as environment variables

I have:
Azure App Service with a Docker container running in it. Inside the Docker container, there is a Python FastAPI Web App.
Azure Key Vault with some App specific secrets in it (e.g. Public API Client Secret for a side service to send requests to)
I'm trying to set secrets to the App.
There are several examples when an app directly reads the secrets from Key Vault (e.g. official MS documentation), but I believe the provisioning should not be the responsibility of the App.
Probably, secrets should be set as environment variables with the CD pipeline (correct me if it's a bad idea). Otherwise, the App knows details about the infrastructure where it's running, which, I guess, is not the best practice.
Is there a proper way to provision Key Vault secrets to the App environment?
I tried to reproduce the same issue in my environment and got the below results
I have created the app service
The azure key vaults supplies a way to store keys & secrets outside of an application, Using access polices we can allow the application to access the keys with in keyvault
To access the keyvault as a environment variables in the azure app service we have to setup the polices mentioned as below
In the app services => identity => click on status is ON
Go to the keyvault and the polices settings click on add polices
And the access polices page set any permissions for keys and secrets
In the select principal page search for the app service name and select then the app service can access as a environment variables
After that we have to add specific secrets in the app service and copy its in secret identifier as below format
#microsoft.keyvault(secretUri={secret url from the keyvault})
After adding the secret it will look like as below
By following the above steps we can access the secrets as a environment variables

App Service Key Vault Reference breaks when re-deploying ARM template

I have an Azure App Service Web App using Key Vault References for several application settings. All resources are deployed and configured through an Bicep/ARM template. The secrets in Key Vault and Access Policies are set through the Bicep/ARM template as well. The Web App works great and has access to Key Vault through those references until I re-deploy the Bicep / ARM template to modify some unrelated values. After running "az deployment group create" the references break (showing red cross in application settings). I found two workarounds to make them connect again:
Restart Web App
Create another app setting / modify a setting in the portal and save
I would like to understand the root cause / possible mistake and why the work-arrounds help. I checked, and the Secrets in Key Vault are not changed / updated when re-deploying the template. My assumption is that this is caused by the Key Vault API removing and re-creating the Access Policies each time the template gets deployed. A what-if deployment of the template tells me that the removal and re-creation of the Access Policies is happening.
As mentioned by #Deepdave in the comment section. ARM does not allow a key vault to be redeployed with out clearing existing access polices.
Please submit your feedback here https://feedback.azure.com/forums/34192--general-feedback

Fetch value from Azure Key Vault reference (Managed identity)

I am trying to fetch secret values from azure key vault in Azure App Service.
My App Service has a managed identity
In the Azure Key vault, this managed identity is added under 'Role assignments' as 'Key vault contributor'
Also access policies has been added in azure key vault to give 'Get' permission to the AppServices's managed identity
Now in my c# code, I am trying to get the value of the AppSetting element using the code
ConfigurationManager.AppSettings['something'];
In my azure app service, under app settings, I have added the a key with name 'something' and it has the value pointing to the reference of the Key Vault as below:
#Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)
Now I am able to retrieve the value from the appsettings, but instead of the actual value, it is pulling the output as #Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/c96f02080254f109c51a1f1cdb1931)
I am expecting the output to be value that I have set, not the keyvault reference string itself.
I am using .Net MVC 4.7 web app
As junnas said, you just add webapp's MSI in key vault Access policy.
1.Turn on webapp System-assign managed identity.
2.Add the identity into keyvault Access policy with secret Get permission.
3.Add the reference of the Key Vault into webapp Application settings.
4.Use Environment.GetEnvironmentVariable("AppsettingName"); to get the secret vaule.
Here is the output:
Actually i figured out that even using ConfiguraionManager.AppSettings["keyname"] also works fine. In my case, i had done everything as listed above , but had enabled "Slot Deployment" option in Connection string configuration in App Service. Once i enabled, now i am able to access my key vault secrets.

Adding a Key Vault Access Policy to an Existing Key Vault via ARM

I am trying to do an ARM deployment in Azure Devops whereby I add a key vault access policy to an existing key vault in Azure.
I want to use the following ARM template which adds an access policy to an existing Key Vault: https://github.com/Azure/azure-quickstart-templates/tree/master/101-keyvault-add-access-policy
I have a separate template that deploys an App service and creates a system assigned managed identity.
What is the best way to link the two templates? how do i reference the System Assigned identity of the app service in the 'Add Key Vault Policy' ARM template if I dont know what the object ID of the service Principle is yet?
here's a sample how you would retrieve the managed identity Id in your other template:
"[reference(concat(resourceId('Microsoft.Web/sites/', %wep_app_name%), '/providers/Microsoft.ManagedIdentity/Identities/default'), '2015-08-31-PREVIEW').principalId]"
https://github.com/Azure/azure-quickstart-templates/blob/master/101-functions-managed-identity/azuredeploy.json#L295

How do I register my application locally created with one I created in Azure Active Directory?

I am following directions here for learning the AzureKeyVault config settings
Key Vault Configuration Provider sample application (ASP.NET Core 2.x)
This sample illustrates the use of the Azure Key Vault Configuration
Provider for ASP.NET Core 2.x. For the ASP.NET Core 1.x sample, see
Key Vault Configuration Provider sample application (ASP.NET Core
1.x).
For more information on how the sample works, see the Azure Key Vault
configuration provider topic.
Using the sample
Create a key vault and set up Azure Active Directory (Azure AD) for the application following the guidance in Get started with Azure Key
Vault.
Add secrets to the key vault using the AzureRM Key Vault PowerShell Module available from the
PowerShell
Gallery,
the Azure Key Vault REST API, or the Azure
Portal. Secrets are created as either
Manual or Certificate secrets. Certificate secrets are certificates for use by apps and services but are not supported by the
configuration provider. You should use the Manual option to create
name-value pair secrets for use with the configuration provider.
Simple secrets are created as name-value pairs. Azure Key Vault secret names are limited to alphanumeric characters and dashes.
Hierarchical values (configuration sections) use -- (two dashes) as a separator in the sample. Colons, which are normally used
to delimit a section from a subkey in ASP.NET Core
configuration, aren't allowed
in secret names. Therefore, two dashes are used and swapped for a
colon when the secrets are loaded into the app's configuration.
Create two Manual secrets with the following name-value pairs. The first secret is a simple name and value, and the second
secret creates a secret value with a section and subkey in the secret
name:
SecretName: secret_value_1
Section--SecretName: secret_value_2
Register the sample app with Azure Active Directory.
Authorize the app to
access the key vault. When you use the
Set-AzureRmKeyVaultAccessPolicy PowerShell cmdlet to authorize the
app to access the key vault, provide List and Get access to
secrets with -PermissionsToSecrets list,get.
Update the app's appsettings.json file with the values of Vault, ClientId, and ClientSecret.
Run the sample app, which obtains its configuration values from IConfigurationRoot with the same name as the secret name. *
Non-hierarchical values: The value for SecretName is obtained with
config["SecretName"]. * Hierarchical values (sections): Use :
(colon) notation or the GetSection extension method. Use either of
these approaches to obtain the configuration value:
config["Section:SecretName"]
config.GetSection("Section")["SecretName"]
Okay so I have copied the name of my application into Azure Active Directory as an 'Enterprise Application'. And I have added 'Access policies' for 'get' and 'list' in Azure for my ADD object I just created. Yet I get this error in the program when attempting to start the application:
Exception: {"error":"unauthorized_client","error_description":"AADSTS70001:
Application with identifier '(guid)' was not found in the directory ...(continues)
Update 8-4-18
Okay I found out that Azure uses the 'ClientId' and 'ClientSecret' in the local appsettings.json to connect to what Azure registers in this tutorial: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#log-in-as-the-application
I get the clientId in appsettings.json from the applicationId on ADD I create with ADD>App Registrations>New
I click settings in ADD on the app I just created and create a key with an expiration to store as ClientSecret in appsettings.json.
I change my 'Vault' in appsettings to my named vault.
I run the powershell above to give access or else do it in ADD.
So now I am getting a simpler error:
'Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: 'Access denied''
I have tried running as Administrator in Visual Studio. I went under Subscriptions in Azure>Access Control>(IAM)>set my new apps to Reader.
So the reason your powershell is failing is because you are trying to assign a User Principal - a user - when actually you want a Service Principal.
I can’t see your C# to support more there than saying when you use the SDK to log in as the Service Principal you use the application id of the Application/Service Principal (its the same id).
The service principal acts like a user in the local directory but you log in as the application.
Edit:
I looked at the example you posted and ran it myself and had very similar problems. However I have got it working. Here's the steps:
Creating the Application
Create the Registered Application. I do this through the Azure Portal so
a Service Principal is created automatically. Make a note of the ApplicationId.
Generate a key credential on the created application and make a note of it.
In the Application click on the link to the Managed app in local directory. This is the Service Principal, make a note of the ObjectId
Creating the Key Vault
Create KeyVault - I used PowerShell to do this. New-AzureRmKeyVault
Apply the Service Principal to the Key Vault.
Set-AzureRmKeyVaultAccessPolicy -VaultName <vault> -ResourceGroupName <ResourceGroupName> -ObjectId <Object Id of the Created Service Principal> -PermissionsToSecrets Get,List
Running the Sample App
In your application settings follow this format:
{
"Vault": <the name of your vault>,
"ClientId": <ApplicationId of the Registered Application>,
"ClientSecret": <Credential generated from the Registered Application>
}
This worked for me and allowed me to run the sample and retrieve the secrets from the vault.
The ultimate problem for me became that running 'Set-AzureRmKeyVaultAccessPolicy' was not needed and for whatever reason it was easier to just ignore it and follow this subsection: https://azure.microsoft.com/documentation/articles/key-vault-get-started/#authorize
I kept trying to set up Object Id and Keys and really I had just overlooked a section mentioning a 'ServerPrincipalName'
They set one commandlet for keys
Set-AzureRmKeyVaultAccessPolicy -VaultName '<vaultName>' -ServicePrincipalName <ApplicationIdGuid> -PermissionsToKeys decrypt,sign
They set one commandlet for secrets
Set-AzureRmKeyVaultAccessPolicy -VaultName '<vaultName>' -ServicePrincipalName <ApplicationIdGuid> -PermissionsToSecrets Get, List
But I decided to follow the immediate proceeding section on doing it all in the Portal. The key take away for me was that the instructions were not wrong. Just vague when it says: "Register a sample app" then "Authorize the App". Really they should be saying
Register a sample app (https://learn.microsoft.com/en-us/azure/key-vault/key-vault-get-started#register)
Authorize the app with Key Vault (https://azure.microsoft.com/documentation/articles/key-vault-get-started/#authorize)
Ultimately all the information is there it was just confusing if you happen to already have a vault and an application and don't understand the prerequisite is that really you need to have a 1. A Vault, 2. An ADD Web Application, 3. Associate permissions for 2 in 1.

Resources