utils/AzureUtils.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
<#
.Synopsis
    Utility function to for Azure
.DESCRIPTION
   This function takes the cluster DNS name and type and fetches the relevant Hadoop configs
    
.EXAMPLE
    ## To be added.
     
.LINK
    https://github.com/mabushaireh/HDICloner
#>


function Get-AzureUtilsAccount($SubscriptionId) {

    Show-Debug "Passed value for SubscriptionId is set to $SubscriptionId"

    if (!$SubscriptionId) {
        Show-Warning "Default Subscription is going to be used!"
    }

    Show-Debug "Check if user already signed in to Azure Account!"

    $context = Get-AzContext

    if (!$context) {
        Show-Debug "Current Session is not logged to any Azure Account"
        Show-Prompt "Please login to your Azure Account"
        if ($SubscriptionId) {
            Show-Debug "Logging and selecting Subscription '$SubscriptionId'"
            $context = Connect-AzAccount -Subscription $SubscriptionId
            Show-Info "Subscription '$SubscriptionId' selected"
        }
        else {
            $context = Connect-AzAccount
            Show-Info "Subscription '$context.SubscriptionId' selected"
        }
    } 
    else {
        Show-Debug "Current Session has already logged to an Azure Account"
        if ($SubscriptionId) {
            if ($context.Subscription.Id -eq $SubscriptionId) {
                Show-Info "Subscription '" + $context.Subscription.Id + "' already selected."
            }
            else {
                Show-Debug "Subscription $SubscriptionId is not selected"
                $context = Select-AzSubscription $SubscriptionId
                Show-Info "Subscription $SubscriptionId is selected"
            }
        }
        else {
            Show-Info ("Subscription '" + $context.Subscription.Id + "' is selected.")
        }
    }

    return $context
}

