Advertisement
Guest User

Untitled

a guest
May 24th, 2019
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.86 KB | None | 0 0
  1. <#
  2. .SYNOPSIS
  3. Wrapper script for get all the VM's in all RG's or subscription level and then Start or Stop all valid required VMs in loop
  4. .DESCRIPTION
  5. This runbook is intended to start/stop VMs (ARM based VMs) that resides in a given list of Azure resource group(s).If the resource group list is empty, then the script gets all the VMs in the current subscription.
  6. Upon completion of the runbook, an option to email results of the started VM can be sent via SendGrid account.
  7.  
  8. This runbook requires the Azure Automation Run-As (Service Principle) account, which must be added when creating the Azure Automation account.
  9. .EXAMPLE
  10. .\start_stop_VM.ps1 -Action "Value1" -WhatIf "False"
  11.  
  12. .PARAMETER
  13. Parameters are read in from Azure Automation variables.
  14. Variables (editable):
  15. - External_Start_ResourceGroupNames : ResourceGroup that contains VMs to be started. Must be in the same subscription that the Azure Automation Run-As account has permission to manage.
  16. - External_Stop_ResourceGroupNames : ResourceGroup that contains VMs to be stopped. Must be in the same subscription that the Azure Automation Run-As account has permission to manage.
  17. - External_ExcludeVMNames : VM names to be excluded from being started.
  18.  
  19. #>
  20.  
  21. Param(
  22. [Parameter(Mandatory=$true,HelpMessage="Enter the value for Action. Values can be either stop or start")][String]$Action,
  23. [Parameter(Mandatory=$false,HelpMessage="Enter the value for WhatIf. Values can be either true or false")][bool]$WhatIf = $false,
  24. [Parameter(Mandatory=$false,HelpMessage="Enter the VMs separated by comma(,)")][string]$VMList
  25. )
  26.  
  27.  
  28. function ValidateVMList ($FilterVMList)
  29. {
  30.  
  31. [boolean] $ISexists = $false
  32. [string[]] $invalidvm=@()
  33. $ExAzureVMList=@()
  34.  
  35. foreach($filtervm in $FilterVMList)
  36. {
  37. $currentVM = Get-AzureRmVM | where Name -Like $filtervm.Trim() -ErrorAction SilentlyContinue
  38.  
  39. if ($currentVM.Count -ge 1)
  40. {
  41. $ExAzureVMList+= @{Name = $currentVM.Name; Location = $currentVM.Location; ResourceGroupName = $currentVM.ResourceGroupName; Type = "ResourceManager"}
  42. $ISexists = $true
  43. }
  44. elseif($ISexists -eq $false)
  45. {
  46. $invalidvm = $invalidvm+$filtervm
  47. }
  48. }
  49.  
  50. if($invalidvm -ne $null)
  51. {
  52. Write-Output "Runbook Execution Stopped! Invalid VM Name(s) in the VM list: $($invalidvm) "
  53. Write-Warning "Runbook Execution Stopped! Invalid VM Name(s) in the VM list: $($invalidvm) "
  54. exit
  55. }
  56. else
  57. {
  58. return $ExAzureVMList
  59. }
  60.  
  61. }
  62.  
  63.  
  64. function CheckExcludeVM ($FilterVMList)
  65. {
  66. [boolean] $ISexists = $false
  67. [string[]] $invalidvm=@()
  68. $ExAzureVMList=@()
  69.  
  70. foreach($filtervm in $FilterVMList)
  71. {
  72. $currentVM = Get-AzureRmVM | where Name -Like $filtervm.Trim() -ErrorAction SilentlyContinue
  73. if ($currentVM.Count -ge 1)
  74. {
  75. $ExAzureVMList+=$currentVM.Name
  76. $ISexists = $true
  77. }
  78. elseif($ISexists -eq $false)
  79. {
  80. $invalidvm = $invalidvm+$filtervm
  81. }
  82.  
  83. }
  84. if($invalidvm -ne $null)
  85. {
  86. Write-Output "Runbook Execution Stopped! Invalid VM Name(s) in the exclude list: $($invalidvm) "
  87. Write-Warning "Runbook Execution Stopped! Invalid VM Name(s) in the exclude list: $($invalidvm) "
  88. exit
  89. }
  90. else
  91. {
  92. Write-Output "Exclude VM's validation completed..."
  93. }
  94. }
  95.  
  96. #-----L O G I N - A U T H E N T I C A T I O N-----
  97. $connectionName = "AzureRunAsConnection"
  98. try
  99. {
  100. # Get the connection "AzureRunAsConnection "
  101. $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
  102.  
  103. "Logging in to Azure..."
  104. Add-AzureRmAccount `
  105. -ServicePrincipal `
  106. -TenantId $servicePrincipalConnection.TenantId `
  107. -ApplicationId $servicePrincipalConnection.ApplicationId `
  108. -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
  109. }
  110. catch
  111. {
  112. if (!$servicePrincipalConnection)
  113. {
  114. $ErrorMessage = "Connection $connectionName not found."
  115. throw $ErrorMessage
  116. } else{
  117. Write-Error -Message $_.Exception
  118. throw $_.Exception
  119. }
  120. }
  121.  
  122.  
  123. #---------Read all the input variables---------------
  124.  
  125. $StartResourceGroupNames = Get-AutomationVariable -Name 'External_Start_ResourceGroupNames'
  126. $StopResourceGroupNames = Get-AutomationVariable -Name 'External_Stop_ResourceGroupNames'
  127. $ExcludeVMNames = Get-AutomationVariable -Name 'External_ExcludeVMNames'
  128.  
  129.  
  130.  
  131. try
  132. {
  133. $Action = $Action.Trim().ToLower()
  134.  
  135. if(!($Action -eq "start" -or $Action -eq "stop"))
  136. {
  137. Write-Output "`$Action parameter value is : $($Action). Value should be either start or stop."
  138. Write-Output "Completed the runbook execution..."
  139. exit
  140. }
  141. Write-Output "Runbook Execution Started..."
  142. [string[]] $VMfilterList = $ExcludeVMNames -split ","
  143. #If user gives the VM list with comma seperated....
  144. $AzurVMlist = Get-AutomationVariable -Name $VMList
  145. if(($AzurVMlist))
  146. {
  147. Write-Output "list of all VMs = $($AzurVMlist)"
  148. [string[]] $AzVMList = $AzurVMlist -split ","
  149. }
  150. if($Action -eq "stop")
  151. {
  152. Write-Output "List of all ResourceGroups = $($StopResourceGroupNames)"
  153. [string[]] $VMRGList = $StopResourceGroupNames -split ","
  154. }
  155.  
  156. if($Action -eq "start")
  157. {
  158. Write-Output "List of all ResourceGroups = $($StopResourceGroupNames)"
  159. [string[]] $VMRGList = $StartResourceGroupNames -split ","
  160. }
  161.  
  162. #Validate the Exclude List VM's and stop the execution if the list contains any invalid VM
  163. if (([string]::IsNullOrEmpty($ExcludeVMNames) -ne $true) -and ($ExcludeVMNames -ne "none"))
  164. {
  165. Write-Output "Values exist on the VM's Exclude list. Checking resources against this list..."
  166. CheckExcludeVM -FilterVMList $VMfilterList
  167. }
  168. $AzureVMListTemp = $null
  169. $AzureVMList=@()
  170.  
  171. if ($AzVMList -ne $null)
  172. {
  173. ##Action to be taken based on VM List and not on Resource group.
  174. ##Validating the VM List.
  175. Write-Output "VM List is given to take action (Exclude list will be ignored)..."
  176. $AzureVMList = ValidateVMList -FilterVMList $AzVMList
  177. }
  178. else
  179. {
  180.  
  181. ##Getting VM Details based on RG List or Subscription
  182. if (($VMRGList -ne $null) -and ($VMRGList -ne "*"))
  183. {
  184. foreach($Resource in $VMRGList)
  185. {
  186. Write-Output "Validating the resource group name ($($Resource))"
  187. $checkRGname = Get-AzureRmResourceGroup -Name $Resource.Trim() -ev notPresent -ea 0
  188.  
  189. if ($checkRGname -eq $null)
  190. {
  191. Write-Warning "$($Resource) is not a valid Resource Group Name. Please verify your input"
  192. }
  193. else
  194. {
  195. # Get resource manager VM resources in group and record target state for each in table
  196. $taggedRMVMs = Get-AzureRmVM | ? { $_.ResourceGroupName -eq $Resource}
  197. foreach($vmResource in $taggedRMVMs)
  198. {
  199. if ($vmResource.ResourceGroupName -Like $Resource)
  200. {
  201. $AzureVMList += @{Name = $vmResource.Name; ResourceGroupName = $vmResource.ResourceGroupName; Type = "ResourceManager"}
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else
  208. {
  209. Write-Output "Getting all the VM's from the subscription..."
  210. $ResourceGroups = Get-AzureRmResourceGroup
  211.  
  212. foreach ($ResourceGroup in $ResourceGroups)
  213. {
  214.  
  215. # Get resource manager VM resources in group and record target state for each in table
  216. $taggedRMVMs = Get-AzureRmVM | ? { $_.ResourceGroupName -eq $ResourceGroup.ResourceGroupName}
  217.  
  218. foreach($vmResource in $taggedRMVMs)
  219. {
  220. Write-Output "RG : $($vmResource.ResourceGroupName) , ARM VM $($vmResource.Name)"
  221. $AzureVMList += @{Name = $vmResource.Name; ResourceGroupName = $vmResource.ResourceGroupName; Type = "ResourceManager"}
  222. }
  223. }
  224.  
  225. }
  226. }
  227.  
  228. $ActualAzureVMList=@()
  229.  
  230. if($AzVMList -ne $null)
  231. {
  232. $ActualAzureVMList = $AzureVMList
  233. }
  234. #Check if exclude vm list has wildcard
  235. elseif(($VMfilterList -ne $null) -and ($VMfilterList -ne "none"))
  236. {
  237. $ExAzureVMList = ValidateVMList -FilterVMList $VMfilterList
  238.  
  239. foreach($VM in $AzureVMList)
  240. {
  241. ##Checking Vm in excluded list
  242. if($ExAzureVMList.Name -notcontains ($($VM.Name)))
  243. {
  244. $ActualAzureVMList+=$VM
  245. }
  246. }
  247. }
  248. else
  249. {
  250. $ActualAzureVMList = $AzureVMList
  251. }
  252.  
  253. Write-Output "The current action is $($Action)"
  254.  
  255. $ActualVMListOutput=@()
  256.  
  257. if($WhatIf -eq $false)
  258. {
  259. $AzureVMListARM=@()
  260.  
  261.  
  262. # Store the ARM VM's
  263. $AzureVMListARM = $ActualAzureVMList | Where-Object {$_.Type -eq "ResourceManager"}
  264.  
  265.  
  266. # process the ARM VM's
  267. if($AzureVMListARM -ne $null)
  268. {
  269. foreach($VM in $AzureVMListARM)
  270. {
  271. $ActualVMListOutput = $ActualVMListOutput + $VM.Name + " "
  272. #ScheduleSnoozeAction -VMObject $VM -Action $Action
  273.  
  274. #------------------------
  275. try
  276. {
  277. Write-Output "VM action is : $($Action)"
  278. Write-OutPut $VM.ResourceGroupName
  279.  
  280. $VMState = Get-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -status | Where-Object { $_.Name -eq $VM.Name }
  281. if ($Action.Trim().ToLower() -eq "stop")
  282. {
  283. Write-Output "Stopping the VM : $($VM.Name)"
  284. Write-Output "Resource Group is : $($VM.ResourceGroupName)"
  285.  
  286.  
  287. if($VMState.Statuses[1].DisplayStatus -ne "VM running")
  288. {
  289. Write-Output "VM is not in running state, No actions performed"
  290. }
  291. else
  292. {
  293. $Status = Stop-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -Force
  294.  
  295. if($Status -eq $null)
  296. {
  297. Write-Output "Error occured while stopping the Virtual Machine."
  298. }
  299. else
  300. {
  301. Write-Output "Successfully stopped the VM $($VM.Name)"
  302. }
  303. }
  304.  
  305. }
  306. elseif($Action.Trim().ToLower() -eq "start")
  307. {
  308. Write-Output "Starting the VM : $($VM.Name)"
  309. Write-Output "Resource Group is : $($VM.ResourceGroupName)"
  310.  
  311. if($VMState.Statuses[1].DisplayStatus -eq "VM running")
  312. {
  313. Write-Output "VM already Running, No actions performed"
  314. }
  315. else
  316. {
  317. $Status = Start-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName
  318.  
  319. if($Status -eq $null)
  320. {
  321. Write-Output "Error occured while starting the Virtual Machine $($VM.Name)"
  322. }
  323. else
  324. {
  325. Write-Output "Successfully started the VM $($VM.Name)"
  326. }
  327. }
  328. }
  329.  
  330. }
  331. catch
  332. {
  333. Write-Output "Error Occurred..."
  334. Write-Output $_.Exception
  335. }
  336. #--------------------------
  337. }
  338. Write-Output "Completed the $($Action) action on the following ARM VMs: $($ActualVMListOutput)"
  339. }
  340.  
  341.  
  342. }
  343. elseif($WhatIf -eq $true)
  344. {
  345. Write-Output "WhatIf parameter is set to True..."
  346. Write-Output "When 'WhatIf' is set to TRUE, runbook provides a list of Azure Resources (e.g. VMs), that will be impacted if you choose to deploy this runbook."
  347. Write-Output "No action will be taken at this time..."
  348. Write-Output $($ActualAzureVMList)
  349. }
  350. Write-Output "Runbook Execution Completed..."
  351. }
  352. catch
  353. {
  354. $ex = $_.Exception
  355. Write-Output $_.Exception
  356. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement