I have a Azure Key Vault in which I want to add access policies for my MSI enabled App Service using powershell.
Using portal it's straightforward. As you can see below, I am searching by my app service name and I see app service and app registrations both.
in above example I selected app service directly without registrating it in Azure AD and it's working awesome.
I just need guidance to do the same using Azure Powershell(which will run VSTS SPN).
Please help.
Thanks
Set-AzureRmKeyVaultAccessPolicy -VaultName $valutName -UserPrincipalName 'PattiFuller#contoso.com' -PermissionsToKeys create,import,delete,list -PermissionsToSecrets set,delete -PassThru
Make sure you have logged in from the PowerShell and selected the resource group where the resource exists before you run the command.
Refer documentation for more.
You need to use the the Set-AzureRmKeyVaultAccessPolicy command but with ObjectId parameter.
Set-AzureRmKeyVaultAccessPolicy -VaultName my-keyvault -ResourceGroupName my-resource-group -ObjectId 15faf32d-146a-4985-a315-640527b6c489 -PermissionsToSecrets get
Bear in mind that MSI apps are registered as Enterprise Apps.
EDIT: Curious, what are you trying to achieve?
Related
I have a powershell script that attempts to retrieve a secret stored in Azure key vault using this command.
$password = (Get-AzureKeyVaultSecret -vaultName $vaultName -name $secretName).SecretValueText
It is working perfectly fine when I execute my powershell script locally. But, when I try to do the same on Azure Devops, it fails giving below error.
[error]Operation returned an invalid status code 'Forbidden'
I feel it isn't an access policy issue, as I am able to successfully perform read/write on my vault using powershell script running locally.
I'm quite sure it is a access policy issue.
Go to your DevOps Project Settings - Pipelines - Service Connections and click on "Update Service Connection" (Use the full version of the dialog). There you can find the Subscription Id and Service Principal ID.
You then have to give explicit permissions to this SPN:
Login-AzureRmAccount -subscription <YourSubscriptionID>
$spn= Get-AzureRmADServicePrincipal -spn <YourSPN>
Set-AzureRmKeyVaultAccessPolicy -VaultName <YourVaultName> -ObjectId $spn.Id -PermissionsToSecrets get,list;
I am using below Azure Powershell command in VSTS.
(Get-AzureKeyVaultSecret -vaultName "debugkv" -name "CoreConfig-StorageAccount-AccessKey")
I am getting ##[error]Access denied error while running it in VSTS but loclaly it works fine.
I have added the SPN in KV's access policies also with GET and SET permissions for secrets.
Need help in troubleshooting it.
To link VSTS to you need to give the Service Principal, which forms the Service Endpoint in VSTS, access to the Key Vault; you already know this.
What can be confusing is that you can assign the application and the service principal to have access to the key vault depending on your use case. Therefore, you must ensure that you assign the right object to the access policy.
The best way to ensure you assign the right object is to do it through Azure Powershell.
Running a signed in Azure Powershell session:
$spObjectId = Get-AzureRmAdServicePrincipal -SearchString <ServicePrincipalName> | Foreach-Object {$_.Id}
Set-AzureRmKeyVaultAccessPolicy -VaultName <VaultName> -ObjectId $spObjectId -PermissionsToSecrets Get,Set
If you wanted to see further details (objectids, permissions etc) of the access policies you can get these through Powershell also:
Get-AzureRmKeyVault -VaultName <VaultName> | Foreach-Object {$_.AccessPolicies}
TL;DR
In summary the steps are:
Use the correct code (the last code in this post)
Manually add your app id in SSMS as either a server administrator or a database administrator
and then you can process an Azure Analysis Services cube from an Azure Automation Account without needing to create another seperate service account
Actual Question:
I am trying to process an Azure Analysis Services cube using the Azure Automation RunAs Service Principal. This is run within an Azure automation account
This code
#Get the existing AzureRunAsConnection connection
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
# Login with service principal account
Login-AzureRMAccount
-ServicePrincipal
-Tenant $Conn.TenantID
-ApplicationId $Conn.ApplicationID
-CertificateThumbprint $Conn.CertificateThumbprint
# Process cube
Invoke-ProcessASDatabase -databasename "DB" -server "Server" -RefreshType "Full"
Results in
Authentication failed: User ID and Password are required when user interface is not
available.
My understanding is that when you create an Azure Automation Account, it also creates a 'RunAs' account, which in turn creates a service principal account. (Although the doco seems a bit light on)
I have tried finding this principal account in Azure AD and adding it to SSAS Admins in the Azure portal, but I can't find the actual account. Do service principals actually appear as accounts?
The code below works fine, but it uses a pre saved credential but I don't want to have to manage yet another account.
# Purpose: Run a full process the SSAS cube
$AzureCred = Get-AutomationPSCredential -Name "MyCredential"
Add-AzureRmAccount -Credential $AzureCred | Out-Null
Invoke-ProcessASDatabase -databasename "MyDB" -server "MyServer" -RefreshType "Full" -Credential $AzureCred
Update 1
I have also tried manually adding these in the SSMS membership area (after looking up the guids in the RunAs Account area in the automation account):
app:applicationid#tenantid
obj:serviceprincipalobjectid#tenantid
and I get the same error message.
I also ran the script with a non-admin user and got
The "zzz" database does not exist on the server.
So it would appear my issue is authentication, not authorisation. In other words it's not that I don't access, it's that I can't log in. I'm thinking based on that error, that -credential is not optional when calling Invoke-ProcessAsDatabase against Azure Analysis services
Also, I note that for the -credential option, the help says
If no credentials are specified, the default Windows account of the user running the script is assume
Given that Azure Analysis Services appears to only be able to use SQL credentials when connecting to a data source (no kind of AD credentials), I can only surmise that Azure Analysis Services is unable to use any kind of Azure Ad authentication for internal processes.
The annoying thing is that this isn't stated anywhere.
Update 2
So I did not read the link carefully enough. The code that works is mostly on the site posted by both answerers here. To pre authenicate to Azure Analysis Server you need to use Add-AzureAnalysisServicesAccount (The linked blog uses Login-AzureAsAccount but I couldn't get it working and couldn't find doco). You need to install powershell module "Azure.AnalysisServices" to use this.
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureAnalysisServicesAccount -RolloutEnvironment "australiasoutheast.asazure.windows.net" -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
Invoke-ProcessASDatabase -databasename "MYDB" -server "MyServerEndpoint" -RefreshType "Full"
You can use the RunAs account with this, and afterwards you don't need to use -credential
So.. this actually works and logs in without needing a seperate credential, but now it doesn't have access to the database. Instead of a login error, I get
The "ZZZZ" database does not exist on the server.
I would appear that the RunAs account has access to the server but not the database and I can't work out to find it to give it access.
Update 3:
This is a more direct guide on how to give the app access to the model so it can be built:
Azure analysis service connection using Service principal not working
Note you can't add in the Azure portal as it won't find it. Add it "manually" in SSMS and it will work, and it will also appear in the Azure Portal as an admin
It all works now.
Update 4:
This has become a handy spot to store my discoveries around authenticating through MSI
Although this question is solved, no I want to connect to SQL Azure from something else using MSI security. No connection string supports this - none of the authentication methods in any connection string support MSI authentication. I did find this interesting link which implies you can create a connection string that supports authentication as MSI:
https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi
The bit of code of interest is:
az webapp config connection-string set
--resource-group myResourceGroup
--name <app name>
--settings MyDbConnection='Server=tcp:<server_name>.database.windows.net,1433;Database=<db_name>;'
--connection-string-type SQLAzure
I can't find any reference to the parameter --connection-string-type. But it looks like you simply exclude the authentication piece altogether.
In your example 1, it seems not your login Azure Login-AzureRMAccount get the error log. Based on my knowledge, Invoke-ProcessASDatabase is not a Azure Power Shell cmdlet. In fact, you no need to login your Azure subscription. Only Invoke-ProcessASDatabase -databasename "MyDB" -server "MyServer" -RefreshType "Full" -Credential $AzureCred should works for you.
Yes if I supply a credential it works, but I want to use the RunAs
credential. If I can't, then what is the point of it.
RunAs credential only works for login your Azure subscription, it does not stores credential for your SQL. In your scenario, you could store your SQL credential in runbook PSCredential, like your example2. In fact, in your example, you could remove Add-AzureRmAccount -Credential $AzureCred | Out-Null.
Update:
You should use following script in runbook.
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Login-AzureASAccount -RolloutEnvironment "southcentralus.asazure.windows.net" -ServicePrincipal -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint -TenantId $Conn.TenantID
Invoke-ProcessTable -Server "asazure://southcentralus.asazure.windows.net/myserver" -TableName "MyTable" -Database "MyDb" -RefreshType "Full"
More information about this please check this blog.
Per the official documentation:
Once the service principal is created, its application ID can be assigned permissions in the Azure Analysis Services server or model roles using the following syntax. The example below adds a service principal to the server administrators group in SSMS.
I didn't see the use of Run-as option, i'd recommend checking this blog
It also contains information about storing credentials in azure automation, this will help you in not hard writing credentials in the code.
I have this Azure Powershell script, which successfully backs up a SQL Azure DB to Azure Blob.
In its current form, it requires me to log in via AD.
I now need to implement this script to execute via a Azure Function at specific intervals.
The first snippet of the script:
$subscriptionId = "YOUR AZURE SUBSCRIPTION ID"
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId $subscriptionId
I thus need to not use Login-AzureRmAccount, but replace it with a method that does not require human input.
I have found this link:
https://cmatskas.com/automate-login-for-azure-powershell-scripts/
In short, the author:
Creates an Azure AD Application (with its own password)
Creates a Service Principal
Assigns Permissions to the Service Principal
This is a once-off manual creation - which is perfect.
The author then logs in to this newly created application
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId e801a3ad-3690-4aa0-a142-1d77cb360b07 -ServicePrincipal
My questions:
Is this what I should do to be able to automate my application and prevent human login?
This Azure AD app created in step 1 - can I use this app as a starting point in my of my Azure functions?
Yes, you can use that route, or use certificate auth, or use an Azure AD user, it can login with user\password, but is considered less secure than service principal.
Yes, you can use one service principal for any number of Azure Functions you would like to.
To use Azure PowerShell in Azure Functions, you may refer to the following response in another SO thread. The example is an HTTP-Trigger, but you can modify it to use a Timer-Trigger for your use-case. Here's the link:
Azure Function role like permissions to Stop Azure Virtual Machines
Run PowerShell as Administrator, you need to install AzureRM in PowerShell,
Login to Azure
Login-AzureRmAccount
Enter your Azure credentials
To get your subscription(s) details
enter
Get-AzureRmSubscription
Use the subscription id to select the subscription.
Select-AzureRmSubscription -SubscriptionId xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Save the AzureProfile using the below command
Save-AzureRmProfile -Path "C:\AzureScripts\profile.json"
The json file can be used to login to Azure
Select-AzureRmProfile -Path "C:\AzureScripts\profile.json"
Put this line on top of you .ps1 file, you does not require human input.
Ref : http://www.smartcoding.in/blog/auto-login-azure-power-shell
I can't find any documentation on how to choose which AAD to create the service principal in. Basically, I can't find out if there is even a way to add the SP to the local AAD.
So we have a default Global AD which covers all of our enrollment and below that all subscriptions. I'm using Powershell derived from the many many examples on the net to create a SP in the default AD. Then I permission that SP against the subscription it is going to be working in.
At this point I've run into the following problem.
I'm rolling out a Key Vault, this works.
New-AzureRmKeyVault -VaultName $VaultName -EnabledForDeployment -EnabledForTemplateDeployment -ResourceGroupName $ResourceGroupName -Location $Location -Verbose
I need to add the first secret into it as part of the deployment. This bit fails because the SP doesn't have access to the KV.
# Set-AzureRmKeyVaultAccessPolicy -VaultName $VaultName -ResourceGroupName $ResourceGroupName -PermissionsToSecrets get,set -ServicePrincipalName $ServicePrincipalName
This is the result of that command.
Set-AzureRmKeyVaultAccessPolicy : Cannot find the Active Directory object
'Service-Principal-Name' in tenant '6166a717-xxxx-xxxxx-b0e8-6b7288c1f7ec'.
Please make sure that the user or application service principal you are
authorizing is registered in the current subscription's Azure Active
directory.
Reading into this, its not possible to set the Global AD Service Principal to have get/set on the local Keyvault. it would have to be a local Service Principal. However, we dont have one of them and nowhere can I work out how to create one of them.
Anyone else feeling this pain and know how to resolve it?
In the settings section of the old portal (manage.windowsazure.com), you will find a list of all subscriptions. The fourth column (Directory) shows the default directory that is associated with each subscription. No matter what, you will have to create the Service Principal in the Directory that is associated with that particular subscription. Please check this link to understand the relationship between Subscriptions and AAD.