Tag: Powershell

  • How to Assign Permissions to an Azure Automation Account

    If you need to create an automation for azure resource where you need to send an email or get access to resources and perform some routine tasks, a managed identity needs to have some permissions in your azure tenant.

    Instead of creating a new managed identity, you use the system assigned identity of the automation account itself to run the PowerShell or Python runbooks within and Schedule it.

    Although you can see the automation account listed on enterprise apps, when you select the application type as managed identity, you can’t directly assign permissions to it via Azure Portal. In this scenario, you can use azure cloud shell and use PowerShell to assign required permissions. Here is a short script to assign mail.send permission to an automation account managed identity.

    # Variables
    $resourceGroupName = "rg-automations"
    $automationAccountName = "aa-myautoacc"
    $appId = "00000003-0000-0000-c000-000000000000" # Microsoft Graph App ID
    $permissionName = "Mail.Send"
    
    # Connect to Azure (if not already connected)
    Connect-AzAccount
    
    # Get the automation account
    $automationAccount = Get-AzAutomationAccount -ResourceGroupName $resourceGroupName -Name $automationAccountName
    
    # Get the managed identity's service principal
    $servicePrincipal = Get-AzADServicePrincipal -ObjectId $automationAccount.Identity.PrincipalId
    
    if ($null -eq $servicePrincipal) {
        Write-Error "Managed identity not found. Ensure the automation account has a system-assigned managed identity enabled."
        exit
    }
    
    Write-Host "Found service principal: $($servicePrincipal.DisplayName)" -ForegroundColor Green
    
    # Get Microsoft Graph service principal
    $graphServicePrincipal = Get-AzADServicePrincipal -ApplicationId $appId
    
    # Get the Mail.Send application permission
    $appRole = $graphServicePrincipal.AppRole | Where-Object { $_.Value -eq $permissionName -and $_.AllowedMemberType -contains "Application" }
    
    if ($null -eq $appRole) {
        Write-Error "Mail.Send permission not found in Microsoft Graph"
        exit
    }
    
    # Check if the permission is already assigned
    $existingAssignment = Get-AzADServicePrincipalAppRoleAssignment -ServicePrincipalId $servicePrincipal.Id | 
        Where-Object { $_.AppRoleId -eq $appRole.Id -and $_.ResourceId -eq $graphServicePrincipal.Id }
    
    if ($existingAssignment) {
        Write-Host "Mail.Send permission is already assigned" -ForegroundColor Yellow
    } else {
        # Assign the Mail.Send permission
        New-AzADServicePrincipalAppRoleAssignment `
            -ServicePrincipalId $servicePrincipal.Id `
            -ResourceId $graphServicePrincipal.Id `
            -AppRoleId $appRole.Id
    
        Write-Host "Mail.Send permission assigned successfully!" -ForegroundColor Green
    }