I have created a script in powershell for checking the expiry date of services principal in azure.The script itself works fine if i will execute it directly in cloud shell.But this is not what i want.I want that the script can be executed by a runbook in azure,so i created the runbook and also "run as account" user.The problem is that "run as account" does not have rights to run the cmdlet "get-azadapplication" & "get-azadserviceprincipal".After some research i find out that this user needs global reader rights to AAD.Is there another way how to monitor the services principal without global reader?Does anybody implemented a similar solution?
E.g this a simply code to show the error which i get
#Connect to Azure
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
Connect-AzAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
#get all subscriptions
get-azsubscription
# read the credential for user sp-acr-c4r-pull
get-azadserviceprincipal -displayname sp-acr-c4r-pull | get-azadspcredential
Then i get this error when i run the runbook
Account SubscriptionName TenantId
------- ---------------- --------
* Cloud_Test… *
Cloud_Test
Get-AzADServicePrincipal: C:\Temp\3s0vpqu0.tms
Line |
30 | get-azadserviceprincipal -displayname sp-acr-c4r-pull | get-azadspcre …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Insufficient privileges to complete the operation.
As you can see i can run the get-azadsubscription but not get-azadserviceprincipal
CodePudding user response:
How do you expect your runbook to read data from your directory if you are unwilling to give it the permissions it needs?
Your only option is to assign the Service Principal some kind of permissions. Global reader doesn't seem so bad to me, but if that is unacceptable you could look into making a custom role: https://docs.microsoft.com/en-us/azure/active-directory/roles/custom-create
CodePudding user response:
You can make an entry (e.g. secret) in Key Vault with expiry date equal to expiry date of secret of service principal. Then just apply event grid from that Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/general/event-grid-overview) and send event for e.g. Microsoft.KeyVault.SecretNearExpiry or Microsoft.KeyVault.SecretExpired (https://docs.microsoft.com/en-us/azure/event-grid/event-schema-key-vault?tabs=event-grid-event-schema) and process the event with the logic you need.