0
votes

In Azure API Management, there's an option to add a certificate from the portal by referencing a certificate in keyvault:

Azure APIM adding certificate from keyvault screenshot

Is it possible to do this using az cli, powershell or terraform?

I have looked through the documentation and the only examples I have found (including Terraform) seem to involve uploading an copy of the certificates bytes, rather than referencing it. I'd like to be able to reference it so that APIM will do the automatic reloading when the certificate changes.

2

2 Answers

1
votes

You could invoke API Management REST API directly from Azure CLI with:

az rest --method put --url "https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/certificates/{certificateId}?api-version=2020-06-01-preview" --body @body.json

where this describes the URI parameters and the file body.json would reflect the request body defined here:

{
  "properties": {
    "keyVault": {
      "identityClientId": "{SystemAssignedIdentity or UserAssignedIdentity Client Id which will be used to access key vault secret.}",
      "secretIdentifier" : "{Key vault secret identifier for fetching secret. Providing a versioned secret will prevent auto-refresh. This requires Api Management service to be configured with aka.ms/apimmsi}"
    }
  }
}
0
votes

I have gone through the official Azure CLI and Azure PowerShell APIM reference and as you said, they not provide a way to set a certificate reference from keyVault. But I think we can export .pfx from keyVault and import it to APIM as a workaround. Just Try the PS command :

$apimName = ""
$apimSresourceGroup = ""
$keyVaultName = "" 
$certName = ""
$password = ""

#export pfx
$cert = Get-AzKeyVaultCertificate -VaultName $keyVaultName -Name $certName
$secret = Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $cert.Name 
$secretByte = [Convert]::FromBase64String($secret.SecretValueText)
$x509Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($secretByte, "", "Exportable,PersistKeySet")
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx
$pfxFileByte = $x509Cert.Export($type, $password)

#import to APIM 
$apim_context = New-AzApiManagementContext -ResourceGroupName $apimSresourceGroup -ServiceName $apimName
New-AzApiManagementCertificate -Context $apim_context -CertificateId 'testcert' -PfxBytes $pfxFileByte -PfxPassword $password 

Result: enter image description here enter image description here