Edit

Share via


Use Terraform to manage Microsoft Foundry resources

Use Terraform to automate the creation of Microsoft Foundry resources, projects, deployments, and connections.

If you already configured a Foundry resource in the Azure portal, you can export that configuration as Terraform code instead of authoring a configuration from scratch.

You can use either the Terraform AzAPI Provider or AzureRM Provider to manage Foundry resources. The AzAPI provider lets you access all Foundry control plane configurations including preview features. The AzureRM variant is limited to core management capabilities.

Terraform state files can include sensitive values. Use a secure backend and access controls for team scenarios.

Tip

For production-ready Terraform configurations that cover common Foundry deployment scenarios, see the infrastructure-setup-terraform folder in the Foundry samples repository. Clone the repository and customize the configurations instead of starting from scratch.

Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax. The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

Provider capabilities

The following table shows which actions each provider supports:

Action AzAPI Provider AzureRM Provider
Create a resource group
Create a Foundry resource
Configure deployments
Configure projects
Configure a connection to knowledge and tools -
Configure a capability host (for advanced tool configurations like Agent standard setup) -

Prerequisites

An Azure account with an active subscription. If you don't have one, create a free Azure account, which includes a free trial subscription.

Create a basic Foundry configuration

  1. Create a directory to test and run the sample Terraform code. Make this directory your current directory.

  2. Create a file named providers.tf and add the following code.

    # Setup providers
    provider "azapi" {
      subscription_id = var.subscription_id
    }
    
  3. Create a file named main.tf and add the following code.

    ## Create a random string
    ## 
    resource "random_string" "unique" {
      length      = 5
      min_numeric = 5
      numeric     = true
      special     = false
      lower       = true
      upper       = false
    }
    
    ## Create a resource group for the resources to be stored in
    ##
    resource "azapi_resource" "rg" {
      type      = "Microsoft.Resources/resourceGroups@2021-04-01"
      name      = "tf-319-basic"
      location  = var.location
    }
    
    ########## Create AI Foundry resource
    ##########
    
    ## Create the AI Foundry resource
    ##
    resource "azapi_resource" "ai_foundry" {
      type                      = "Microsoft.CognitiveServices/accounts@2025-06-01"
      name                      = "aifoundry${random_string.unique.result}"
      parent_id                 = azapi_resource.rg.id
      location                  = var.location
      schema_validation_enabled = false
    
      body = {
        kind = "AIServices"
        sku = {
          name = "S0"
        }
        identity = {
          type = "SystemAssigned"
        }
    
        properties = {
          # Support both Entra ID and API Key authentication for Cognitive Services account
          disableLocalAuth = false
    
          # Specifies that this is an AI Foundry resourceyes
          allowProjectManagement = true
    
          # Set custom subdomain name for DNS names created for this Foundry resource
          customSubDomainName = "aifoundry${random_string.unique.result}"
        }
      }
    }
    
    ## Create a deployment for OpenAI's GPT-4o in the AI Foundry resource
    ##
    resource "azapi_resource" "aifoundry_deployment_gpt_4o" {
      type      = "Microsoft.CognitiveServices/accounts/deployments@2023-05-01"
      name      = "gpt-4o"
      parent_id = azapi_resource.ai_foundry.id
      depends_on = [
        azapi_resource.ai_foundry
      ]
    
      body = {
        sku = {
          name     = "Standard"
          capacity = 1
        }
        properties = {
          model = {
            format  = "OpenAI"
            name    = "gpt-4o"
            version = "2024-11-20"
          }
        }
      }
    }
    
    ## Create AI Foundry project
    ##
    resource "azapi_resource" "ai_foundry_project" {
      type                      = "Microsoft.CognitiveServices/accounts/projects@2025-06-01"
      name                      = "project${random_string.unique.result}"
      parent_id                 = azapi_resource.ai_foundry.id
      location                  = var.location
      schema_validation_enabled = false
    
      body = {
        sku = {
          name = "S0"
        }
        identity = {
          type = "SystemAssigned"
        }
    
        properties = {
          displayName = "project"
          description = "My first project"
        }
      }
    }
    
  4. Create a file named variables.tf and add the following code.

    variable "location" {
      description = "The name of the location to provision the resources to"
      type        = string
    }
    
    variable "subscription_id" {
      type = string
    }
    

References:

Initialize Terraform

Run terraform init to initialize the Terraform deployment. This command downloads the Azure provider required to manage your Azure resources.

terraform init -upgrade

Key points:

  • The -upgrade parameter upgrades the necessary provider plugins to the newest version that complies with the configuration's version constraints.

Create a Terraform execution plan

Run terraform plan to create an execution plan.

terraform plan -out main.tfplan

Key points:

  • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
  • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.

Apply a Terraform execution plan

Run terraform apply to apply the execution plan to your cloud infrastructure.

terraform apply main.tfplan

Key points:

  • The example terraform apply command assumes you previously ran terraform plan -out main.tfplan.
  • If you specified a different filename for the -out parameter, use that same filename in the call to terraform apply.
  • If you didn't use the -out parameter, call terraform apply without any parameters.

Verify your deployment

Run the following commands to verify deployed resources:

terraform state list
terraform output

Export an existing resource to Terraform

If you already configured a Foundry resource in the Azure portal, you can export that configuration as Terraform code. The export captures your current resource settings, including network rules, identity configuration, and project associations. Use the exported code as a starting point for managing the resource with Terraform.

  1. In the Azure portal, go to your Foundry resource.
  2. In the left menu under Automation, select Export template.
  3. Select the Terraform tab to view the generated Terraform code.
  4. Select Download to save the file locally, or Copy to copy the code to your clipboard.

Note

The export might complete with warnings if some resource types don't support full export. Review the output and fill in any missing properties manually.

Import the exported resource into Terraform state

To manage the exported resource with Terraform going forward, import it into your Terraform state. For the AzAPI provider:

terraform import azapi_resource.example <resource-id>

Replace <resource-id> with the full Azure resource ID shown in the exported file (for example, /subscriptions/.../providers/Microsoft.CognitiveServices/accounts/<name>).

Customize the exported configuration

The exported Terraform code contains hardcoded values specific to your subscription and resource group. Before you reuse the configuration:

  • Replace hardcoded subscription IDs, resource group names, and resource IDs with Terraform variables.
  • Remove any properties you don't need or that reference resources outside the deployment scope.
  • Add or adjust security configurations to match your organization's requirements.

For production-ready Terraform configurations with enterprise security built in, see the infrastructure-setup-terraform folder in the Foundry samples repository.

When you customize your configuration, consider adding the following security settings:

Customize security and compliance

To meet security and compliance requirements, customize Foundry with security configurations and by bringing your own storage resources. For example, when using the Agent service, you can opt to bring your own Azure Cosmos DB database, Azure AI Search instance, and Azure Storage Account to store your threads and messages.

For advanced setup samples, see the following repositories:

Clean up resources

When you no longer need the resources created via Terraform, do the following steps:

  1. Run terraform plan and specify the destroy flag.

    terraform plan -destroy -out main.destroy.tfplan
    

    Key points:

    • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
    • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.
  2. Run terraform apply to apply the execution plan.

    terraform apply main.destroy.tfplan
    

Troubleshoot Terraform on Azure

Troubleshoot common problems when using Terraform on Azure.

Next steps