-
Notifications
You must be signed in to change notification settings - Fork 10
/
StopCluster.ps1
85 lines (74 loc) · 2.94 KB
/
StopCluster.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
$connectionName = "AzureRunAsConnection"
$clusters = @(
[pscustomobject]@{AKS_NAME='<<aksservicename>>';AKS_RG='<<aksserviceresourcegroup>>';AKS_SUBSCRIPTION='<<aksservicesubscription>>'}
)
function RunScript()
{
$clusters | ForEach-Object {
$AKS_SUBSCRIPTION=$_.AKS_SUBSCRIPTION
$AKS_RG=$_.AKS_RG
$AKS_NAME=$_.AKS_NAME
$URI="https://management.azure.com/subscriptions/$AKS_SUBSCRIPTION/resourceGroups/$AKS_RG/providers/Microsoft.ContainerService/managedClusters/$AKS_NAME/stop?api-version=2020-09-01"
$token=Get-AzureRmBearerToken
$headers = @{
'Authorization' = "Bearer $token"
}
Invoke-RestMethod -Method Post -Uri $URI -ContentType "application/json" -Headers $headers
}
}
function Authenticate(){
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
}
function Get-AzureRmCachedAccessToken()
{
$ErrorActionPreference = 'Stop'
if(-not (Get-Module AzureRm.Profile)) {
Import-Module AzureRm.Profile
}
$azureRmProfileModuleVersion = (Get-Module AzureRm.Profile).Version
# refactoring performed in AzureRm.Profile v3.0 or later
if($azureRmProfileModuleVersion.Major -ge 3) {
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
if(-not $azureRmProfile.Accounts.Count) {
Write-Error "Ensure you have logged in before calling this function."
}
} else {
# AzureRm.Profile < v3.0
$azureRmProfile = [Microsoft.WindowsAzure.Commands.Common.AzureRmProfileProvider]::Instance.Profile
if(-not $azureRmProfile.Context.Account.Count) {
Write-Error "Ensure you have logged in before calling this function."
}
}
$currentAzureContext = Get-AzureRmContext
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile)
Write-Debug ("Getting access token for tenant" + $currentAzureContext.Tenant.TenantId)
$token = $profileClient.AcquireAccessToken($currentAzureContext.Tenant.TenantId)
$token.AccessToken
}
function Get-AzureRmBearerToken()
{
$ErrorActionPreference = 'Stop'
('{0}' -f (Get-AzureRmCachedAccessToken))
}
Authenticate
RunScript