使用 Batch 安全地访问 Key VaultSecurely access Key Vault with Batch

本文介绍如何设置 Batch 节点,以便安全地访问 Azure Key Vault 中存储的凭据。In this article, you'll learn how to set up Batch nodes to securely access credentials stored in Azure Key Vault. 无需将管理员凭据放入 Key Vault,然后对凭据进行硬编码以从脚本访问 Key Vault。There's no point in putting your admin credentials in Key Vault, then hard-coding credentials to access Key Vault from a script. 解决方案是使用授予 Batch 节点对 Key Vault 的访问权限的证书。The solution is to use a certificate that grants your Batch nodes access to Key Vault.

若要从 Batch 节点向 Azure Key Vault 进行身份验证,需要:To authenticate to Azure Key Vault from a Batch node, you need:

  • 一个 Azure Active Directory (Azure AD) 凭据An Azure Active Directory (Azure AD) credential
  • 一个证书A certificate
  • 一个 Batch 帐户A Batch account
  • 具有至少一个节点的 Batch 池A Batch pool with at least one node

获得证书Obtain a certificate

如果还没有证书,获取证书最简单的方法是使用 makecert 命令行工具生成自签名证书。If you don't already have a certificate, the easiest way to get one is to generate a self-signed certificate using the makecert command-line tool.

通常可以在以下路径中找到 makecertC:\Program Files (x86)\Windows Kits\10\bin\<arch>You can typically find makecert in this path: C:\Program Files (x86)\Windows Kits\10\bin\<arch>. 以管理员身份打开命令提示符,并使用以下示例导航到 makecertOpen a command prompt as an administrator and navigate to makecert using the following example.

cd C:\Program Files (x86)\Windows Kits\10\bin\x64

接下来,使用 makecert 工具创建名为 batchcertificate.cerbatchcertificate.pvk 的自签名证书文件。Next, use the makecert tool to create self-signed certificate files called batchcertificate.cer and batchcertificate.pvk. 使用的公用名称 (CN) 对此应用程序并不重要,但将其设置为告诉你证书的用途是非常有帮助的。The common name (CN) used isn't important for this application, but it's helpful to make it something that tells you what the certificate is used for.

makecert -sv batchcertificate.pvk -n "cn=batch.cert.mydomain.org" batchcertificate.cer -b 09/23/2019 -e 09/23/2019 -r -pe -a sha256 -len 2048

Batch 需要 .pfx 文件。Batch requires a .pfx file. 使用 pvk2pfx 工具将 makecert 创建的 .cer.pvk 文件转换为单个 .pfx 文件。Use the pvk2pfx tool to convert the .cer and .pvk files created by makecert to a single .pfx file.

pvk2pfx -pvk batchcertificate.pvk -spc batchcertificate.cer -pfx batchcertificate.pfx -po

创建服务主体Create a service principal

将对 Key Vault 的访问权限授予用户或服务主体。 Access to Key Vault is granted to either a user or a service principal. 若要以编程方式访问 Key Vault,请将服务主体与上一步中创建的证书一起使用。To access Key Vault programmatically, use a service principal with the certificate you created in the previous step. 服务主体必须与 Key Vault 位于同一 Azure AD 租户中。The service principal must be in the same Azure AD tenant as the Key Vault.

$now = [System.DateTime]::Parse("2020-02-10")
# Set this to the expiration date of the certificate
$expirationDate = [System.DateTime]::Parse("2021-02-10")
# Point the script at the cer file you created $cerCertificateFilePath = 'c:\temp\batchcertificate.cer'
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cer.Import($cerCertificateFilePath)
# Load the certificate into memory
$credValue = [System.Convert]::ToBase64String($cer.GetRawCertData())
# Create a new AAD application that uses this certificate
$newADApplication = New-AzureRmADApplication -DisplayName "Batch Key Vault Access" -HomePage "https://batch.mydomain.com" -IdentifierUris "https://batch.mydomain.com" -certValue $credValue -StartDate $now -EndDate $expirationDate
# Create new AAD service principal that uses this application
$newAzureAdPrincipal = New-AzureRmADServicePrincipal -ApplicationId $newADApplication.ApplicationId

应用程序的 URL 并不重要,因为我们只是将其用于访问 Key Vault。The URLs for the application aren't important, since we're only using them for Key Vault access.

授予 Key Vault 的权限Grant rights to Key Vault

