Deploy a App service from Terraform and a Docker image

Written by

Prerequisites

  1. Ensure you have an Azure Container Registry with a container image already uploaded.
  2. Install Terraform and configure your Azure credentials.

Terraform Script

provider "azurerm" {
features {}
}

# Resource group
resource "azurerm_resource_group" "example" {
name = "example-rg"
location = "East US"
}

# App Service Plan
resource "azurerm_app_service_plan" "example" {
name = "example-asp"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
sku {
tier = "Basic"
size = "B1"
}
}

# App Service
resource "azurerm_app_service" "example" {
name = "example-app"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
app_service_plan_id = azurerm_app_service_plan.example.id

app_settings = {
WEBSITES_PORT = "8080" # Set your container's exposed port
DOCKER_REGISTRY_SERVER_URL = "https://${azurerm_container_registry.example.login_server}"
DOCKER_REGISTRY_SERVER_USERNAME = azurerm_container_registry.example.admin_username
DOCKER_REGISTRY_SERVER_PASSWORD = azurerm_container_registry.example.admin_password
}

site_config {
linux_fx_version = "DOCKER|${azurerm_container_registry.example.login_server}/example-image:latest"
}
}

# Container Registry
resource "azurerm_container_registry" "example" {
name = "exampleacr"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
sku = "Basic"
admin_enabled = true
}

output "app_service_url" {
value = azurerm_app_service.example.default_site_hostname
}

Steps to Apply the Script

  1. Save the script to a file, e.g., main.tf.
  2. Run the following commands:bashCopy codeterraform init terraform plan terraform apply
  3. Confirm the apply step by typing yes when prompted.

Notes

  • Replace "example-image:latest" in the linux_fx_version setting with your actual container image name and tag in ACR.
  • Update resource names and locations to fit your environment.
  • If you don’t have admin access enabled for your ACR, you can use a service principal to provide credentials instead. Let me know if you’d like a script for that!