Quickstart: Deploy your first Azure resource_action resource 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.

In this article, you learn how to use the AzAPI Terraform provider to perform an imperative action on a resource. The azapi_resource_action will be used to list Azure Key Vault Keys.

  • Define and configure the AzureRM and AzAPI providers
  • Generate a random name for the Key Vault
  • Use the AzureRM provider to create an Azure Key Vault and Key Vault Key
  • Use the AzAPI provider to list Azure Key Vault Keys

Prerequisites

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

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"
        }
      }
    }
    
    provider "azapi" {}
    
    provider "azurerm" {
      features {}
    }
    
  3. Create a file named main.tf and insert the following code:

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      name     = random_pet.rg_name.id
      location = var.resource_group_location
    }
    
    data "azurerm_client_config" "current" {}
    
    resource "random_string" "azurerm_key_vault_name" {
      length  = 13
      lower   = true
      numeric = false
      special = false
      upper   = false
    }
    
    locals {
      current_user_id = coalesce(var.msi_id, data.azurerm_client_config.current.object_id)
    }
    
    resource "azurerm_key_vault" "vault" {
      name                       = coalesce(var.vault_name, "vault-${random_string.azurerm_key_vault_name.result}")
      location                   = azurerm_resource_group.rg.location
      resource_group_name        = azurerm_resource_group.rg.name
      tenant_id                  = data.azurerm_client_config.current.tenant_id
      sku_name                   = var.sku_name
      soft_delete_retention_days = 7
    
      access_policy {
        tenant_id = data.azurerm_client_config.current.tenant_id
        object_id = local.current_user_id
    
        key_permissions    = var.key_permissions
        secret_permissions = var.secret_permissions
      }
    }
    
    resource "random_string" "azurerm_key_vault_key_name" {
      length  = 13
      lower   = true
      numeric = false
      special = false
      upper   = false
    }
    
    resource "azurerm_key_vault_key" "key" {
      name = coalesce(var.key_name, "key-${random_string.azurerm_key_vault_key_name.result}")
    
      key_vault_id = azurerm_key_vault.vault.id
      key_type     = var.key_type
      key_size     = var.key_size
      key_opts     = var.key_ops
    
      rotation_policy {
        automatic {
          time_before_expiry = "P30D"
        }
    
        expire_after         = "P90D"
        notify_before_expiry = "P29D"
      }
    }
    
  4. Create a file named variables.tf and insert the following code:

    variable "resource_group_location" {
      type        = string
      description = "Location for all resources."
      default     = "eastus"
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
      default     = "rg"
    }
    
    variable "vault_name" {
      type        = string
      description = "The name of the key vault to be created. The value will be randomly generated if blank."
      default     = ""
    }
    
    variable "key_name" {
      type        = string
      description = "The name of the key to be created. The value will be randomly generated if blank."
      default     = ""
    }
    
    variable "sku_name" {
      type        = string
      description = "The SKU of the vault to be created."
      default     = "standard"
      validation {
        condition     = contains(["standard", "premium"], var.sku_name)
        error_message = "The sku_name must be one of the following: standard, premium."
      }
    }
    
    variable "key_permissions" {
      type        = list(string)
      description = "List of key permissions."
      default     = ["List", "Create", "Delete", "Get", "Purge", "Recover", "Update", "GetRotationPolicy", "SetRotationPolicy"]
    }
    
    variable "secret_permissions" {
      type        = list(string)
      description = "List of secret permissions."
      default     = ["Set"]
    }
    
    variable "key_type" {
      description = "The JsonWebKeyType of the key to be created."
      default     = "RSA"
      type        = string
      validation {
        condition     = contains(["EC", "EC-HSM", "RSA", "RSA-HSM"], var.key_type)
        error_message = "The key_type must be one of the following: EC, EC-HSM, RSA, RSA-HSM."
      }
    }
    
    variable "key_ops" {
      type        = list(string)
      description = "The permitted JSON web key operations of the key to be created."
      default     = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"]
    }
    
    variable "key_size" {
      type        = number
      description = "The size in bits of the key to be created."
      default     = 2048
    }
    
    variable "msi_id" {
      type        = string
      description = "The Managed Service Identity ID. If this value isn't null (the default), 'data.azurerm_client_config.current.object_id' will be set to this value."
      default     = null
    }
    
  5. Create a file named outputs.tf and insert the following code:

    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    
    output "azurerm_key_vault_name" {
      value = azurerm_key_vault.vault.name
    }
    
    output "azurerm_key_vault_id" {
      value = azurerm_key_vault.vault.id
    }
    
  6. Create a file named main-generic.tf and insert the following code:

    data "azapi_resource_action" "example" {
      type                   = "Microsoft.KeyVault/vaults@2023-07-01"
      resource_id            = azurerm_key_vault.vault.id
      action                 = "listKeys"
    }
    

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

Key points:

  • The list of keys are displayed in the terraform apply output.

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