Azure Credentials error in Azure Automation - azure

I'm trying to create an Azure Automation job to create a standard set of tags/values in a subscription.
Working with Tags requires AzureResourceManager, which is not available in Automation out of the box (Go vote for this feedback item!), so I followed these steps to upload the ARM module.
When I test my runbook I get the following output:
-------------------------
PSComputerName : localhost
PSSourceJobInstanceId : a8b85213-ee0f-40ea-842f-d33f2e87c910
Id : xxxxx-56ad-42c2-97f4-e364456fc4a6
Name : xxxxx
Environment : AzureCloud
Account : my-service-principal-app-id
Properties : {Default, Tenants, SupportedModes}
-------------------------
New-AzureTag : Your Azure credentials have not been set up or have expired, please run Add-AzureAccount to set up your
Azure credentials.
At Add-SubscriptionTags:41 char:41
+
+ CategoryInfo : CloseError: (:) [New-AzureTag], ArgumentException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Tags.Tag.NewAzureTagCommand
Here's my runbook:
workflow Add-SubscriptionTags
{
param
(
# Subscription
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$SubscriptionName
)
# Get the PowerShell credential and prints its properties
$cred = Get-AutomationPSCredential -Name 'AzureMaint'
# Connect to Azure
Add-AzureAccount -Credential $cred -ServicePrincipal -Tenant 'xxx-49ab-8a9c-4abce32afc1e' | Write-Verbose
# Set subscription
$subscription = Select-AzureSubscription -SubscriptionName $SubscriptionName -PassThru
write-output '-------------------------'
write-output $subscription
write-output '-------------------------'
# Add tags (Requires AzureResourceManager module)
New-AzureTag -Name 'Managed' -Value $true
New-AzureTag -Name 'Managed' -Value $false
}
The AzureMaint PSCredential contains a service principal ID and key, and the service principal has been granted the Contributor role on the specified subscription. I can do Add-AzureAccount in the ISE with those credentials and add tags just fine. Since it successfully prints the subscription info I assume that means Add-AzureAccount was successful, so why do I get the error?
Update:
I created a new Automation Account without the ARM module and I'm still having the same issue, although the error message is slightly different:
Your Azure credentials have not been set up or have expired, please run Add-AzureAccount
to set up your Azure credentials. (Your Azure credentials have not been set up or
have expired, please run Add-AzureAccount to set up your Azure credentials. (Unable
to retrieve service key for ServicePrincipal account xxx-4a00-becf-952fda93edc5.
Please run the Add-AzureAccount cmdlet to supply the credentials for this service principal.))
So now I'm wondering if it doesn't like me using a Service Principal?

Just to update here, we've discovered that service principal authentication does not work in Azure Automation currently. Given you are trying to use a service principal, that is the reason for the issues you are hitting.
For now, a user principal should be used to work around this issue.
Please see the following for more info:
Authenticating to Azure Resource Manager with a Service Principal in Azure Automation
https://github.com/Azure/azure-powershell/issues/655

Using ARM cmdlets in Azure Automation is not officially supported yet. That said, various people have been successful doing so. Are your ARM and Azure PowerShell modules the same version? Weird things can happen if they are loaded side by side but are not the same version.

Related

Assign Key Vault Secrets to an Azure Function using Azure PowerShell