function Deploy-AzureUtilsResource {
    [CmdletBinding()]
    param 
    (
        [Parameter(Mandatory = $true)] [string] $ResourceGroupName,
        [Parameter(Mandatory = $true)] [string] $ResourceName,
        [Parameter(Mandatory = $true)] [string] $Arm,
        [Parameter(Mandatory = $true)] [string] $DeploymentName,
        [Parameter(Mandatory = $true)] [Hashtable] $Params
    )

    $temp = ConvertTo-Json $Params -Depth 100

    Show-Debug "Passed value for ResourceGroupName is set to $ResourceGroupName"
    Show-Debug "Passed value for Arm is set to $Arm"
    Show-Debug "Passed value for ResourceName is set to $ResourceName"
    Show-Debug "Passed value for DeploymentName is set to $DeploymentName"
    Show-Debug "Passed value for Params is set to $temp"
    
    

    Show-Debug "Checking if Resource Group already exists.."

    $rs = Get-AzResourceGroup -Name $ResourceGroupName


    if (!$rs){
        Show-Warning "Resource Group $ResourceGroupName doesnt exists. Creating it."
        
        #TODO: get Cluster Location
        New-AzResourceGroup -Name $ResourceGroupName -Location "West Europe"

        Show-Info "Resource Group $ResourceGroupName created!"
    }

    $TemplateObject = ConvertFrom-Json $Arm -AsHashtable

    #Prepare-ArmTemplate ($TemplateObject["resources"])[0] $TemplateObject

    Show-Info "Prepare Arm template for new deployment"
    $oldResourceName = ($TemplateObject["resources"])[0]["name"]

    switch -Exact ((($TemplateObject["resources"])[0])["type"]) {
        'Microsoft.HDInsight/clusters' {
            # Chekc if params are correct
            # Storage Name
            # ambari username and password
            # ssh password
            # Network Profile (Optional)
            ($TemplateObject["resources"])[0]["name"] = $ResourceName


            Show-Debug "Delete blueprint"
            (((($TemplateObject["resources"])[0])["properties"])["clusterDefinition"]).Remove("blueprint")

            Show-Debug "blueprint properties removed"

            #add hduserPassword
            $hduserPassword = @{
                "gateway" = @{
                    "restAuthCredential.isEnabled" = "true"
                    "restAuthCredential.username" = $Params["hduser"]
                    "restAuthCredential.password" = $Params["hdpassword"]
                }
            }
            
            (((($TemplateObject["resources"])[0])["properties"])["clusterDefinition"]).Add("configurations", $hduserPassword)

            #add SshPassword
            (((((($TemplateObject["resources"])[0])["properties"])["computeProfile"])["roles"][0])["osProfile"])["linuxOperatingSystemProfile"].Add("password", $Params["sshpassword"])            
            (((((($TemplateObject["resources"])[0])["properties"])["computeProfile"])["roles"][1])["osProfile"])["linuxOperatingSystemProfile"].Add("password", $Params["sshpassword"])            
            (((((($TemplateObject["resources"])[0])["properties"])["computeProfile"])["roles"][2])["osProfile"])["linuxOperatingSystemProfile"].Add("password", $Params["sshpassword"]) 


            #Add storage Profile Key
            $storageName =  $Params["Storage"].substring(0, $dependicies.Storage.IndexOf(".")+2)
            Show-Debug "storageName is $storageName"

            $rsStroage = Get-AzResource -Name $storageName

            Show-Debug "rsStroage is $rsStroage"
            $resourceId = $rsStroage.ResourceId

            Show-Debug "resourceId is $resourceId"
            $TemplateObject["resources"][0]["properties"]["storageProfile"]["storageaccounts"][0].Add("key", "[listKeys('" + $resourceId  + "', '2015-05-01-preview').key1]") 
            $TemplateObject["resources"][0]["properties"]["storageProfile"]["storageaccounts"][0]["name"] =  $Params["Storage"]
        }
        'Microsoft.Storage/storageAccounts' {
            Show-Debug "Fix DependsOn Properties"
            foreach ($rs in $TemplateObject["resources"]) {
                if ($rs["dependsOn"]) {
                    $index = 0
                    foreach ($depend in $rs["dependsOn"]) {
                        if ($depend -contains "blobServices"){
                            $depend = "[resourceId('Microsoft.Storage/storageAccounts/blobServices', '$ResourceName', 'default')]"
                        } else {
                            $depend = "[resourceId('Microsoft.Storage/storageAccounts', '$ResourceName')]"
                        }
                        
                        $rs["dependsOn"][$index] = $depend
                        $index = $index + 1
                    }
                }

                $rs["name"] = $rs["name"].replace($oldResourceName, $ResourceName)
            }
        }
    }
    
    $temp = ConvertTo-Json $TemplateObject -Depth 100
    
    Show-Debug "Template after preparation $temp"

    Show-Info "Deployment $Name started!"
    New-AzResourceGroupDeployment -Name $DeploymentName -ResourceGroupName $ResourceGroupName -Mode Incremental -TemplateObject $TemplateObject
}


function Export-AzureUtilsResource {
    [CmdletBinding()]
    param 
    (
        [Parameter(Mandatory = $true)] [string] $ResourceName,
        [Parameter(Mandatory = $true)] [string] $Path
    )

    Show-Debug "ResourceName set to $ResourceName"

    Show-Info "Get Reosurce Resource Gruop"

    $rs = Get-AzResource -Name $ResourceName

    if (!$rs)
    {
        Show-Error "Resource $ResourceName not found!"
        return
    }

    Show-Info "Exporting " + $rs.Name +" of type [" + $rs.ResourceType + "]"
    Export-AzResourceGroup -ResourceGroupName $rs.ResourceGroupName -Resource $rs.ResourceId -SkipAllParameterization -IncludeComments -Path "$Path\$ResourceName.json" -Force
}


function Ger-AzureUtilsHdiDependencies {
    [CmdletBinding()]
    param 
    (
        [Parameter(Mandatory = $true)] [string] $ClusterDnsName
    )

    Show-Debug "ClusterDnsName set to $ClusterDnsName"

    $cluster = Get-AzHDInsightCluster -ClusterName $ClusterDnsName

    if (!$cluster) {
        Show-Error "Cluster not found!"
        return
    }

    $dependicies = @{
        ResourceGroup = $cluster.ResourceGroup
        Storage = $cluster.DefaultStorageAccount
        VNet = $cluster.VirtualNetworkId
        Subnet = $cluster.SubnetName
    }

    return $dependicies 
}