How can I established credentials in PowerShell script running in an Azure Automation Account

Viewed 222

I'm trying to get a simple Powershell script working in Azure Automation Accounts; I've tested the script in VS Code and it works fine; the issue is in the Credentials; following this page: https://docs.microsoft.com/en-us/azure/automation/shared-resources/credentials?tabs=azure-powershell, I'm using the following code

# Connect to Azure
$myCredential = Get-AutomationPSCredential -Name 'XXX'
$myUserName = $myCredential.UserName
$mySecurePassword = $myCredential.Password
$myPSCredential = New-Object System.Management.Automation.PSCredential ($myUserName, $mySecurePassword)
Connect-AzureAD -Credential $myPSCredential

The only different to my "local" script is the first of the above lines which uses a local file

$myCredential = Import-CliXml -Path 'C:\Users\<me>\Desktop\credentials.xml'

But it doesn't work; diagnostics seem to be poor in Automation Accounts, but I'm 99% sure is related to credentials; perhaps it's forcing MFA, but that's not happening locally ... any suggestions appreciated

1 Answers

If you are using the older RunAs account then you can use the following:

$connectionName = "connectionName"

try {
    # Get the connection "AzureRunAsConnection" You can't use the Az module version for reasons.
    $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName

    "Logging in to Azure..."
    $connectAzAccountSplat = @{
        ServicePrincipal      = $true
        TenantId              = $servicePrincipalConnection.TenantId 
        ApplicationId         = $servicePrincipalConnection.ApplicationId 
        CertificateThumbprint = $servicePrincipalConnection.CertificateThumbprint
    }
    Connect-AzAccount @connectAzAccountSplat -ErrorAction Stop | Out-Null
}
catch {
    if (!$servicePrincipalConnection) {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    }
    else {
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

Automation Accounts have recently been updated to use system assigned identities however. You can find the docs of that here:

https://docs.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation

Related