Export Certificates between Azure KeyVault Instances

So, this should be a quick one. I had a problem recently, I was trying to export certificates from my old Azure Keyvault instance to a new one and i didn't want to download them each and import to the new Azure Keyvault instance.

I picked Terraform to do this as that is what i use to setup the infrastructure already. so here I will assume you have some experience with terraform already and jump right into it.

Now you would expect that the terraform data source azurerm_key_vault_certificate would be the resource to read the certificate data and create a new certificate resource. However, this data source only fetches the certificate public data and you cannot create a certificate resource with this data. Also, the terraform data source azurerm_key_vault_certificate_data provides the certificate data in pem format and the private key. I have had issues with certificates imported in pem format and application_gateway certificates.


Apparently the certificate data can be accessed from the terraform data source azurerm_key_vault_secret and that solved my problem. here is the final script i used.

terraform {
  required_version = ">= 0.13"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.17.0"

provider "azurerm" {
  features {}

locals {
  certificates = [

data "azurerm_key_vault" "old" {
  name                = "old_keyvault_name"
  resource_group_name = "old_keyvault_resource_group"

data "azurerm_key_vault" "new" {
  name                = "new_keyvault_name"
  resource_group_name = "new_keyvault_resource_group"

data "azurerm_key_vault_secret" "secrets" {
  for_each     = toset(local.certificates)
  name         = each.value
  key_vault_id = data.azurerm_key_vault.old.id

resource "azurerm_key_vault_certificate" "secrets" {
  for_each     = data.azurerm_key_vault_secret.secrets
  name         = each.value.name
  key_vault_id = data.azurerm_key_vault.new.id

  certificate {
    contents = each.value.value