Update-AutomationRunAsAccountRoleAssignments.ps1


<#PSScriptInfo
 
.VERSION 1.0.1
 
.GUID 262c9086-ae62-4c89-9fa8-25f58d574469
 
.AUTHOR Automation Team
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS AzureAutomation
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
    Use this script to restrict the permissions of your Azure Automation RunAs accounts. You can:
    - Create a new custom role definition that excludes specified resources. If you use this script as-is, it will exclude Azure Key Vault; however,
      you can exclude any resource type as required in your organization.
    - Assign an existing custom role definition to your RunAs accounts.
    - Add more subscriptions to the scope of your custom role definition.
    - Change the role assignment of your RunAs account. For example, if your RunAs account has the original built-in "Contributor" role
      assigned to it, you can reassign it to your custom role definition.
    The script will update all automation accounts in all provided subscriptions.
 
#>
 

<#
.SYNOPSIS
    Use this script to restrict the permissions of your Azure Automation RunAs accounts.
 
.PREREQUISITES
    To run this script, your Powershell console has to be connected to Azure. Use Login-AzureRmAccount to log in.
    To run this script, you will need write permissions on role definitions and role assignments for all provided subscriptions.
    
.USAGE
    PS C:\MyScriptFolder>$mySubs = "00000000-0000-0000-0000-000000000000", "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222"
    PS C:\MyScriptFolder>.\Update-AutomationRunAsAccountRoleAssignments.ps1 `
            -SubscriptionIds $mySubs `
            -CustomRoleName <CustomRoleName> `
            -ParentSubscriptionId <ParentSubscriptionId> `
            -ReplaceCustomRoleAssignment <$true|$false> `
            -Confirm <$true|$false>
 
.PARAMETERS
    -SubscriptionIds
        This is an array of subscriptions whose role assignments you want to change. The array can contain one or more subscriptions.
 
    -CustomRoleName
        The name of your custom Role Definition. The following rules apply:
        - If this is the first custom role definition that you create, you need to provide a name that is not yet assigned to
          any other role definition within your AAD tenant. If you provide a name that is already assigned to another role definition
          within your AAD tenant, this operation will fail.
        - If you have already created your custom role definition, and now you want to add more subscriptions, you need to provide
          the name of a custom role definition that already exists. Please note that in this case you also need to provide the
          ParentSubscriptionId parameter (see above).
 
     -ParentSubscriptionId
        This is a subscription that is already in the assignable scope of your custom role definition. The script will run in the
        context of the parent subscription.
        - You will need this if you have already created your custom role definition, and now you want to add more subscriptions to its
          assignable scope.
        - If you use this script to create your first custom role definition you don't need this parameter.
 
   -ReplaceCustomRoleAssignment
        - If set to $true, it will delete existing role assignments for any role definition, built-in or custom.
        - If set to $false (default), it will only replace role assignments for the built-in "Contributor" role, but leave
          existing role assignments to custom role definitions in place.
        When you create a RunAs account, it has the built-in "Contributor" role assigned. If you want to change only this built-in role
        assignment, but not any custom role assignment that you or other members of your organization have created, you want to leave
        this parameter set to $false.
 
    -Confirm
        - If set to $true (default), a confirmation prompt will be displayed for each automation account before chaning it.
        - If set to $false, no confirmation prompt will be displayed. Use this only if you are absolutely sure that you want to
          change all role assignments in all provided subscriptions.
 
.ADVANCED TOPICS
    This script excludes Azure Key Vault from the custom role definition that it creates. If desired, you can exclude other resource
    types from the custom role definition as well. Follow these steps to customize the list of excluded resources:
        1. Locate the following code in the script below:
            $AutomationRunAsContributor.NotActions.Add("Microsoft.KeyVault/*")
        2. If for example you also want to exclude Azure Monitoring Workspaces from being accessible from your RunAs account, you could add
           the following line:
            $AutomationRunAsContributor.NotActions.Add("Microsoft.OperationalInsights/*")
 
.NOTES
    LASTEDIT: June 26, 2019
#>


Param (
    [Parameter(Mandatory = $true)]
    [String[]] $SubscriptionIds,

    [Parameter(Mandatory = $true)]
    [String] $CustomRoleName = "Automation RunAs Contributor",

    [Parameter(Mandatory = $false)]
    [String] $ParentSubscriptionId,

    [Parameter(Mandatory = $false)]
    [Boolean] $ReplaceCustomRoleAssignment = $false,

    [Parameter(Mandatory = $false)]
    [Boolean] $Confirm = $true,

    [Parameter(Mandatory = $false)]
    [bool] $UseAzModules = $false
)

function GetOrCreateCustomRoleDefinition([string] $customRoleName, [string[]] $subscriptionIds, [string] $parentSubscriptionId) 
{
    Select-AzureRmSubscription -SubscriptionId $parentSubscriptionId

    # Retrieve the existing "Contributor" role definition
    $builtinRoleDefinition = Get-AzureRmRoleDefinition -Name Contributor -ErrorAction Stop

    # Check whether the new custom role defition already exists in the AAD tenant, and whether
    # it can be reached within the context of our working subscription
    $customRoleDefinition = Get-AzureRmRoleDefinition -Name $customRoleName
    if ($customRoleDefinition) 
    {
        # The custom role definition already exists and can be reached. We add any of the provided subscriptions
        # to its assignable scope that isn't already in it

        Write-Host -ForegroundColor green "Custom Role definition '$CustomRoleName' already exists, checking if all provided subscriptions are in assignable scope."

        $addedSubsCount = 0
        $addedSubForVisibilityCheck = ""

        foreach ($subscriptionId in $subscriptionIds)
        {
            $assignableScopeExists = $false
            $newAssignableScope = "/subscriptions/" + $subscriptionId
            foreach ($assignableScope in $customRoleDefinition.AssignableScopes)
            {
                if ($assignableScope -eq $newAssignableScope)
                {
                    $assignableScopeExists = $true
                    Write-Host -ForegroundColor green "Subscription '$subscriptionId' is already in assignable scope."
                    break
                }
            }
            if ($assignableScopeExists -ne $true)
            {
                Write-Host "Adding subscription '$subscriptionId' to assignable scope."
                $customRoleDefinition.AssignableScopes.Add($newAssignableScope)
                $addedSubsCount++

                $addedSubForVisibilityCheck = $subscriptionId
            }
        }

        if ($addedSubsCount -gt 0)
        {
            # Adding subscriptions to the assignable scope of existing role definition
            Write-Host "Attempting to add subscriptions to assignable scope." 
            $customRoleDefinition = Set-AzureRmRoleDefinition -Role $customRoleDefinition -ErrorAction Stop
            Write-Host "Subscriptions have been added to assignable scope."

            # Changes to the role definition will not be visible immeiately, so we will wait in a loop until
            # one of the newly assigned subscription IDs can be found in the assignable scope
            $subsInAssignableScope = $false
            do
            {
                Write-Host "Adding subscriptions takes some time. Please wait." -ForegroundColor Yellow
                Start-Sleep -Seconds 20

                $checkRoleDefinition = Get-AzureRmRoleDefinition -Name $customRoleName
                foreach ($assignableScope in $checkRoleDefinition.AssignableScopes)
                {
                    if ($assignableScope -match $addedSubForVisibilityCheck)
                    {
                        Write-Host "Subscriptions was added." -ForegroundColor Green
                        $subsInAssignableScope = $true
                        break
                    }
                }

            } while ($subsInAssignableScope -eq $false)
            Write-Host "All provided subscriptions have been added to assignable scope. Continuing." -ForegroundColor Green
        }
        else
        {
            Write-Host "All provided subscriptions are already in assignable scope." -ForegroundColor Green
        }
    } 
    else 
    {
        # Create a new role definition for everything except Key Vault
        Write-Host -ForegroundColor yellow "New custom role definition '$CustomRoleName' will be created."
        $AutomationRunAsContributor = $builtinRoleDefinition
        $AutomationRunAsContributor.IsCustom = $true
        $AutomationRunAsContributor.Name = $customRoleName
        $AutomationRunAsContributor.Description = "Can manage all resources except Key Vault and access permissions"
        $AutomationRunAsContributor.Id = $null
        $AutomationRunAsContributor.NotActions.Add("Microsoft.KeyVault/*")
        $AutomationRunAsContributor.AssignableScopes.Clear()

        foreach ($subscriptionId in $subscriptionIds)
        {
            $newAssignableScope = "/subscriptions/" + $subscriptionId
            $AutomationRunAsContributor.AssignableScopes.Add($newAssignableScope)
        }

        $customRoleDefinition = New-AzureRMRoleDefinition -Role $AutomationRunAsContributor -ErrorAction Stop
    }

    return $customRoleDefinition
}

function GetRunAsAccountAADApplicationId([string] $resourceGroupName, [string] $automationAccountName) 
{  
    $connectionAssetName = "AzureRunAsConnection"

    $runasAccountConnection = Get-AzureRmAutomationConnection `
        -Name $connectionAssetName `
        -ResourceGroupName $resourceGroupName `
        -AutomationAccountName $automationAccountName `
        -ErrorAction SilentlyContinue

    $runasAccountAADAplicationId = $null
    if ($runasAccountConnection) 
    {
        [GUID]$runasAccountAADAplicationId=$runasAccountConnection.FieldDefinitionValues['ApplicationId']
        Write-Host ("A RunAs account is present, and its ApplicationId is: " + $runasAccountAADAplicationId)
    }

    return $runasAccountAADAplicationId;
}

function AssignCustomRoleToRunAsAccounts ([string] $subscriptionId)
{
    Select-AzureRmSubscription -SubscriptionId $subscriptionId
    $automationAccounts = Get-AzureRmAutomationAccount

    if (!$automationAccounts) 
    {
        Write-Host ("No automation account found in subscription " + $subscriptionId) -ForegroundColor Yellow
        Return
    } 

    Write-Host ("Changing role assignments for all automation accounts in subscription " + $subscriptionId) 

    foreach( $automationAccount in $automationAccounts)
    {
        Write-Host ("Changing role assignment for automation account: " + $automationAccount.AutomationAccountName)
        $runasAccountAADAplicationId = GetRunAsAccountAADApplicationId `
                                        -resourceGroupName $AutomationAccount.ResourceGroupName `
                                        -automationAccountName $AutomationAccount.AutomationAccountName
        if ($runasAccountAADAplicationId) 
        { 
            $subscriptionScope = "/subscriptions/" + $SubscriptionId
            if ($ReplaceCustomRoleAssignment -eq $true)
            {
                $currentRoleAssignments = Get-AzureRMRoleAssignment `
                    -ServicePrincipalName $runasAccountAADAplicationId `
                    -Scope $subscriptionScope `
                    -ErrorAction Stop
            }
            else
            {
                $currentRoleAssignments = Get-AzureRMRoleAssignment `
                    -ServicePrincipalName $runasAccountAADAplicationId `
                    -RoleDefinitionName "Contributor" `
                    -Scope $subscriptionScope `
                    -ErrorAction Stop
            }

            Write-Host "The following role assignments exist in this automation account:"
            $currentRoleAssignments

            $hasContributorRoleAssignment = $false
            foreach ($roleAssignment in $currentRoleAssignments)
            {
                if ($roleAssignment.RoleDefinitionName -eq "Contributor")
                {
                    $hasContributorRoleAssignment = $true
                    Break
                }
            }

            if (($hasContributorRoleAssignment -eq $true) -or ($ReplaceCustomRoleAssignment -eq $true)) 
            {
                # Confirmation
                if ($Confirm -eq $true)
                {
                    $automationAccountName = $automationAccount.AutomationAccountName
                    $promptMessage = "Are you sure to change the RunAs account role assignment for automation account $automationAccountName ? [y/n]"
                    $reply = Read-Host -Prompt $promptMessage
                }

                if (($reply -match "[yY]") -or ($Confirm -eq $false))
                {
                    Write-Host ("Deleting existing role assignments from " + $automationAccount.AutomationAccountName)
                    foreach ($roleAssignment in $currentRoleAssignments)
                    {
                        if (($roleAssignment.RoleDefinitionName -eq "Contributor") -or ($ReplaceCustomRoleAssignment -eq $true))
                        {
                            Remove-AzureRmRoleAssignment -InputObject $roleAssignment -ErrorAction Stop
                            Write-Host ("Deleted role assignment to " + $roleAssignment.RoleDefinitionName)
                        }
                    }

                    Write-Host ("Creating new role assignment for " + $automationAccount.AutomationAccountName)
                    $customRoleAssignment = New-AzureRmRoleAssignment `
                                        -RoleDefinitionName $CustomRoleName `
                                        -ServicePrincipalName $runasAccountAADAplicationId `
                                        -ErrorAction Stop
            
                    Write-Host "Created a new role assignment:" -ForegroundColor Green
                    $customRoleAssignment
                } else {
                    # No action
                    Write-Host 
                }
            } 
            else 
            {
                Write-Host ("Automation account: " + $automationAccount.AutomationAccountName + " was not changed because Contributor role was not assigned to RunAs account.") -ForegroundColor Yellow
                Write-Host 
            }
        } else {
            Write-Host  ("Automation account: " + $AutomationAccount.AutomationAccountName + " was not changed because RunAs account does not exist.") -ForegroundColor Yellow
            Write-Host
        }       
    }
}

# Main code starts here


if ($SubscriptionIds.Count -lt 1)
{
    Write-Host "No subscription IDs were provided. Please provide at least 1 subscription ID." -ForegroundColor Yellow
    exit -1
}

if (!$ParentSubscriptionId)
{
    Write-Host "No parent subscription ID was provided. Attempting to run this in the context of the first provided subscription ID." -ForegroundColor Green
    $ParentSubscriptionId = $SubscriptionIds[0]
}

# Get or create the new custom role definition. If this is successful, all listed subscription IDs should be in the
# assignable scope of the role definition.
$customRoleDefinition = GetOrCreateCustomRoleDefinition `
    -customRoleName $CustomRoleName `
    -subscriptionIds $SubscriptionIds `
    -parentSubscriptionId $ParentSubscriptionId

# Make new role assignments for automation accounts in all provided subscriptions
foreach ($subscriptionId in $SubscriptionIds)
{
    AssignCustomRoleToRunAsAccounts -subscriptionId $subscriptionId
}


# Main code ends here