Update-AutomationRunAsAccountRoleAssignments.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382

<#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