Everytime you want to schedule some repeatable script which needs to use some specific permission you use service account.
In on-premises environments it’s quite easy. You provide name of the account, add proper permission and set password to never expires.
Everything can be done via Acitve Directory Users and Computers or Powershell.
To do the same for cloud base environments you should register new application in Azure Active Directory with portal or Powershell. But common, who will use portal when you have great AzureAD PS module 🙂
Remember, to create application account you must have sufficient permission – Global Administrator on Azure subscription will be the best 😉 Ok, let’s start.
As a first step you must create AD application. Provide name, home page and password and Uri. If you don’t have any app, you can create fake one providing incorrect data for homepage and identifieUris.
Remember to save result to variable, application id later will be used as a service principal name.
$Application = New-AzureRmADApplication -DisplayName "TestApp" -HomePage "https://testdomain.com/TestApp" -IdentifierUris "https://testdomain.com/TestApp" -Password "SuperSecretPassword"
Create service prinicpal by providing application id
New-AzureRmADServicePrincipal -ApplicationId $Application.ApplicationId
You must wait a while that changes will be replicated to AD or sleep script for 30 seconds.
Assign sufficient role to account, use Microsoft docs to find proper one for you.
New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $Application.ApplicationId
Once service principal is created you can proceed with logging to azure. There are two additional switches which should be used :
TenenatID – Tenant Id of subscribtion
$tenant = (Get-AzureRmSubscription).TenantId
ServicePrincipal – it determines that service prinicpal account will be used to login.
Below code shows how it should be done. Remember that password should be encrypted (we will talk about this in another article).
$password = "SuperSecretPassword" | ConvertTo-SecureString -asPlainText -Force $username = $Application.ApplicationId $creds = New-Object System.Management.Automation.PSCredential($username,$password) $login = Login-AzureRmAccount -Credential $creds -ServicePrincipal -TenantId $tenant