问题描述

在Azure Function中创建一个PowerShell的函数后,其中使用了Get-AzMaintenanceUpdate,New-AzApplyUpdate 等指令,但是在执行时错误。错误截图:

【Azure Function】Function App和Powershell 集成问题, 如何安装PowerShell的依赖模块

 

问题分析及解决

第一步:分析错误日志

在错误截图中,可以清晰的发现问题【ERROR: The term 'Get-AzMaintenanceUpdate' is not recognized as the name of a cmdlet, function, script file, or operable program. 】这里正好说明了在Function App所运行的实例中,没有安装支持Get-AzMaintenanceUpdate命令的模块包。网上搜索发现,这个方法属于Az.Maintenance包。所以接下来就是需要在Azure Function App中安装Az包。

 

第二步:如何安装所需要的PowerShell依赖包

方式一:在“

依赖项管理

host.json 文件的根目录中,将 managedDependency 属性设置为 true,如以下示例所示:

{
  "managedDependency": {
          "enabled": true
       }
}

支持的语法为 MajorNumber .* 或确切的模块版本,如以下 requirements.psd1 示例所示:

@{
    Az = '1.*'
    SqlServer = '21.1.18147'
}

更新 requirements.psd1 文件时,会在重启后安装更新的模块。

修改成功后,在Kudu中所见的效果如下:

 

方式二:上传本地Az.Maintenance包文件到Function App 站点中,详细步骤为

  1. 在本地 PowerShell 安装Az.Maintenance这个moudle,安装好之后找到这个安装的文件夹
  2. 登录到kudu,在 CMD>site>wwwroot><your Function Name>这个目录下创建一个名为moudles 的文件夹, 把第一步中安装好的这个moudle里面的内容上传到这个文件夹下
  3. 找到执行文件,执行导入模块指令
Import-Module "D:\home\site\wwwroot\<your Function Name>\modules\Az.Maintenance.psd1"

 

附录一:Function App中所执行的PowerShell脚本

# Input bindings are passed in via param block.
param($Timer)

# Check if any maintenance updates are available for your dedicated host
$isMaintenance = Get-AzMaintenanceUpdate `
    -ResourceGroupName MaintenanceGroup `
    -ResourceName MaintenanceInstance `
    -ResourceType hosts `
    -ResourceParentName MaintenanceGroup `
    -ResourceParentType hostGroups `
    -ProviderName Microsoft.Compute

# if available, apply the update. Else, write that there are "no availabe updates" to the log
if ($isMaintenance -ne $null)
{
New-AzApplyUpdate `
    -ResourceGroupName MaintenanceGroup `
    -ResourceName MaintenanceInstance `
    -ResourceType hosts `
    -ResourceParentName MaintenanceGroup `
    -ResourceParentType hostGroups `
    -ProviderName Microsoft.Compute
}
else {
   Write-Output 'No Updates Available'

}

 

参考资料:

https://docs.microsoft.com/zh-cn/azure/azure-functions/functions-reference-powershell?tabs=portal#dependency-management

Get-AzMaintenanceUpdate: https://docs.microsoft.com/en-us/powershell/module/az.maintenance/get-azmaintenanceupdate?view=azps-5.9.0

 

分类:

技术点:

相关文章: