在 Azure 虚拟机上运行脚本,使用自定义脚本扩展

随着您的团队开始配置更多的Windows Azure虚拟机(VM),在某个时候,您会厌倦重复造轮子。您需要自动化!在这篇文章中,跟着我一步步来开始使用Azure自定义脚本扩展在Azure上运行脚本以在您的VM上执行脚本。

如果您的团队在Windows环境中,自动化服务器配置的最佳工具之一是PowerShell。通过使用Azure PowerShell模块,您的组织不仅可以利用PowerShell的强大功能来自动化本地任务,还可以批量在Azure VM上运行命令,而不是逐个执行。

微软提供给我们的一个功能是Azure自定义脚本扩展。自定义脚本扩展是Azure虚拟机扩展,VM代理程序通过使用Azure API而不是控制台登录VM或使用PowerShell远程来执行任意PowerShell代码。

以这种方式运行命令有几个好处。在Windows中使用Azure自定义扩展运行命令:

  • 提供了更高的安全性,无需为PowerShell远程打开网络端口
  • 允许在VM启动时轻松执行PowerShell代码
  • 作为配置过程的一部分,自动将资源从Azure存储传输到您的VM
  • 一个运行存储在不同 Azure 存储账户中的 PowerShell 脚本的简单方法

在 Windows 上启用 Azure 自定义脚本扩展有几种方法。在本文中,我们将重点介绍通过 PowerShell 启用自定义脚本扩展的方法,但您也可以通过 Azure 资源管理器(ARM)模板来启用该扩展。

作为一个简单的示例,假设您想要确保 Azure 订阅中的 Azure VM 上启用了 PowerShell 远程管理。为此,您需要在每台 VM 上本地运行以下命令:

Enable-PSRemoting -Force

让我们来构建一个自定义脚本扩展来实现这个目标。

使用 Azure 在 VM 上运行脚本

首先,在您的本地计算机上创建一个名为 Enable-PSRemoting.ps1 的 PowerShell 脚本,其中包含上述命令。该脚本需要在 Azure VM 上运行。为了实现这一点,我们将创建另一个小的 PowerShell 脚本,名为 New-CustomScriptExtension.ps1,将其上传到 Azure,并创建一个自定义脚本扩展来执行它。在我们进展太远之前,您需要几个项目:

  • 将存储脚本的 Azure 资源组和存储账户名称
  • Azure 存储容器名称
  • VM 名称
  • VM 所在的 Azure 资源组名称

这个脚本可以分为两个部分;将小的 PowerShell 脚本上传到 Azure 并创建自定义脚本扩展。其余的内容是将这两个流程粘合在一起所必需的。

将 PowerShell 脚本上传到 Azure

首先,我们将上传 Enable-PSRemoting.ps1 脚本到 Azure 存储账户($StorageAccountName)中的容器($ContainerName)里,所在资源组为($ResourceGroupName)。

Copying Enable-PSRemoting.ps1 to Azure
$saParams = @{ 'ResourceGroupName' = $ResourceGroupName 'Name' = $StorageAccountName } $storageContainer = Get-AzureRmStorageAccount @saParams |Get-AzureStorageContainer -Container $ContainerName $bcParams = @{ 'File' = 'C:\Enable-PSRemoting.ps1' 'BlobType' = 'Block' 'Blob' = ' Enable-PSRemoting.ps1' } $storageContainer | Set-AzureStorageBlobContent @bcParams

运行自定义脚本扩展

当您运行 New-CustomScriptExtension.ps1 时,此脚本将会上传指定的 Enable-PSRemoting.ps1 脚本到 Azure 存储账户中。

现在,脚本已存储在 Azure 中,您可以通过 VM 的自定义脚本扩展来执行它:

  • 名称:$VMName
  • 资源组:$rgName
  • 存储账户:$saName
  • 存储容器:$scName

打开文本编辑器,输入 New-CustomScriptExtension.ps1 并粘贴以下示例。运行此示例将执行 Windows 的 Azure 自定义脚本扩展,该扩展将执行您之前上传的 Enable-PSRemoting.ps1 PowerShell 脚本。

New-CustomScriptExtension.ps1
# 获取我们需要配置的 VM $vm = Get-AzureRmVM -ResourceGroupName $rgName -Name $VMName # 获取存储账户密钥 $key = (Get-AzureRmStorageAccountKey -Name $saName -ResourceGroupName$rgname).Key1 ## 启用自定义脚本扩展并运行脚本 $scriptParams = @{ 'ResourceGroupName' = $rgName 'VMName' = $VMName 'Name' = 'Enable-PSRemoting.ps1' 'Location' = $vm.Location 'StorageAccountName' = $saName 'StorageAccountKey' = $key 'FileName' = 'Enable-PSRemoting.ps1' 'ContainerName' = $scName 'Run' = 'Enable-PSRemoting.ps1' } Set-AzureRmVMCustomScriptExtension @scriptParams

Summary

一旦此脚本完成,您可以验证 Enable-PSRemoting.ps1 已在虚拟机上执行,并且已成功启用了 PowerShell 远程管理。现在,您应该能够使用 Invoke-Command 对您的 Azure VM 进行操作。

通过在 Windows 中利用 Azure 自定义脚本扩展,您现在可以远程在 Azure VM 上运行任何类型的 PowerShell 脚本。

Source:
https://adamtheautomator.com/azure-run-script-on-vm/