在上一步中创建的服务主体需要权限才能从 Key Vault 检索机密。The service principal created in the previous step needs permission to retrieve the secrets from Key Vault. 可以通过 Azure 门户或以下 PowerShell 命令授予权限。Permission can be granted either through the Azure portal or with the PowerShell command below.

Set-AzureRmKeyVaultAccessPolicy -VaultName 'BatchVault' -ServicePrincipalName '"https://batch.mydomain.com' -PermissionsToSecrets 'Get'

将证书分配给 Batch 帐户Assign a certificate to a Batch account

创建 Batch 池,然后转到该池中的“证书”选项卡,并分配所创建的证书。Create a Batch pool, then go to the certificate tab in the pool and assign the certificate you created. 证书现在位于所有 Batch 节点上。The certificate is now on all Batch nodes.

接下来,将该证书分配到 Batch 帐户。Next, assign the certificate to the Batch account. 将证书分配到帐户之后,Batch 就可以将其分配到池,然后分配到节点。Assigning the certificate to the account lets Batch assign it to the pools and then to the nodes. 执行此操作最简单的方法是,转到门户中的 Batch 帐户,导航到“证书”,然后选择“添加”。 The easiest way to do this is to go to your Batch account in the portal, navigate to Certificates, and select Add. 上传先前生成的 .pfx 文件,并提供密码。Upload the .pfx file you generated earlier and supply the password. 完成后,相应的证书将添加到列表,你可以验证指纹。Once complete, the certificate is added to the list and you can verify the thumbprint.

现在,在创建 Batch 池时,可以导航到池中的“证书”,并将创建的证书分配到该池。Now when you create a Batch pool, you can navigate to Certificates within the pool and assign the certificate you created to that pool. 执行此操作时,请确保选择存储位置 LocalMachine。When you do so, ensure you select LocalMachine for the store location. 证书将加载到池中的所有 Batch 节点上。The certificate is loaded on all Batch nodes in the pool.

安装 Azure PowerShellInstall Azure PowerShell

如果计划在节点上使用 PowerShell 脚本访问 Key Vault,则需要安装 Azure PowerShell 库。If you plan on accessing Key Vault using PowerShell scripts on your nodes, then you need the Azure PowerShell library installed. 如果节点安装了 Windows Management Framework (WMF) 5,则可使用 install-module 命令下载该库。If your nodes have Windows Management Framework (WMF) 5 installed, you can use the install-module command to download it. 如果你使用的节点未安装 WMF 5,最简单的安装方法是将 Azure PowerShell .msi 文件与 Batch 文件捆绑在一起,然后在 Batch 启动脚本的第一部分中调用该安装程序。If you're using nodes that don't have WMF 5, the easiest way to install it is to bundle up the Azure PowerShell .msi file with your Batch files, and then call the installer as the first part of your Batch startup script. 有关详细信息,请参阅此示例:See this example for details:

$psModuleCheck=Get-Module -ListAvailable -Name Azure -Refresh
if($psModuleCheck.count -eq 0) {
    $psInstallerPath = Join-Path $downloadPath "azure-powershell.3.4.0.msi" Start-Process msiexec.exe -ArgumentList /i, $psInstallerPath, /quiet -wait
}

访问密钥保管库Access Key Vault

现在可以通过在 Batch 节点上运行的脚本访问 Key Vault 了。Now you're ready to access Key Vault in scripts running on your Batch nodes. 若要从脚本访问 Key Vault,你只需使用证书对脚本针对 Azure AD 进行身份验证。To access Key Vault from a script, all you need is for your script to authenticate against Azure AD using the certificate. 若要在 PowerShell 中执行此操作,请使用以下示例命令。To do this in PowerShell, use the following example commands. 为“指纹”、“应用 ID”(服务主体的 ID)和“租户 ID”(服务主体所在的租户)指定相应的 GUID。 Specify the appropriate GUID for Thumbprint, App ID (the ID of your service principal), and Tenant ID (the tenant where your service principal exists).

Add-AzureRmAccount -Environment AzureChinaCloud -ServicePrincipal -CertificateThumbprint -ApplicationId

经过身份验证后,可以像往常一样访问 KeyVault。Once authenticated, access KeyVault as you normally would.

$adminPassword=Get-AzureKeyVaultSecret -VaultName BatchVault -Name batchAdminPass

这些是要在脚本中使用的凭据。These are the credentials to use in your script.

后续步骤Next steps