Edit

Quickstart: Perform Azure resource actions with the AzAPI Terraform provider

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.

Use azapi_resource_action as a managed Terraform resource to perform imperative, state-changing operations on Azure resources. In this example, you create an Azure storage account and then rotate its access keys.

azapi_resource_action has two usage forms:

  • Resource: Performs a state-changing operation during terraform apply. Terraform tracks the action in state and can optionally reverse it on terraform destroy.
  • Data source: Performs a read-only operation during planning. See the resource action data source quickstart for that scenario.

Use the resource form when you need Terraform to perform an Azure operation that isn't based on a standard create/read/update/delete lifecycle—for example, rotating credentials, starting or stopping a VM, or triggering a failover.

  • Create a storage account with the AzureRM provider
  • Rotate the storage account access key with azapi_resource_action

Prerequisites

  • Azure subscription: If you don't have an Azure subscription, create a free account before you begin.

When you log in to the Azure portal with a Microsoft account, the default Azure subscription for that account is used.

Terraform automatically authenticates using information from the default Azure subscription.

Run az account show to verify the current Microsoft account and Azure subscription.

az account show

Any changes you make via Terraform are on the displayed Azure subscription. If that's what you want, skip the rest of this article.

Implement the Terraform code

  1. Create a directory in which to test the sample Terraform code and make it the current directory.

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

    terraform {
      required_providers {
        azapi = {
          source  = "Azure/azapi"
          version = "~> 2.0"
        }
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~> 3.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
    provider "azapi" {}
    
  3. Create a file named variables.tf and insert the following code:

    variable "resource_group_location" {
      type        = string
      default     = "eastus"
      description = "Location of the resource group."
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random value to create a unique name."
    }
    
    variable "storage_account_name_prefix" {
      type        = string
      default     = "st"
      description = "Prefix of the storage account name that's combined with a random value to create a unique name."
    }
    
  4. Create a file named main.tf and insert the following code:

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "random_string" "storage_suffix" {
      length  = 8
      upper   = false
      special = false
    }
    
    resource "azurerm_resource_group" "example" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    resource "azurerm_storage_account" "example" {
      name                     = "${var.storage_account_name_prefix}${random_string.storage_suffix.result}"
      resource_group_name      = azurerm_resource_group.example.name
      location                 = azurerm_resource_group.example.location
      account_tier             = "Standard"
      account_replication_type = "LRS"
    }
    
    resource "azapi_resource_action" "regenerate_key" {
      type        = "Microsoft.Storage/storageAccounts@2023-01-01"
      resource_id = azurerm_storage_account.example.id
      action      = "regenerateKey"
      method      = "POST"
    
      body = {
        keyName = "key1"
      }
    }
    

    Key points about using azapi_resource_action as a resource:

    • The action field specifies the ARM operation to perform. For storage account key rotation, use regenerateKey.
    • The method field specifies the HTTP method. Most imperative actions use POST.
    • The body attribute passes data to the action. For key regeneration, specify which key (key1 or key2) to rotate.
    • The action is performed during terraform apply and tracked in Terraform state.
  5. Create a file named outputs.tf and insert the following code:

    output "resource_group_name" {
      value = azurerm_resource_group.example.name
    }
    
    output "storage_account_name" {
      value = azurerm_storage_account.example.name
    }
    

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.

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.

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 the results

After terraform apply completes, the storage account key has been rotated. You can verify the key rotation by checking the storage account keys in Azure.

Run az storage account keys list to view the storage account keys.

```azurecli
az storage account keys list \
  --resource-group <resource_group_name> \
  --account-name <storage_account_name>
```

The `value` field shows the current key.

Examples of other resource actions

The azapi_resource_action resource works with many Azure operations. Here are common examples:

  • Virtual Machines: deallocate, start, restart, powerOff, reimage
  • Key Vaults: purge (for soft-deleted vaults), rotate (for managed keys)
  • App Services: swap (for deployment slots), restart
  • Databases: failover, promote
  • Compute resources: Any operation exposed by the Azure REST API that modifies state without creating or destroying a resource

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