AzureAutomation.psm1

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
383
384
<#
LICENSE:
The MIT License (MIT)
Copyright (c) 2020 Preston K. Parsard
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
DISCLAIMER:
THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. We grant You a nonexclusive,
royalty-free right to use and modify the Sample Code and to reproduce and distribute the Sample Code, provided that You agree: (i) to not use Our name,
logo, or trademarks to market Your software product in which the Sample Code is embedded;
(ii) to include a valid copyright notice on Your software product in which the Sample Code is embedded; and (iii) to indemnify, hold harmless,
and defend Us and Our suppliers from and against any claims or lawsuits, including attorneys’ fees,
that arise or result from the use or distribution of the Sample Code.
#>


function New-AutomationAccountRunAsServicePrincipal
{
<#
.SYNOPSIS
 Creates a new Azure Automation Account RunAs service principal.
.DESCRIPTION
 This script creates a new Azure Automation Account RunAs service principal, which will be granted contributor level access at the subscription level to execute runbooks in the subscription that the automation account belongs to.
 In order for this script to create the RunAs account, the user or service principal context in which this script is executed, must have owner permissions to the specified subscription.
.EXAMPLE
 New-AutomationAccountRunAsServicePrincipal -rgName <rgName> `
 -AutomationAccountName <AutomationAccountName> `
 -ApplicationDisplayName <ApplicationDisplayName> `
 -SubscriptionId <SubscriptionId> `
 -SelfSignedCertPlainPassword <SelfSignedCertPlainPassword> `
 -SelfSignedCertNoOfMonthsUntilExpired <NumberOfMonthsForCerificateExpiry> `
 -Verbose
.PARAMETER rgName
 The resource group name in which the Azure automation account resides.
.PARAMETER AutomationAccountName
 The Azure automaiton account name for which the RunAs account will be provisioned.
.PARAMETER SubscriptionId
 The subscription ID for the subscription that the automation account belongs to.
.PARAMETER SelfSignedCertPlainPassword
 The user supplied password for the self-signed certificate that will be associated with the RunAs service principal
.PARAMETER SelfSignedCertNoOfMonthsUntilExpired
 The certificate expiration period in months. The default is 12.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Azure Automation, Certificate, RunAs, Runbooks
.LINK
 1: https://www.powershellgallery.com/packages/AzureAutomation
 2: https://docs.microsoft.com/en-us/azure/automation/manage-runas-account
#>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [String] $rgName,
        [Parameter(Mandatory = $true)]
        [String] $AutomationAccountName,
        [Parameter(Mandatory = $true)]
        [String] $ApplicationDisplayName,
        [Parameter(Mandatory = $true)]
        [String] $SubscriptionId,
        [Parameter(Mandatory = $true)]
        [String] $SelfSignedCertPlainPassword,
        [int] $SelfSignedCertNoOfMonthsUntilExpired = 12
    ) # end param

    # Create self-signed certificate
    function New-SelfSignedCertificateForRunAsAccount
    {
        param
        (
            [string] $CertificateAssetName,
            [string] $SelfSignedCertPlainPassword,
            [string] $certPath,
            [string] $certPathCer,
            [string] $selfSignedCertNoOfMonthsUntilExpired
        ) # end param

        $Cert = New-SelfSignedCertificate -DnsName $$CertificateAssetName `
        -CertStoreLocation cert:\LocalMachine\My `
        -KeyExportPolicy Exportable `
        -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
        -NotAfter (Get-Date).AddMonths($selfSignedCertNoOfMonthsUntilExpired) `
        -HashAlgorithm SHA256

        $CertPassword = ConvertTo-SecureString $selfSignedCertPlainPassword -AsPlainText -Force
        Export-PfxCertificate -Cert ("Cert:\localmachine\my\" + $Cert.Thumbprint) -FilePath $certPath -Password $CertPassword -Force | Write-Verbose
        Export-Certificate -Cert ("Cert:\localmachine\my\" + $Cert.Thumbprint) -FilePath $certPathCer -Type CERT | Write-Verbose
    } # end function

    # Create the RunAs Account
    function New-ServicePrincipalForRunAsAccount
    {
        [OutputType([string])]
        [CmdletBinding()]
        param
        (
            [System.Security.Cryptography.X509Certificates.X509Certificate2] $PfxCert,
            [string] $ApplicationDisplayName
        ) # end param

        $keyValue = [System.Convert]::ToBase64String($PfxCert.GetRawCertData())
        $keyId = (New-Guid).Guid

        # Create an Azure AD application, AD App Credential, AD ServicePrincipal
        $homePage = "www." + $ApplicationDisplayName.ToLower() + ".com"
        # Requires Application Developer Role, but works with Application administrator or GLOBAL ADMIN
        New-AzADApplication -DisplayName $ApplicationDisplayName -HomePage ("http://" + $homePage) -IdentifierUris ("http://" + $keyId)
        $applicationId = (Get-AzAdApplication -DisplayName $ApplicationDisplayName | Where-Object {$_.IdentifierUris[0] -match $keyId}).ApplicationId.guid
        # Requires Application administrator or GLOBAL ADMIN
        # $ApplicationCredential = New-AzADAppCredential -ApplicationId $Application.ApplicationId -CertValue $keyValue -StartDate $PfxCert.NotBefore -EndDate $PfxCert.NotAfter
        New-AzADAppCredential -ApplicationId $applicationId -CertValue $keyValue -StartDate $PfxCert.NotBefore -EndDate $PfxCert.NotAfter
        # Requires Application administrator or GLOBAL ADMIN
        New-AzADServicePrincipal -ApplicationId $applicationId
        # New-AzADServicePrincipal -ApplicationId $Application.ApplicationId -PasswordCredential $ApplicationCredential
        # $servicePrincipalObj = Get-AzADServicePrincipal -ObjectId $ServicePrincipal.Id
        # Sleep here for a few seconds to allow the service principal application to become active (ordinarily takes a few seconds)
        Start-Sleep -Seconds 15
        # Requires User Access Administrator or Owner.
        $NewRole = New-AzRoleAssignment -ApplicationId $applicationId -RoleDefinitionName Contributor -ErrorAction SilentlyContinue
        $Retries = 0;
        While (($Retries -le 6) -and ($NewRole.RoleAssignmentId -eq $null))
        {
            Start-Sleep -Seconds 10
            $NewRole = Get-AzRoleAssignment -ServicePrincipalName $applicationId -ErrorAction SilentlyContinue
            $Retries++;
        } # end while
        return $applicationId
    } # end function

    # Create the certificate asset
    function New-AutomationCertificateAsset
    {
        param
        (
            [string] $resourceGroup,
            [string] $automationAccountName,
            [string] $certificateAssetName,
            [string] $certPath,
            [string] $certPlainPassword,
            [Boolean] $Exportable
        ) # end param

        $CertPassword = ConvertTo-SecureString $certPlainPassword -AsPlainText -Force
        Remove-AzAutomationCertificate -ResourceGroupName $resourceGroup -AutomationAccountName $automationAccountName -Name $certificateAssetName -ErrorAction SilentlyContinue -Verbose
        New-AzAutomationCertificate -AutomationAccountName $automationAccountName -Name $certificateAssetName -Path $certPath -Description $certificateAssetName -Password $CertPassword -ResourceGroupName $resourceGroup -Exportable:$Exportable  | write-verbose
    } # end function

    # Create the connection asset
    function New-AutomationConnectionAsset
    {
        param
        (
            # Had to overwrite the value for the $resourceGroup parameter and then later extract a substring of 19 characters to avoid the issue filed at:
            # https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/38585344-new-azautomationconnection-cmdlet-incorrectly-stat
            [string] $resourceGroup,
            [string] $automationAccountName,
            [string] $connectionAssetName,
            [string] $connectionTypeName,
            [System.Collections.Hashtable] $connectionFieldValues
        ) # end params

        Remove-AzAutomationConnection -ResourceGroupName $resourceGroup -AutomationAccountName $automationAccountName -Name $connectionAssetName -Force -ErrorAction SilentlyContinue -Verbose
        New-AzAutomationConnection -ResourceGroupName $resourceGroup -AutomationAccountName $automationAccountName -Name $connectionAssetName -ConnectionTypeName $connectionTypeName -ConnectionFieldValues $connectionFieldValues
    } # end function

    # Create a Run As account by using a service principal
    $CertificateAssetName = "AzureRunAsCertificate"
    $ConnectionAssetName = "AzureRunAsConnection"
    $ConnectionTypeName = "AzureServicePrincipal"

    $PfxCertPathForRunAsAccount = Join-Path $env:TEMP -ChildPath ($CertificateAssetName + ".pfx")
    $PfxCertPlainPasswordForRunAsAccount = $SelfSignedCertPlainPassword
    $CerCertPathForRunAsAccount = Join-Path $env:TEMP -ChildPath ($CertificateAssetName + ".cer")

    New-SelfSignedCertificateForRunAsAccount -CertificateAssetName $CertificateAssetName `
    -SelfSignedCertPlainPassword $SelfSignedCertPlainPassword `
    -certPath $PfxCertPathForRunAsAccount `
    -certPathCer $CerCertPathForRunAsAccount `
    -selfSignedCertNoOfMonthsUntilExpired  $SelfSignedCertNoOfMonthsUntilExpired

    # Create the Automation certificate asset
    New-AutomationCertificateAsset -resourceGroup $rgName `
    -automationAccountName $AutomationAccountName `
    -certificateAssetName $CertificateAssetName `
    -certPath $PfxCertPathForRunAsAccount `
    -certPlainPassword $PfxCertPlainPasswordForRunAsAccount `
    -Exportable $true
    # Wait for 2 minutes to avoid a race condition to allow the RunAs Account time to populate the certificate attributes.
    Start-Sleep -Seconds 120
    # Create a service principal
    $PfxCert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @($PfxCertPathForRunAsAccount, $PfxCertPlainPasswordForRunAsAccount)
    $applicationId = New-ServicePrincipalForRunAsAccount -PfxCert $PfxCert -applicationDisplayName $ApplicationDisplayName
    [guid]$applicationId = ($applicationId)[0].ApplicationId

    # Populate the ConnectionFieldValues
    $SubscriptionInfo = Get-AzSubscription -SubscriptionId $SubscriptionId
    $TenantID = $SubscriptionInfo | Select-Object TenantId -First 1
    $Thumbprint = $PfxCert.Thumbprint
    $ConnectionFieldValues = @{"ApplicationId" = $applicationId; "TenantId" = $TenantID.TenantId; "CertificateThumbprint" = $Thumbprint; "SubscriptionId" = $SubscriptionId}

    # Create an Automation connection asset named AzureRunAsConnection in the Automation account. This connection uses the service principal.
    New-AutomationConnectionAsset -resourceGroup $rgName `
    -automationAccountName $AutomationAccountName `
    -connectionAssetName  $ConnectionAssetName `
    -ConnectionTypeName  $ConnectionTypeName `
    -ConnectionFieldValues $ConnectionFieldValues

    # Cleanup temporary certificate files from local file system
    Remove-Item -Path $env:TEMP -Include *.pfx, *.cer -Force -Verbose

} # end function

function Publish-AutomationAccountRunbookScripts
{
<#
.SYNOPSIS
 Uploads and publishes a set of runbook scripts to an automation account.
.DESCRIPTION
 This function uploads and publishes a set of PowerShell runbook scripts to an Azure Automation account so they can be executed manually, triggered by an event, or scheduled.
.EXAMPLE
 Publish-AutomationAccountRunbookScripts -rbScripts <rbScripts> -ResourceGroupName <ResourceGroupName> -Verbose
.PARAMETER rbScripts
 The array of full runboook script paths to publish.
.PARAMETER ResourceGroupName
 The Azure resource group name hosting the automation account where the runbooks will be published to.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Azure Automation, Runbooks, Publish
.LINK
 1: https://www.powershellgallery.com/packages/AzureAutomation
#>

    [CmdletBinding()]
    param
    (
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]]$rbScripts,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$ResourceGroupName,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$AutomationAccountName
    ) # end param

    ForEach ($runbookScript in $runbookScripts)
    {
        Import-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Path $runbookScript -Type PowerShell -LogProgress $true -LogVerbose $true -Published -Verbose
    } # end foreach
} # end function

function New-AutomationAccountModules
{
<#
.SYNOPSIS
 Imports module assets into an Azure automation account.
.DESCRIPTION
 This function imports modules from the public https://www.powershellgallery.com repository, into a specified Azure automation account as a module asset to support runbooks or state configuration scripts.
.EXAMPLE
 New-AutomationAccountRunbookModules -ResourceGroupName <ResourceGroupName> -runbookModules <runbookModules>
.PARAMETER ResourceGroupName
 The resource group hosting the Azure automation account where the modules will be imported into.
.PARAMETER runbookModules
 The array of runbook modules that will be imported into the specified aut
.PARAMETER AutomationAccountName
 The Azure automation account that the modules will be imported into as module assets.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Modules, Azure Automation, Assets
.LINK
 1: https://www.powershellgallery.com/packages/AzureAutomation
 2: https://mcpmag.com/articles/2018/09/27/upload-powershell-gallery-module-to-azure.aspx
#>

    [CmdletBinding()]
    param
    (
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $ResourceGroupName,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]] $modules,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $AutomationAccountName
    ) # end param
    $i = 0
    $preReqModule = "Az.Accounts"
    $repoUriPrefix = (Find-Module -Name $preReqModule -Repository PSGallery).RepositorySourceLocation
    $repoUriInfix = "/package/"
    ForEach ($module in $modules)
    {
        $i++
        If ($i -eq 1)
        {
            $module = $preReqModule
            $uri = $repoUriPrefix + $repoUriInfix + $module
            New-AzAutomationModule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $module -ContentLinkUri $uri -Verbose -ErrorAction SilentlyContinue
        } # end if
        ElseIf ($module -ne $preReqModule)
        {
            $uri = $repoUriPrefix + $repoUriInfix + $module
            New-AzAutomationModule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $module -ContentLinkUri $uri -Verbose -ErrorAction SilentlyContinue
        } # end else if
        # Wait for 4 minutes
        Start-Sleep -Seconds 240
    } # end foreach
} # end function

function Format-AutomationAccountScheduleTimeZoneOffset
{
<#
.SYNOPSIS
 Convert the current UTC offset of the local time zone (i.e. -5 for EST US) into the runbook time scheduling format: "yyyy-MM-ddT00:00:00-00:00"
.DESCRIPTION
 This function will detect the current UTC offset based on the local system time from where the script executes, and convert it to the required Azure Automation Account schedule format so that runbooks can be scheduled.
.EXAMPLE
 Format-AutomationAccountScheduleTimeZoneOffset -offset <offset>
.PARAMETER offset
 The current UTC offset of the local system time zone from where the script executes (i.e. If the script runs from a machine in the US Eastern Standard Time zone <EST>, the offset would be "-5")
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: NSG, Network Security Group, Subnet
.LINK
 1: https://www.powershellgallery.com/ARMDeploy
#>

    [OutputType([string])]
    [CmdletBinding()]
    param
    (
        [ValidateLength(1,3)]
        [string]$offset
    ) # end param
    if ($offset -match "-")
    {
        $offset = $offset.Remove(0,1)
        If ($offset.Length -eq 1)
        {
            $offset = $offset.Insert(0,"-0")
        } # end if
        elseif ($offset.Length -eq 2)
        {
            $offset = $offset.Insert(0,"-")
        } # end else
    } # end if
    elseif ($offset -notmatch "-")
    {
        if ($offset.Length -eq 1)
        {
            $offset = $offset.Insert(0,"+0")
        } # end if
        elseif ($offset.Length -eq 2)
        {
            $offset = $offset.Insert(0,"+")
        } # end else
    } # end else if
    return $offset
} # end function

Export-ModuleMember -Function *AutomationAccount* -Verbose