I am trying to create a Runbook which does some maintenance in Active Directory. On creation of an Automation Account an "RunAs" account was created. In the runbook I connect to AD using the below command.
$connectionName = "AzureRunAsConnection"
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to AzureAD..."
Connect-AzureAD `
-TenantId $servicePrincipalConnection.TenantId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-LogLevel Info
This command runs fine, however the subsequent use of AD CMDLETS gives the following error,
$Users = Get-AzureADUser
Get-AzureADUser : Error occurred while executing GetUsers Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation.
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
The same is true for other CMDLETS in the AD module, not just this I have tried adding API permission through the registered application (relating to the Automation Account connection resource) in Active Directory but I am still facing the above privileges issue.
According to some test, you need to add the permissions of Azure AD but not Micorsoft Graph. It seems the Get-AzureADUser command use Azure AD graph in the backend. So we need to do the operations as below:
After that we can use the command Get-AzureADUser successfully(if you test the command in powershell, when you add the Azure AD permission, please close the powershell and reopen it and re-connect)
Related
I am currently busy to convert my Azure AD PowerShell scripts to Microsoft Graph PowerShell. I have already some scripts that I want to run within Azure Automation, but I try to figure out how to connect to Azure Automation.
With Azure AD PowerShell, I have a connected service account in Azure Automation. With Microsoft Graph PowerShell I'm trying to use a RunAs account within the Azure Automation Account with the following connection:
$Connection = Get-AutomationConnection -Name AzureRunAsConnection
# Get certificate from the automation account
$Certificate = Get-AutomationCertificate -Name AzureRunAsCertificate
# Connect to the Graph SDK endpoint using the automation account
Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connection.TenantId -CertificateThumbprint $Connection.CertificateThumbprint
When I run the RunBook to create the connection I get an error:
Connect-MgGraph: C:\Temp\os4k24vd.4cs\xxxxxxxxxxxxxxxxxxx.ps1:5
Line | 5 | Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connec …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0,
| Culture=neutral, PublicKeyToken=xxxxxxx'. The system cannot | find the file specified.
I have the following module installed that is needed for Connect-MgGraph Microsoft.Graph.Authentication >> Runtime: 7.1 When I search on the error, it have something to do that .NET could not find the Json.NET library. But which module I'm missing in Azure Automation, or are there other ways to connect Microsoft Graph PowerShell with Azure Automation?
I hope you are using App only Access approach to connect the Azure Automation. if not refer MSDOC - App only Authentication
To get the Certificate and AppID you can use the below command let
#To get App Id
$AppId = Get-AutomationVariable -Name '<Your AppID>'
# Get TenentId
$TenantId = Get-AutomationVariable -Name '< your tenantId>'
# Get Certificate
$CertificateName = Get-AutomationCertificate -Name '<Your Certificate>'
#Connect the mgGraph
Connect-MgGraph -ClientID $AppId -TenantId $TenantId -CertificateName $CertificateName ## Or -CertificateThumbprint
Still, you are facing issue please give a try Automation Hybrid Runbook Worker for more flexibility.
The problem was not the first connect script, but the runtime version. After changing to PS 5.1 instead of 7.1 it all works. The Runbook now shows 'Welcome to Welcome To Microsoft Graph!'
$Connection = Get-AutomationConnection -Name AzureRunAsConnection
# Connect to the Graph SDK endpoint using the automation account
Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connection.TenantId -CertificateThumbprint $Connection.CertificateThumbprint
I am trying to login to Azure from VS Code so that i can run Terraform scripts.
So i created a SP by following the below commands.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal `enter code here`
After running the Add-AzAccount it displays me the Account Name, Subscription Name, Tenant ID and Environment.
But when i now try to run terraform plan from my VS Code so that i can check what all things will be deployed in my azure environment, it throws me this error below :
Error: Error building account: Error getting authenticated object ID: Error parsing json result from
the Azure CLI: Error waiting for the Azure CLI: exit status 1: AADSTS50076: Due to a configuration
change made by your administrator, or because you moved to a new location, you must use multi-factor
authentication to access '00000002-0000-0000-c000-000000000000'.
Trace ID: 19a89f14-0138-4fbd-8d67-5f30c95e5701
Correlation ID: 7d80e2b1-49cc-4f42-9010-401e4453d13e
Timestamp: 2021-02-05 16:39:03Z
I have also tried logging in by typing Login-AzAccount and logged in using Multi Factor Auth, but still i see the above error.
Any reason why i am still getting the error while trying to run Terraform Plan even though i am logged in to Azure from my VS Code
As discussed in the comment:
You need to use Azure CLI and run az login first. Az-Powershell is not being used by Terraform under the hood.
I have an Azure Automation Run As account. When I run the following code (from step 5 of Azure online tutorial) on the runbook in Azure Portal, I get the error shown below. Question: What I may be missing here, and how can we resolve the issue?
runbook code:
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave –Scope Process
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzAccount -ServicePrincipal -Tenant $Conn.TenantID `
-ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
$AzureContext = Select-AzSubscription -SubscriptionId $Conn.SubscriptionID
Error:
Failed At line:4 char:1
+ Disable-AzContextAutosave –Scope Process
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cannot find the 'Disable-AzContextAutosave' command. If this command is defined as a workflow, ensure it is defined before the workflow that calls it. If it is a command intended to run directly within Windows PowerShell (or is not available on this system), place it in an InlineScript: 'InlineScript { Disable-AzContextAutosave }'
I'm assuming you havn't imported the Az.Accounts module into your automation account. Disable-AzContextAutosave, Connect-AzAccount and Select-AzSubscription are from this module.
Follow this guide to Import Az modules.
Unable to assign role to user using New-AzureRmRoleAssignment command. When I run the above command its thronging an error as follows .
New-AzureRmRoleAssignment : Object reference not set to an instance of an object.
Can any one help to resole the issue.
To assign role to user successfully in the runbook, follow the steps below.
Note : The New-AzureRmRoleAssignment you used belongs to the old AzureRM, it was deprecated and will not be updated anymore. In my sample, I use the new Az command New-AzRoleAssignment, I also recommend you to use it.
1.Navigate to the subscription in the portal(you need to be Owner/User Access Administrator in the subscription) -> add the service principal of your automation RunAs account as an Owner/User Access Administrator(by default it will be added as Contributor when it was created, but Contributor have no permission to run New-AzRoleAssignment).
2.Navigate to the Azure Active Directory in the portal -> App registrations -> find the AD App of your RunAs Account and add the Directory.Read.All application permission in Azure Active Directory Graph(Not Microsoft Graph) like below, don't forget to click the Grant admin consent for xxx button at last(you need to be the admin role in your AAD tenant). The permission may take about 30 min to take effect.
3.Navigate to the automation account in the portal -> Modules -> make sure you have installed the Az.Accounts, Az.Resources modules, if not, go to Browse Gallery, search for the names, and install them.
4.Then in the runbook, use the script below, it works fine on my side. In my sample, I add the user as a Reader in the resource group joyRG, you can change it, it depends on your requirement.
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
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
}
}
$user = Get-AzADUser -UserPrincipalName joyw2#xxxx.onmicrosoft.com
New-AzRoleAssignment -ObjectId $user.id -ResourceGroupName joyRG -RoleDefinitionName Reader
The following code works great via Azure Cloud Shell (completes, App Service deleted as expected).
Remove-AzWebApp -ResourceGroupName "ResourceGroup1" -Name "AppService1" -Force
It also completes without error within my Runbook workflow, but the App Service remains operational. This feels like a permissions problem, but I've tried adding the Owner role at the subscription level without success.
Any ideas/tips for how to make this work for the AzureRunAsConnection account?
This feels like a permissions problem, but I've tried adding the Owner role at the subscription level without success.
It is not a permission problem, when you create the automation account along with the RunAsAccount, it will add the service principal related to the RunAsAccount to the subscription as a Contributor role, which is enough to remove the web app.
If you are using the PowerShell Workflow Runbook, try the sample below, it works for me. (First, make sure you have installed the Az.Accounts, Az.Websites modules in the automation account -> Modules.)
workflow testrun3
{
$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
}
}
Remove-AzWebApp -ResourceGroupName "<group-name>" -Name "joywebapp1234" -Force
}
Check the result in the portal:
To create or update a Run As account, you must have specific privileges and permissions. An Application administrator in Azure Active Directory and an Owner in a subscription can complete all the tasks. Use Remove-AzAutomationConnection to remove an Automation connection.
For more details, you could refer to this article about Run As account permissions.