DEV Community

Frederick Ollinger
Frederick Ollinger

Posted on

Terraform Write SSH to to Azure Key Vault for an Azure VM

Shows Terraform code which will write an auto-generated SSH key to Azure Key Vault so that you can programmatically get the key later on.

Normally, when Terraform creates a key, it will just save it on the local disk. But this means the key won't be available unless you have access to your private disk.

When doing a deployment in Gitlab CI/CD, for example, you will lose the key when the pipeline ends.

This code assumes that you have previously made an Azure Key Vault (https://azure.microsoft.com/en-us/services/key-vault/), and you have given your service principle for the current Terraform code to the Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/general/rbac-guide?tabs=azure-cli).

1st make an SSH key pair in Terraform:

resource "tls_private_key" "this" {
  algorithm = "RSA"
  rsa_bits  = 4096
}
Enter fullscreen mode Exit fullscreen mode

Next upload to Azure Key Vault.

data "azurerm_client_config" "current" {}
data "azurerm_key_vault" "kv1" {
  name                        = var.kv_name
  resource_group_name         = var.resource_group_name
  depends_on = [local_file.key_pem]
}

resource "azurerm_key_vault_secret" "privatekey" {
  name         = "private-key"
  value        = tls_private_key.this.private_key_pem
  key_vault_id = data.azurerm_key_vault.kv1.id
}
Enter fullscreen mode Exit fullscreen mode

In this example, we need a few variables to be set:

  1. kv_name = Azure Key Vault Name

  2. resource_group_name = The Azure Resource Group the Azure Key Vault belongs to.

When you are done, you will find your private SSH key in the key vault. Adding the public key is an exercise to the reader.

Top comments (0)