PPL.AzUtils.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
#Requires -Modules Az.Accounts, Az.Automation, Az.Storage


$Script:PSModuleRoot = $PSScriptRoot
# Importing from [/home/vsts/work/1/s/PPL.AzUtils\Public]
# ./PPL.AzUtils/Public/Connect-AzAutomationConnectionAccount.ps1


function Connect-AzAutomationConnectionAccount {

    [CmdletBinding()]
    Param (

    )


    Process {
        $connectionName = "AzureRunAsConnection"
        try
        {
            # Get the connection "AzureRunAsConnection "
            $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
            Write-Information "Logging in to Azure..."
            Connect-AzAccount -Tenant $servicePrincipalConnection.TenantID `
                                    -ApplicationId $servicePrincipalConnection.ApplicationID   `
                                    -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
                                    -ServicePrincipal
            Write-Verbose "Logged in."
        }
        catch {
            if (!$servicePrincipalConnection)
            {
                $ErrorMessage = "Connection $connectionName not found. ${_.Exception}"
                throw $ErrorMessage
            } else{
                Write-Error -Message $_.Exception
                throw $_.Exception
            }
        }
    }

}

# ./PPL.AzUtils/Public/Enable-FrontDoorBackend.ps1

function Enable-FrontDoorBackend {


    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Microsoft.Azure.Commands.FrontDoor.Models.PSFrontDoor] $Frontdoor,

        [Parameter (Mandatory = $true)]
        [string] $Pool,

        [Parameter (Mandatory = $true)]
        [string] $Backend
    )

    Process {
        $_backend = $Frontdoor | Get-FrontDoorBackend -Pool $Pool -Address $Backend
        $_backend.EnabledState = "Enabled"
    }
}

# ./PPL.AzUtils/Public/Get-FrontDoorBackend.ps1

function Get-FrontDoorBackend {


    [CmdletBinding()]
    [OutputType([Microsoft.Azure.Commands.FrontDoor.Models.PSBackend])]
    param (
        [Parameter(ValueFromPipeline)]
        [Microsoft.Azure.Commands.FrontDoor.Models.PSFrontDoor] $Frontdoor,

        [Parameter (Mandatory = $true)]
        [string] $Pool,

        [Parameter (Mandatory = $true)]
        [string] $Address
    )

    Process {
        $_address = $Address;
        $_pool = $Frontdoor | Get-FrontDoorBackendPool -Pool $Pool
        return ($_pool.Backends | Where-Object { $_.Address -eq $_address })[0]

    }



}

# ./PPL.AzUtils/Public/Get-FrontDoorBackendPool.ps1

function Get-FrontDoorBackendPool {


    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [Microsoft.Azure.Commands.FrontDoor.Models.PSFrontDoor] $Frontdoor,

        [Parameter (Mandatory = $true)]
        [string] $Pool
    )


    Process {
        $_pool = $Pool;
        return ($Frontdoor.BackendPools | Where-Object { $_.Name -eq $_pool })[0]
    }



}

# ./PPL.AzUtils/Public/Publish-PSModuleToAzAutomationAccount.ps1

<#
    .SYNOPSIS
    Publish a PowerShell module to an Azure Automation Account

    .DESCRIPTION
    Azure Automation can only import module from either the PowerShellGallery,
    or via a zip file fetched from a publically-accessible URL.

    This function takes a zip file containing a module and uploads it to an
    Azure Storage Blob, generates a short-lived SAS URL for accessing it and then
    passes this URL to the named AzureAutomation account so that it can import it.

    Once the module has been imported the storage blob will be deleted.

    .PARAMETER ModuleName
    Name of the module being published.

    .PARAMETER ModuleVersion
    Module version

    .PARAMETER ModuleZip
    Path to a zip file containing the module you wish to publish.

    .PARAMETER AutomationResourceGroup
    Name of the resource group containing your AutomationAccount.

    .PARAMETER AutomationAccount
    Name of the AutomationAccount to publish to.

    .PARAMETER StorageResourceGroup
    Name of the resource group containing the transfer storage account.

    .PARAMETER StorageAccount
    Name of the storage account to use for module transfer.

    .PARAMETER StorageContainer
    Name of the container in the storage account to use for module transfer.

    .PARAMETER DontCleanUpStorage
    Set this switch to *not* remove the transfer storage blob once transfer is complete.
    Useful for debugging issues.


#>

