使用 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 安全地存储密钥。With a few steps, we can implement secure key storage for Batch.

若要从 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 we created previous step.

有关 Azure 服务主体的详细信息,请参阅 Azure Active Directory 中的应用程序和服务主体对象For more information on Azure service principals, see Application and service principal objects in Azure Active Directory.

备注

服务主体必须与 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, we need to assign the certificate to the Batch account. 将证书分配到帐户之后,我们就可以将其分配到池,然后分配到节点。Assigning the certificate to the account allows us to 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 we generated in the Obtain a certificate 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 do 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 命令下载该库。There are a few ways to do this, if your nodes have Windows Management Framework (WMF) 5 installed, then 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, 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 we're all setup to access Key Vault in scripts running on 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 -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.