Azure Automation - Unable to get AzRoleAssignement - azure

In order to automate some processes, I'm using Azure Automation with Owner rights for RunAsAccount.
$connection = Get-AutomationConnection -Name AzureRunAsConnection
while(!($connectionResult) -And ($logonAttempt -le 10))
{
$LogonAttempt++
# Logging in to Azure...
$connectionResult = Connect-AzAccount `
-ServicePrincipal `
-Tenant $connection.TenantID `
-ApplicationId $connection.ApplicationID `
-CertificateThumbprint $connection.CertificateThumbprint
Start-Sleep -Seconds 30
Write-Output $connectionResult
}
Get-AzRoleAssignment -ResourceGroupName $USERRGNAME -SignInName $USEREMAIL -verbos
An error is being thrown each time I execute the script:
Get-AzRoleAssignment: Cannot find principal using the specified options
Any idea to solve this issue?

Probably you need to give RunAsAccount with the Application permission Directory.Read.All of the Azure AD Graph(not Microsoft Graph, not Delegated permission). By default, RunAsAccount doesn't have the Azure AD permission.
You could read Joy's answer for more details.

This error is showing when there is no Role Assignment for name that is provided in the SignInName option.

Related

Get-AzSubscription won't show my subscription

I have a subscription I want to pause/resume with a PowerShell script (Azure Analysis Services). I use this exact same script to pause my Embedded Capacity and that works fine, but when I run my script for my new subscription it wont work. This is the script I use:
$userPassword = "myappsecret"
$userPassword2 = ConvertTo-SecureString -String $userPassword -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "appid", $userPassword2
Connect-AzAccount -ServicePrincipal -TenantId "tenantid" -Credential $Credential
Select-AzSubscription -SubscriptionId "subscriptionname here"
Get-AzPowerBIEmbeddedCapacity -ResourceGroupName "groupnamehere" -Name "namehere"
Suspend-AzPowerBIEmbeddedCapacity -Name "namehere" -ResourceGroupName "groupnamehere" -PassThru
To check why this won't work I tried to simply use Get-AzSubscription to see if something was wrong and it wont show any subscription.
If I try the same for my Embedded Capacity it works just fine.
What could be wrong?
To get the list of all Azure Ad subscriptions by using Get-AzSubscription, make sure that you have owner/admin role.
You can make use of the below command to get Azure Ad subscriptions for a specific tenant:
Make sure to connect-azaccount with Administrator details.
Get-AzSubscription -TenantId "your_tenant_id"
Get-AzContext command list the information of the Azure Subscription that is currently selected.
To use a specific subscription, you can make use of below command:
Get-AzSubscription -SubscriptionId "xxxx-xxxx-xxxx-xxxx" -TenantId "yyyy-yyyy-yyyy-yyyy" | Set-AzContext
Or please modify your code by adding the below snippet:
$subscriptionId = 'Your_Subscription_ID';
Select-AzSubscription -SubscriptionId $subscriptionId
You can check the Subscription Id via Azure Portal too.
Reference:
Get-AzSubscription (Az.Accounts) | Microsoft Docs

Runbook automation fails but powershell cmd line works fine

I have the following powershell code for suspending azure d/w
$TenantId = "<>"
$SubscriptionId = "<>"
# Get the service principal credentials connected to the automation account.
$SPCredential = Get-AutomationPSCredential -Name "psvar"
# Login to Azure ($null is to prevent output, since Out-Null doesn't work in Azure)
Write-Output "Login to Azure using automation account 'psvar'."
$null = Login-AzureRmAccount -TenantId $TenantId -SubscriptionId $SubscriptionId -Credential $SPCredential
Write-Output "Login Status "
# Select the correct subscription
Write-Output "Selecting subscription '$($SubscriptionId)'."
$null = Select-AzureRmSubscription -SubscriptionID $SubscriptionId
$ResourceGroupName = '<>'
$ServerName = '<>'
$DatabaseName = '<>'
Write-Output "Suspending $($DatabaseName)..."
$null = Suspend-AzureRmSqlDatabase `
-ResourceGroupName $ResourceGroupName`
-DatabaseName $DatabaseName`
-ServerName $ServerName
Write-Output "Done"
Suspend azure rm sqldatabase works fine in PowerShell Azure Command line interface
But in runbook automation it fails with
Suspend-AzureRmSqlDatabase : Run Login-AzureRmAccount to login.
At line:33 char:9
+ $null = Suspend-AzureRmSqlDatabase `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Suspend-AzureRmSqlDatabase], PSInvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperation,Microsoft.Azure.Commands.Sql.DatabaseActivation.Cmdlet.SuspendAzureSqlDatabase
Any idea what could be wrong. Appreciate any pointers regarding this
I test your script, it works in the runbook.
Navigate to the automation account -> Credentials, make sure your user account name and password are correct.
If it still not work, you could try my solution here, it works.
For Azure Synapse analytics we need to use
Update-AzSynapseSqlPool -WorkspaceName <wsname>-Name <dbname> -Pause

Azure runbook - run Powershell on remote VM

