Quickstart: Create an Azure Container Instance with a public IP address using Terraform

Use Azure Container Instances to run serverless Docker containers in Azure with simplicity and speed. Deploy an application to a container instance on-demand when you don't need a full container orchestration platform like Azure Kubernetes Service. In this article, you use Terraform to deploy an isolated Docker container and make its web application available with a public IP address.

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:

Prerequisites

Implement the Terraform code

Note

The sample code for this article is located in the Azure Terraform GitHub repo. You can view the log file containing the test results from current and previous versions of Terraform.

See more articles and sample code showing how to use Terraform to manage Azure resources

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

  2. 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
    }
    
    resource "random_string" "container_name" {
      length  = 25
      lower   = true
      upper   = false
      special = false
    }
    
    resource "azurerm_container_group" "container" {
      name                = "${var.container_group_name_prefix}-${random_string.container_name.result}"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
      ip_address_type     = "Public"
      os_type             = "Linux"
      restart_policy      = var.restart_policy
    
      container {
        name   = "${var.container_name_prefix}-${random_string.container_name.result}"
        image  = var.image
        cpu    = var.cpu_cores
        memory = var.memory_in_gb
    
        ports {
          port     = var.port
          protocol = "TCP"
        }
      }
    }
    
  3. Create a file named outputs.tf and insert the following code:

    output "container_ipv4_address" {
      value = azurerm_container_group.container.ip_address
    }
    
  4. Create a file named providers.tf and insert the following code:

    terraform {
      required_version = ">=1.0"
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~>3.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    provider "azurerm" {
      features {}
    }
    
  5. Create a file named variables.tf and insert the following code:

    variable "resource_group_location" {
      type        = string
      default     = "eastus"
      description = "Location for all resources."
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random value so name is unique in your Azure subscription."
    }
    
    variable "container_group_name_prefix" {
      type        = string
      description = "Prefix of the container group name that's combined with a random value so name is unique in your Azure subscription."
      default     = "acigroup"
    }
    
    variable "container_name_prefix" {
      type        = string
      description = "Prefix of the container name that's combined with a random value so name is unique in your Azure subscription."
      default     = "aci"
    }
    
    variable "image" {
      type        = string
      description = "Container image to deploy. Should be of the form repoName/imagename:tag for images stored in public Docker Hub, or a fully qualified URI for other registries. Images from private registries require additional registry credentials."
      default     = "mcr.microsoft.com/azuredocs/aci-helloworld"
    }
    
    variable "port" {
      type        = number
      description = "Port to open on the container and the public IP address."
      default     = 80
    }
    
    variable "cpu_cores" {
      type        = number
      description = "The number of CPU cores to allocate to the container."
      default     = 1
    }
    
    variable "memory_in_gb" {
      type        = number
      description = "The amount of memory to allocate to the container in gigabytes."
      default     = 2
    }
    
    variable "restart_policy" {
      type        = string
      description = "The behavior of Azure runtime if container has stopped."
      default     = "Always"
      validation {
        condition     = contains(["Always", "Never", "OnFailure"], var.restart_policy)
        error_message = "The restart_policy must be one of the following: Always, Never, OnFailure."
      }
    }
    

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

  1. When you apply the execution plan, Terraform outputs the public IP address. To display the IP address again, run terraform output.

    terraform output -raw container_ipv4_address
    
  2. Enter the sample's public IP address in your browser's address bar.

    Screenshot of the Azure Container Instances sample page

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