你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

在 Azure Functions 和应用服务混合连接中使用 PowerShell 管理混合环境

可以通过 Azure 应用服务混合连接功能访问其他网络中的资源。 若要详细了解此功能,可参阅混合连接文档。 本文介绍如何使用此功能运行以本地服务器为目标的 PowerShell 函数, 然后使用该服务器通过 Azure PowerShell 函数管理本地环境中的所有资源。

配置适用于 PowerShell 远程处理的本地服务器

以下脚本启用 PowerShell 远程处理,并创建新的防火墙规则和 WinRM Https 侦听器。 出于测试目的,我们使用自签名的证书。 在生产环境中,建议使用签名证书。

# For configuration of WinRM, see
# https://learn.microsoft.com/windows/win32/winrm/installation-and-configuration-for-windows-remote-management.

# Enable PowerShell remoting.
Enable-PSRemoting -Force

# Create firewall rule for WinRM. The default HTTPS port is 5986.
New-NetFirewallRule -Name "WinRM HTTPS" `
                    -DisplayName "WinRM HTTPS" `
                    -Enabled True `
                    -Profile "Any" `
                    -Action "Allow" `
                    -Direction "Inbound" `
                    -LocalPort 5986 `
                    -Protocol "TCP"

# Create new self-signed-certificate to be used by WinRM.
$Thumbprint = (New-SelfSignedCertificate -DnsName $env:COMPUTERNAME  -CertStoreLocation Cert:\LocalMachine\My).Thumbprint

# Create WinRM HTTPS listener.
$Cmd = "winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname=""$env:COMPUTERNAME ""; CertificateThumbprint=""$Thumbprint""}"
cmd.exe /C $Cmd

在门户中创建 PowerShell 函数应用

应用服务混合连接功能只能在“基本”、“标准”和“隔离”定价计划中使用。 使用 PowerShell 创建函数应用时,请创建或选择上述计划中的一项。

  1. 在 Azure 门户菜单上或在门户主页中,选择“创建资源”。

  2. “新建” 页面,选择 “计算”>“函数应用”

  3. 在“基本信息”页上,使用下表中指定的函数应用设置。

    设置 建议值 描述
    订阅 你的订阅 要在其下创建此新函数应用的订阅。
    资源组 myResourceGroup 要在其中创建 Function App 的新资源组的名称。
    函数应用名称 全局唯一名称 用于标识新 Function App 的名称。 有效字符为 a-z(不区分大小写)、0-9-
    发布 代码 用于发布代码文件或 Docker 容器的选项。
    运行时堆栈 首选语言 选择 PowerShell Core。
    版本 版本号 选择已安装的运行时的版本。
    区域 首选区域 选择离你近或离函数访问的其他服务近的区域

    Create a function app - Basics.

  4. 选择“下一步: 托管”。 在“托管”页上,输入以下设置。

    设置 建议值 说明
    存储帐户 全局唯一名称 创建函数应用使用的存储帐户。 存储帐户名称必须为 3 到 24 个字符,并且只能包含数字和小写字母。 也可使用现有帐户,但该帐户必须符合存储帐户要求
    操作系统 首选操作系统 系统会根据你的运行时堆栈选择为你预先选择一个操作系统,但你可以根据需要更改该设置。
    计划类型 应用服务计划 选择“应用服务计划”。 按应用服务计划运行时,必须管理函数应用的缩放

    Create a function app - Hosting.

  5. 选择“下一步: 监视”。 在“监视”页上,输入以下设置。

    设置 建议值 说明
    Application Insights 默认 在最近的受支持的区域中,创建一个具有相同应用名称的 Application Insights 资源。 通过展开此设置或选择“新建”,可以更改 Application Insights 名称或在 Azure 地理位置中选择要存储数据的其他区域。

    Create a function app - Monitoring.

  6. 选择“查看 + 创建”,以便查看应用配置选择。

  7. 在“查看 + 创建”页上查看设置,然后选择“创建”来预配并部署函数应用 。

  8. 选择门户右上角的“通知”图标,留意是否显示了“部署成功”消息。

  9. 选择“转到资源”,查看新的函数应用。 还可选择“固定到仪表板”。 固定可以更轻松地从仪表板返回此函数应用资源。

为函数应用创建混合连接

混合连接在函数应用的网络部分配置:

  1. 在刚刚创建的函数应用的“设置”下,选择“网络” 。

  2. 选择“配置混合连接终结点”。

    Configure the hybrid connection endpoints.

  3. 选择“添加混合连接”。

    Add a hybrid connection.

  4. 输入混合连接的相关信息,如以下屏幕截图后面的内容所示。 对于终结点主机,请使用创建了自签名证书的本地服务器的主机名。 当本地服务器的证书名称和主机名不匹配时,会出现连接问题。 端口与此前在服务器上定义的默认 Windows 远程管理服务端口匹配。

    Add hybrid connection.

    设置 建议的值
    混合连接名称 ContosoHybridOnPremisesServer
    终结点主机 finance1
    终结点端口 5986
    服务总线命名空间 新建
    位置 选取可用位置
    名称 contosopowershellhybrid
  5. 选择“确定”,创建此混合连接。

下载并安装安装混合连接

  1. 选择“下载连接管理器”,将“.msi”文件保存到计算机本地。

    Download the installer.

  2. 将 .msi 文件从本地计算机复制到本地服务器。

  3. 运行混合连接管理器安装程序,在本地服务器上安装此服务。

    Install the hybrid connection.

  4. 在门户中打开混合连接,然后将网关连接字符串复制到剪贴板。

    Copy the hybrid connection string.

  5. 在本地服务器上打开“混合连接管理器 UI”。

    Open the Hybrid Connection UI.

  6. 选择“手动输入”,从剪贴板粘贴连接字符串。

    Paste the hybrid connection.

  7. 在 PowerShell 中重启混合连接管理器(如果它没有显示为已连接)。

    Restart-Service HybridConnectionManager
    

针对管理员帐户的密码创建应用设置

  1. 在函数应用的“设置”下,选择“配置” 。

  2. 选择“+ 新建应用程序设置”。

    Configure a password for the administrator account.

  3. 将设置命名为 ContosoUserPassword,然后输入密码。 选择“确定” 。

  4. 选择“保存”,将密码存储在函数应用程序中。

    Save the password for the administrator account.

创建函数 HTTP 触发器

  1. 在函数应用中,选择“函数”,然后选择“+ 添加” 。

    Create new HTTP trigger.

  2. 选择“HTTP 触发器”模板。

    Select the HTTP trigger template.

  3. 命名新函数并选择“创建函数”。

    Name and create the new HTTP trigger function.

测试函数

  1. 在新函数中,选择“代码 + 测试”。 将模板中的 PowerShell 代码替换为以下代码:

    # Input bindings are passed in via param block.
    param($Request, $TriggerMetadata)
    
    # Write to the Azure Functions log stream.
    Write-Output "PowerShell HTTP trigger function processed a request."
    
    # Note that ContosoUserPassword is a function app setting, so I can access it as $env:ContosoUserPassword.
    $UserName = "ContosoUser"
    $securedPassword = ConvertTo-SecureString  $Env:ContosoUserPassword -AsPlainText -Force
    $Credential = [System.management.automation.pscredential]::new($UserName, $SecuredPassword)
    
    # This is the name of the hybrid connection Endpoint.
    $HybridEndpoint = "finance1"
    
    $Script = {
        Param(
            [Parameter(Mandatory=$True)]
            [String] $Service
        )
        Get-Service $Service
    }
    
    Write-Output "Scenario 1: Running command via Invoke-Command"
    Invoke-Command -ComputerName $HybridEndpoint `
                   -Credential $Credential `
                   -Port 5986 `
                   -UseSSL `
                   -ScriptBlock $Script `
                   -ArgumentList "*" `
                   -SessionOption (New-PSSessionOption -SkipCACheck)
    
  2. 选择“保存”。

    Change the PowerShell code and save the HTTP trigger function.

  3. 选择“测试”,然后选择“运行”来测试函数 。 检查日志以验证测试是否成功。

    Test HTTP trigger function.

在本地管理其他系统

可以使用连接的本地服务器连接到本地环境中的其他服务器和管理系统。 这样即可使用 PowerShell 函数在 Azure 中管理数据中心操作。 以下脚本注册一个 PowerShell 配置会话,该会话使用提供的凭据运行。 这些凭据必须是远程服务器上的管理员的。 然后,可以使用此配置访问本地服务器或数据中心中的其他终结点。

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Note that ContosoUserPassword is a function app setting, so I can access it as $env:ContosoUserPassword.
$UserName = "ContosoUser"
$SecuredPassword = ConvertTo-SecureString  $Env:ContosoUserPassword -AsPlainText -Force
$Credential = [System.management.automation.pscredential]::new($UserName, $SecuredPassword)

# This is the name of the hybrid connection Endpoint.
$HybridEndpoint = "finance1"

# The remote server that will be connected to run remote PowerShell commands on
$RemoteServer = "finance2".

Write-Output "Use hybrid connection server as a jump box to connect to a remote machine"

# We are registering an endpoint that runs under credentials ($Credential) that has access to the remote server.
$SessionName = "HybridSession"
$ScriptCommand = {
    param (
        [Parameter(Mandatory=$True)]
        $SessionName)

    if (-not (Get-PSSessionConfiguration -Name $SessionName -ErrorAction SilentlyContinue))
    {
        Register-PSSessionConfiguration -Name $SessionName -RunAsCredential $Using:Credential
    }
}

Write-Output "Registering session on hybrid connection jumpbox"
Invoke-Command -ComputerName $HybridEndpoint `
               -Credential $Credential `
               -Port 5986 `
               -UseSSL `
               -ScriptBlock $ScriptCommand `
               -ArgumentList $SessionName `
               -SessionOption (New-PSSessionOption -SkipCACheck)

# Script to run on the jump box to run against the second machine.
$RemoteScriptCommand = {
    param (
        [Parameter(Mandatory=$True)]
        $ComputerName)
        # Write out the hostname of the hybrid connection server.
        hostname
        # Write out the hostname of the remote server.
        Invoke-Command -ComputerName $ComputerName -Credential $Using:Credential -ScriptBlock {hostname} `
                        -UseSSL -Port 5986 -SessionOption (New-PSSessionOption -SkipCACheck)
}

Write-Output "Running command against remote machine via jumpbox by connecting to the PowerShell configuration session"
Invoke-Command -ComputerName $HybridEndpoint `
               -Credential $Credential `
               -Port 5986 `
               -UseSSL `
               -ScriptBlock $RemoteScriptCommand `
               -ArgumentList $RemoteServer `
               -SessionOption (New-PSSessionOption -SkipCACheck) `
               -ConfigurationName $SessionName

请将该脚本中的以下变量替换为你环境中的相应值:

  • $HybridEndpoint
  • $RemoteServer

在上面的两个方案中,可以在 Azure Functions 和混合连接中使用 PowerShell 连接和管理本地环境。 建议你深入了解混合连接函数中的 PowerShell

还可以通过 Azure Functions 使用 Azure 虚拟网络连接到本地环境。

后续步骤