function Publish-PSModuleToAzAutomationAccount {

    [CmdletBinding()]
    Param (
        [Parameter (Mandatory = $true)]
        [string]  $ModuleName,

        [Parameter (Mandatory = $true)]
        [version] $ModuleVersion,

        [Parameter (Mandatory = $true)]
        [string]  $ModuleZip,

        [Parameter (Mandatory = $true)]
        [string]  $AutomationResourceGroup,

        [Parameter (Mandatory = $true)]
        [string]  $AutomationAccount,

        [Parameter (Mandatory = $true)]
        [string]  $StorageResourceGroup,

        [Parameter (Mandatory = $true)]
        [string]  $StorageAccount,

        [Parameter (Mandatory = $false)]
        [string]  $StorageContainer = "tmp",

        [Parameter (Mandatory = $false)]
        [switch]  $DontCleanUpStorage = $false

    )

    Process {


        Write-Output "Writing module to storage container"

        $storage = Get-AzStorageAccount `
            -ResourceGroupName $StorageResourceGroup    `
            -Name $StorageAccount

        $guid = New-Guid
        $blobName = "transfer-$($guid.ToString())"
        Write-Output "Uploading module [$ModuleName] as blob [$blobName]..."
        Set-AzStorageBlobContent            `
            -File $ModuleZip                `
            -Container $StorageContainer    `
            -Blob $blobName                 `
            -Context $storage.Context       `
            -Force


        Write-Output "Generating SAS token for resource blob..."
        $blobUrl = New-AzStorageBlobSASToken -FullUri       `
            -Context $storage.Context           `
            -Container $storageContainer        `
            -Blob $blobName                     `
            -Permission "r"                     `
            -Protocol "HttpsOnly"               `
            -ExpiryTime (Get-Date).AddMinutes(15)



        Write-Output "Checking if module [$ModuleName] is already present on automation account [$AutomationAccount]..."
        try
        {
            $module = Get-AzAutomationModule                `
                -Name $ModuleName                           `
                -ResourceGroupName $AutomationResourceGroup           `
                -AutomationAccountName $AutomationAccount   `

        }
        catch
        {
            $module = $null
        }


        if (!$module)
        {
            Write-Output "Module [$ModuleName] does not yet exist on automation account [$AutomationAccount], creating..."
            New-AzAutomationModule -Name $ModuleName        `
                -ContentLinkUri $blobUrl                    `
                -ResourceGroupName $AutomationResourceGroup           `
                -AutomationAccountName $AutomationAccount
        }
        else
        {
            Write-Output "Updating module [$ModuleName] on automation account [$AutomationAccount] to version [$ModuleVersion]..."
            Set-AzAutomationModule                          `
                -Name $ModuleName                           `
                -ContentLinkUri $blobUrl                    `
                -ContentLinkVersion $ModuleVersion          `
                -ResourceGroupName $AutomationResourceGroup           `
                -AutomationAccountName $AutomationAccount
        }


        Write-Output "Waiting for module [$ModuleName] to be imported..."
        $status = $null
        while ( $status -ne "Succeeded")
        {
            $module = Get-AzAutomationModule -Name $ModuleName -ResourceGroupName $AutomationResourceGroup -AutomationAccountName $AutomationAccount
            $status = $module.ProvisioningState
            if ($status -eq "Succeeded")
            {
                break;
            }
            Write-Verbose " ProvisioningState is [$status]. Waiting 2 seconds..."
            Start-Sleep -Seconds 2
        }


        if( ! $DontCleanUpStorage ) {
            Write-Output "Deleting transfer blob..."
            Remove-AzStorageBlob                `
                -Context $storage.Context       `
                -Container $StorageContainer    `
                -Blob $blobName                 `
                -Force -Verbose
        }

    }

}

# ./PPL.AzUtils/Public/Update-AzFrontDoorBackendEnabledState.ps1


function Update-AzFrontDoorBackendEnabledState {


    [CmdletBinding()]
    param (
        [Parameter (Mandatory = $true)]
        [string] $Subscription,

        [Parameter (Mandatory = $true)]
        [string] $ResourceGroup,

        [Parameter (Mandatory = $true)]
        [string] $FrontDoor,

        [Parameter (Mandatory = $true)]
        [string] $BackendPool,

        [Parameter (Mandatory = $true)]
        [string] $BackendAddress,

        [Parameter (Mandatory = $true)]
        [string] $EnabledState
    )


    Process {
        Set-AzContext -SubscriptionName $Subscription
        $_frontdoor = Get-AzFrontDoor -Name $FrontDoor -ResourceGroupName $ResourceGroup
        $_backend = $_frontdoor | Get-FrontDoorBackend -Pool $BackendPool -Address $BackendAddress
        $_backend.EnabledState = $EnabledState
        Set-AzFrontDoor -InputObject $_frontdoor
    }
}