Search code examples
azureterraform-provider-azureazure-openai

Using Azure openAI key rotation automation


We are planning to do the Azure OpenAI key rotation automatically. How can we achieve this? Do we have terraform resource for this.

resource "azurerm_cognitive_account" "example" {
  name                = "xxxxx"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  kind                = "OpenAI"

  sku_name = "S0"
}

Solution

  • Firstly, there is no direct resource present for the Open AI key rotation in terraform. Following a workaround on the requirement, I found below approach to make it work.

    As I mentioned in the comments, use azurerm_cognitive_account resource from terraform by providing kind as an "OpenAI" as shown.

    I tried creating a new open AI account with the below code and the deployment was successful.

    provider  "azurerm"{
      features{}
    }
    data  "azurerm_resource_group"  "example"  {
        name = "DefaultResourceGroup-EUS"
    }
    resource  "azurerm_cognitive_account"  "example"  {
        name = "examplesample"
        location = data.azurerm_resource_group.example.location
        resource_group_name = data.azurerm_resource_group.example.name
        kind = "OpenAI"
    sku_name = "S0"
    }
    }
    

    enter image description here

    Once it is done, you need to retrieve the keys from the external path. To do that, use data "external" block.

    How to use it: Reference

    Sample data block shown below:

    data "external" "keys" {
      program = ["sh", "/path/retrieve_sshkey.sh"]
    }
    

    Now refer this in the main.tf terraform resource with null_resource block by passing the open ai resource id under triggers block and add a provisioner as well.

    resource "null_resource" "samplerotation" {
      triggers = {
        open_ai_resource_id = azurerm_cognitive_account.example.id
        }
    provisioner "remote-exec" {
     //write a powershell script here and refer the above keys data block here
     }
    }
    

    Alternatively, you can also follow an other approach with the help of key vault. Store all the keys in the key vault and apply the key rotation from there itself.

    To do so, refer the terraform code from SO & for CLI approach refer Github doc.