How to Create Azure Key Vault and Assign Key Vault Administrator Role Using Terraform

naveen0142
New Contributor

Hi all,

I’m currently working with Terraform to set up Azure resources, including OpenAI services, and I’d like to extend my configuration to create an Azure Key Vault. Specifically, I want to:

  1. Create an Azure Key Vault to store secrets/keys.
  2. Assign the Key Vault Administrator role to a specific user or service principal to manage the vault.

    Here's the existing Terraform configuration I have for the OpenAI service:

    terraform {
      required_version = ">= 1.0.0"
    
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = ">= 2.0.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
       # Authentication with Service Principal
      client_id       = var.client_id
      client_secret   = var.client_secret
      tenant_id       = var.tenant_id
      subscription_id = var.subscription_id
    }
    
    # Define the resource group
    resource "azurerm_resource_group" "example" {
      name     = var.resource_group_name
      location = var.location  # Update to a supported region
    }
    
    # Define the Cognitive Services account
    resource "azurerm_cognitive_account" "openai" {
      name                = var.cognitive_account_name
      resource_group_name = azurerm_resource_group.example.name
      location            = azurerm_resource_group.example.location
      kind                = "OpenAI"
      sku_name            = "S0"  # Ensure this attribute is specified
    
      identity {
        type = "SystemAssigned"
      }
    }
    
    # Define the Cognitive Services model deployment
    resource "azurerm_cognitive_deployment" "model" {
      name                  = var.model_name
      cognitive_account_id  = azurerm_cognitive_account.openai.id
    
      model {
        name   = var.model_name
        format = "OpenAI"
      }
    
      sku {
        name = "Standard"  # Ensure this is a supported SKU for the chosen region
      }
    }
    
    # Define the output blocks
    output "api_base" {
      value     = azurerm_cognitive_account.openai.endpoint
      sensitive = true
    }
    
    output "api_key" {
      value     = azurerm_cognitive_account.openai.primary_access_key
      sensitive = true
    }
    
    output "api_type" {
      value = "azure"
    }
    
    output "api_version" {
      value = "2024-08-01-preview"  # Use the latest version
    }
    
    output "engine" {
      value = azurerm_cognitive_deployment.model.name
    }
     

    What I want to add:

    1. Create a Key Vault.
    2. Add a Key Vault Administrator role assignment for a service principal or a user (please specify how to do this).
    3. Store keys/secrets in the Key Vault.

      Can someone provide an example or guide me on how to extend my Terraform configuration to include these steps?

      Thank you in advance for your help!