I am trying to automate the creation of certain azure resources via an Azure PowerShell script that is triggered from an Azure DevOps release pipeline. I want to create a function app, and automatically integrate reading right access to secrets in an already existing Key Vault. This Key Vault is in the same Azure subscription.
While I can create most resources following the documentation, there seems to be a lack of documentation regarding the creation of certain resources using Azure PowerShell (or I can't find it).
If I follow the sample from this link, I can accomplish it without a problem by using the UI in the Azure Portal, but I can't find any documentation on Microsoft Docs to do it using PowerShell.
Write-Host "Creating Function App..."
$fnApp = New-AzFunctionApp -Name $functionAppName `
-ResourceGroupName $emailFunctionRg `
-Location "$(AzureRegion)" `
-StorageAccount $storageName `
-Runtime dotnet `
-FunctionsVersion '3' `
-IdentityType SystemAssigned
Write-Host "Function App created!"
Write-Host "Assigning Key Vault access..."
$appId = Get-AzADServicePrincipal -DisplayName $functionAppName
Set-AzKeyVaultAccessPolicy -VaultName EmailSettings -ServicePrincipalName $appId -PermissionsToSecrets Get,List
Write-Host "Key Vault access granted!"
Running Set-AzKeyVaultAccessPolicy fails with "Insufficient privileges to complete the operation.". But I am not sure if this is the right path to follow, it was just a guess, based on the available functions in the documentation.
Any ideas?
Two potential issues to check out here:
your app creation assigns the result to $fnApp. perhaps $fnApp or as commented above, $fnApp.ApplicationId is what you should be using for the -ServicePrincipalName parameter on the access policy grant.
you don't have privileges to assign RBAC roles. Go to the Key Vault, choose Access Control, then click the Role Assignments tab and verify that your user appears in the list as an Administrator, User Access Administrator, or Owner.
Edit: With respect to the RBAC privilege, since this is running in Azure Powershell from Azure DevOps, you need to check the role assignment for the Service Connection's service principal - under Azure Active Directory in the Azure Portal, look up the principal used to create the service connection, and make sure THAT gets the correct Role on the key vault.
After a little of trial and error I just came to the conclusion I was not using the right parameter for the Set-AzKeyVaultAccessPolicy cmdlet.
The following script will work (if the service principle running it has the appropriate role, like WaitingForGuacamole mentioned in his/her answer):
Write-Host "Creating Function App..."
$fnApp = New-AzFunctionApp -Name <FnAppName> `
-ResourceGroupName <ResourceGroupName> `
-Location <AzureRegion> `
-StorageAccount <StorageAccount> `
-Runtime dotnet `
-FunctionsVersion '3' `
-IdentityType SystemAssigned
Write-Host "Function App created!"
Write-Host "Assigning Key Vault access..."
Set-AzKeyVaultAccessPolicy -VaultName <NameOfTheKeyVault> -ObjectId (Get-AzADServicePrincipal -DisplayName <FnAppName>).Id -PermissionsToSecrets <Get, List, etc...>
Write-Host "Key Vault access granted!"

Connect-AzAccount Powershell on-prem

I am new to Azure and I've successfully installed PowerShell on my macOS. Now I want to run get-azvm command and stop/delete a vm from on-prem (not cloud shell).
First thing I did from Terminal:
1. PWSH to launch PowerShell
2. Connect-AzAccount, browser opens to authenticate and I get an error:
Connect-AzAccount xx: Device authentication is required.
Trace ID: xx
Correlation ID: xx
+ CategoryInfo : CloseError: (:) [Connect-AzAccount], AadAuthenticationFailedException
I continue with az login command. Result:
You have logged in. Now let us find all the subscriptions to which you have access...
{
}
I run: get-azvm and get another error:
get-azvm : No subscription found in the context. Please ensure that the credentials you provided are authorized to access an Azure subscription, then run Connect-AzAccount to login.
At line:1 char:1
Please, what am I doing wrong? Do I need to register my on-prem machine somewhere?
Thanks for the help.
As mentioned in above comment - you might have conditional access policies enabled on your Azure AD so you might want to check it out and confirm.
Secondly, if that's not the case - try running commands below before you access your azure resources
Add-AzAccount
Get-AzSubscription -SubscriptionId "your_azure_subscription_id" | Select-AzSubscription
$vm = Get-AzVM -ResourceGroupName "your_vm_resource_group_name" -Name "your_vm_name"
Hope it helps?
According to the error from Connect-AzAccount, Looks your account is MFA-enabled, please use the authentication methods to authenticate. Or you can create a service principal, assign a role for it in the subscription, then you can login with the service principal and use it to Get-AzVM, details here.
I continue with az login command. Result: You have logged in. Now let us find all the subscriptions to which you have access..
You should note, Connect-AzAccount is used to login the Azure Powershell, az login is used to login the Azure CLI, they are different. From the output, looks you logged in successfully in Azure CLI, you could use az account set --subscription <subscription-id> to set the subscription which you want to get the VMs from, then use az vm list to list VMs.

How to login AzureRm using ConnectionType as Azure in AzureAutomation

My Azure Automation is created using Create Azure Run As Account
I can able to login to Azure using the below commands
$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
I'm now investigating about the connectiontype as Azure
I've created a new connection as Azure Type by uploading my own certificate in Certificate
My Own certificate in Automation
My Azure Connection
Now I'm thinking how can use this abc connection to login into my Azure Rm Account
$connectionName = "abc"
$conn = Get-AutomationConnection -Name $connectionName
echo $conn
"Logging in to Azure..."
Connect-AzureRmAccount -SubscriptionId $conn.SubscriptionID
I know the above it's not the correct approach, but hoping someone will help me to get the correct one.
The above query is giving the error like below
Name Value
---- -----
AutomationCertificateName MyCertificate
SubscriptionID xxxx-xxx-xxx-xxx-xxxxxxx
Logging in to Azure...
Connect-AzureRmAccount : Unable to find an entry point named 'GetPerAdapterInfo' in DLL 'iphlpapi.dll'.
At line:5 char:5
+ Connect-AzureRmAccount -SubscriptionId $conn.SubscriptionID
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
Also, I couldn't get any reference document for the exact usage of connectionType as Azure. I couldn't get any example except this one related to connectiontype as Azure
It would be a great help if someone guide to get some reference document on the connectionType as Azure
An Azure Run As Account is not just a Connection and Certificate asset.
There's also an Azure AD application, Azure AD service principal and contributor permissions assigned for that service principal during the creation of an Azure Run As Account.
Check out https://learn.microsoft.com/en-us/azure/automation/manage-runas-account for more information. The docs also contain a PowerShell script for creating your own Azure Run As Account, which includes support for the following configurations:
Create a Run As account by using a self-signed certificate.
Create a Run As account and a Classic Run As account by using a
self-signed certificate.
Create a Run As account and a Classic Run As account by using a
certificate issued by your enterprise certification authority (CA).
Create a Run As account and a Classic Run As account by using a
self-signed certificate in the Azure Government cloud.
I already opened a Github issue already which got resolved today. For someone who is still trying to get the answer, pls look at the detailed documentation.
Azure - This connection can be used to manage classic resources.
AzureClassicCertificate - This connection is used by the
AzureClassicRunAs account. AzureServicePrincipal - This connection is
used by the AzureRunAs account.

Azure Powershell - automating Login-AzureRmAccount AD Login - for Azure function

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

Azure Automation Runbooks using Get-Credential without parameters

There are several Runbooks examples in the Azure Runbook Gallery, such as:
Deploy a Windows Azure Web Site Pointing to a SQL Database and Storage Account
that use the following syntax with Get-Credential:
$credential = Get-Credential
which implies that the command should prompt for the credentials -- but this fails in a Runbook with the following message:
Get-Credential : Cannot process command because of one or more missing mandatory parameters: Credential.
The credentials that are desired here are for this purpose:
# Get credentials from user to setup administrator access to new SQL Azure Server
which then should get used in downstream cmdlet calls in the Runbook such as
$databaseServer = New-AzureSqlDatabaseServer -AdministratorLogin $credential.UserName `
-AdministratorLoginPassword $credential.GetNetworkCredential().Password -Location $Location
But because Get-Credential fails the downstream calls fail.
What I am doing wrong?
Why does a Runbook in the Gallery have statements that seem to be incompatible (prompt for Credentials) with allowable Runbook behaviors?
So with Azure Automation, you would create a credential asset (for example, named AzureAdmin) and then you would reference that in the runbook, to get those credentials:
$cred = Get-AutomationPSCredential -Name AzureAdmin
As for the reference script, I suppose, it was just added to the runbook gallery without any verification, so in reality its not Azure Automation friendly

Resources