Azure runbook.
The question:
How to run/call powershell scripts on remote Azure VM via runbook? The script is placed on a remote VM.
There is no Azure AD, powershell has Az module installed.
Thank you.
Have your Azure Automation runbook something like shown below. It will accomplish your requirement.
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Add-AzAccount -ServicePrincipal -TenantId $ServicePrincipalConnection.TenantId -ApplicationId $ServicePrincipalConnection.ApplicationId -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
$rgname ="rrrrrrrrrrrrrr"
$vmname ="vvvvvvvvvvvvvv"
$ScriptToRun = "ssssssssssssss"
Out-File -InputObject $ScriptToRun -FilePath ScriptToRun.ps1
Invoke-AzVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunPowerShellScript' -ScriptPath ScriptToRun.ps1
Remove-Item -Path ScriptToRun.ps1
Note: Before you run your runbook, make sure you update "rrrrrrrrrrrrrr" with your resource group name, "vvvvvvvvvvvvvv" with your VM name and "ssssssssssssss" with the path of the script along with script name
For reference, you may refer the source from here.
Hope this helps!! Cheers!!

How can I assure that newly created prod azure resources are locked by policy?

I'm an Azure administrator. I want to assure that new resources created in production are automatically locked when they're created. Is there a way to set that policy? I know I can create locks with the CLI/GUI. I need to do it automatically without scripting az commands.
Thanks
You can use Azure Blueprints to do this.
https://learn.microsoft.com/en-us/azure/governance/blueprints/tutorials/protect-new-resources
or you can do it by scheduling a Runbook in an automation account. I have built a script for this that locks the Resource Groups that i have scheduled every night. Locking can have a negative impact on functionallity and sometimes its enoying if your resources gets locked to early.
In my code below i have excluded AzureBackup_RG_ since it breaks the functionallity of deleting snapshots which causes the backup to fail after a while.
<###########################################################################################################
#
# LckResourceGroup
#
# This script is intended to run daily to lock all resource groups to prevent accidential deletion
# of resources.
#
# Written by Daniel Björk - 2018-02-27
# Designed for Accigo AB
#
#
# Ver 1.0 Date 2018-02-27
# First Version
#
Instructions
1. Import Az.Accounts to the Automation Account
2. Import Az.Resources to the Automation Account
3. Create Runbook (Copy Powershell)
4. Schedule runbook
#
###########################################################################################################>
# INFORMATION: Change Subscription name to enable on other subscriptions
$SubScriptionName = "SubscriptionName"
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint | Out-Null
Write-Output "Select Subscription"
Select-AzSubscription -SubscriptionName $SubScriptionName
$resourceGroups = Get-AzResourceGroup | where {!$_.ResourceGroupName.StartsWith("AzureBackup")}
foreach ($resourceGroup in $resourceGroups) {
Write-Output $resourceGroup.ResourceGroupName
$lockId = (Get-AzResourceLock -ResourceGroupName $resourceGroup.ResourceGroupName).LockId
#Remove-AzureRmResourceLock -LockId $lockId
if (!$lockId -and !$resourceGroup.ResourceGroupName.StartsWith("AzureBackupRG_")){
Write-Output "Locking Resource Group"
New-AzResourceLock `
-LockName ResourceGroupLock `
-LockLevel CanNotDelete `
-LockNotes 'Locks all resources in the resource group' `
-ResourceGroupName $resourceGroup.ResourceGroupName `
-Force
}
}

Select-AzureRmSubscription : Please provide a valid tenant or a valid subscription

I have created the Powershell Runbook, and added all the required details and valid values. Still I am facing the error for Select-AzureRmSubscription command. The error I am getting all the time is
Select-AzureRmSubscription : Please provide a valid tenant or a valid subscription.
I am using below connection setting in Powershell runbook:
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount -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
}
}
fetch-group-memberships | Select-Object UserName, PrincipalName, GroupName, AzureGroupName |Sort-Object GroupName| Export-Csv -NoTypeInformation -Path
'MEMBERSHIP.csv'
#=======================================================================================
# Select the subscription you are going to work with
#=======================================================================================
Select-AzureRmSubscription -SubscriptionId
"[removed for security purpose]"
#Get-AzureRmSubscription -SubscriptionName "BIG" | Select-AzureRmSubscription
#=======================================================================================
# Set the Current Storage Account to the approperiate location
#=======================================================================================
Set-AzureRmCurrentStorageAccount -StorageAccountName devapacbi01 -ResourceGroupName dev-rgp-apac-01
#=======================================================================================
# Capture the file that is local to automation and save to Storage Blob
#=======================================================================================
Set-AzureStorageBlobContent -Container bi-app-carm-im -File ADGROUP_MEMBERSHIP.csv -Blob _MEMBERSHIP_AL.csv -Force
Even if the subscription id is correct it keeps throwing an error as above.
this means you do not have permissions to do so. you need to assign proper permissions to the account you are using for the runbook
You do not need to Select-AzureRmSubscription because runbook connection is only tied to on subscription.
Also keep in mid the runbook is running on a environment setup to run your script, I prefer to stay away from Set environment commands.
Removing the subscription line and fixing lines below should work.
$storageAccount = Get-AzureRmStorageAccount -StorageAccountName devapacbi01 -ResourceGroupName dev-rgp-apac-01
Set-AzureStorageBlobContent -Container bi-app-carm-im -File ADGROUP_MEMBERSHIP.csv -Blob _MEMBERSHIP_AL.csv -Context $storageAccount.Context -Force
Hope this helps.
Its Solved! You guys were correct, it was an issue with correct permissions with Automation Account only. We should have a access as a contributor on your storage account. After giving right permissions to automation RunAs (contributor on your storage account) it worked and ran successfully. Than you all again.

Resources