In some scenarios it is not possible to generate a ServicePrincipal for automation in Azure, although this is the recommended way. In this case, credentials can also be stored and used in Azure Automation. In the following I used the scripts for Start-AzureV2VMs and Stop-AzureV2VMs and modified them a bit. They
- now use credentials
- a TenantID and SubscriptionID are additionally required
- the script finds and uses a specific VM or all VMs of a resource group or all VMs of a subscription.
The scripts can be downloaded in my GitHub-Account: https://github.com/tzuehlke/scripts/tree/master/AzureAutomation
The decisive lines for authentication with credentials are defined in the script in line 20 – 28:
...
param (
[Parameter(Mandatory=$true)]
[String] $TenantId,
[Parameter(Mandatory=$true)]
[String] $SubscriptionId,
[Parameter(Mandatory=$true)]
[String] $AzureCredentialName,
[Parameter(Mandatory=$false)]
[String] $ResourceGroupName,
[Parameter(Mandatory=$false)]
[String] $VMName
)
try {
$Cred = Get-AutomationPSCredential -Name $AzureCredentialName
$userName = $Cred.UserName
$securePassword = $Cred.Password
Write-Output "using user $userName"
$PsCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $securePassword
Write-Output $myPsCred
Write-Output "try to connect..."
Connect-AzAccount -TenantId $TenantId -Subscription $SubscriptionId -Credential $PsCred
Write-Output "connection succeeded"
#Write-Output "set subscrioption..."
#Set-AzContext -SubscriptionId $SubscriptionId -TenantId $TenantId
}
catch {
Write-Error $_.Exception
throw $_.Exception
}
...
The user name and password are read out, converted into a PSCredential object and then applied to the Connect-AzAccount.
So it is really easy to change the authentication or add some parameters for personal needs, even in existing scripts.
Schreibe einen Kommentar