如何检查密钥库中是否已存在某个证书?

时间:2020-05-26 16:57:30

标签: azure azure-pipelines azure-powershell azure-keyvault azure-cli

在每晚的Azure管道构建中,我有2个任务:

  • 首先,我从密钥库中删除并清除自签名证书
  • 然后我将相同的自签名证书导入密钥库

我这样做的原因是确保密钥库中始终有一定的证书

这是我当前的代码:

# purge the self-signed cert from the Keyvault to avoid conflict; ignore failures
- task: AzureCLI@2
  inputs:
    azureSubscription: '${{ parameters.ArmConnection }}'
    scriptType: 'pscore'
    scriptLocation: 'inlineScript'
    continueOnError: true
    failOnStandardError: false
    powerShellErrorActionPreference: 'silentlyContinue'
    inlineScript: |
      az keyvault certificate delete --vault-name $(KeyVaultName) --id 'https://$(KeyVaultName).vault.azure.net/certificates/my-self-signed-cert'
      az keyvault certificate purge --vault-name $(KeyVaultName) --id 'https://$(KeyVaultName).vault.azure.net/deletedcertificates/my-self-signed-cert'

# import the self-signed certificate my-self-signed-cert into the Keyvault
- task: AzurePowerShell@5
  inputs:
    azureSubscription: '${{ parameters.ArmConnection }}'
    ScriptType: 'InlineScript'
    azurePowerShellVersion: '3.1.0'
    Inline: |
      $Pwd = ConvertTo-SecureString -String 'MyPassword' -Force -AsPlainText
      $Base64 = 'MIIKqQ____3000_CHARS_HERE______1ICAgfQ=='
      Import-AzKeyVaultCertificate -VaultName $(KeyVaultName) -Name my-self-signed-cert -CertificateString $Base64 -Password $Pwd

我的问题是:

我如何检查证书库中的证书是否已经可用?

(因为我使用ARM模板,并且在每天晚上运行管道时,资源会继续运行并且不会被删除)。

如果有证书,该如何跳过以上两个任务(Azure-cli和PowerShell)?

我不太了解如何在管道YAML文件中使用条件。

1 个答案:

答案 0 :(得分:1)

YAML不能包含条件,因此您需要做的是处理Powershell脚本中的逻辑。

有一个命令可以检查给定证书是否存在于保管库中,那么怎么做呢?

        $cert = Get-AzureKeyVaultCertificate -VaultName "ContosoKV01" -Name "TestCert01"

        if(!$cert) {
          $Pwd = ConvertTo-SecureString -String 'MyPassword' -Force -AsPlainText
          $Base64 = 'MIIKqQ____3000_CHARS_HERE______1ICAgfQ=='
          Import-AzKeyVaultCertificate -VaultName $(KeyVaultName) -Name my-self-signed-cert -CertificateString $Base64 -Password $Pwd
        }

如果由于某种原因您还想要删除和清除证书,则也可以在PowerShell中进行。不确定为什么在当前设置中同时使用CLI和纯PowerShell?