Azure Static Web Apps with Terraform

Azure Static Web Apps with Terraform

Overview

Devops is many different things to many different people, but nearly all practitioners agree that infrastructure as code is a critical part. So rather then use the Azure portal UI to create our desired resources we are going to script it in code. We will have confidence that we can create, destroy and eventually scale resources as needed.

In this post we will create a Azure static using terraform, step by step.

Terraform is a great tool for scripting your infrastructure. It has first class Azure providers and the security model integrates with the az command line.

Setup

In order to follow this example you will need

  1. An Azure account
  2. Terraform installed
  3. az cli installed

This exercise can be done in the free plan. We will create and destroy the infrastructure. If you neglect to destroy the resources you may wind up with charges.

Logging in to Azure

Once the az cli is installed, run az login and follow the instructions. On some operating systems your browser will automatically open with a login page, Once you have logged in, return to the terminal.

I'm running linux System76 Lemur Pro w/ PopOS (ubuntu) and I've given my subscription the name personal. If you run this on a new free account you may see something like "Pay as you go" for the name.

 1⚡  uname
 2Linux
 3
 4⚡  az login
 5The default web browser has been opened at https://login.microsoftonline.com/common/oauth2/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`.
 6
 7# The above command opens a browser window and you need to login to it.
 8
 9You have logged in. Now let us find all the subscriptions to which you have access...
10[
11  {
12    "cloudName": "AzureCloud",
13    "homeTenantId": "XXXXX-XXXX-",
14    "id": "XXXXX-XXXX-",
15    "isDefault": true,
16    "managedByTenants": [],
17    "name": "personal",
18    "state": "Enabled",
19    "tenantId": "XXXXX-XXXX-"
20    "user": {
21      "name": "myemail@live.com",
22      "type": "user"
23    }
24  }
25]

Use Terraform to create the infrastructure

Base setup and Resource Group

Let's start with a minimal terraform file that just sets up a new Resource Group.

You need to tell Terraform that you will be using the Azure provider and then add the code for a basic resource group.

 1# file: blog.tf
 2terraform {
 3  required_providers {
 4    azurerm = {
 5      source = "hashicorp/azurerm"
 6      version = "~>2.0"
 7    }
 8  }
 9}
10
11resource "azurerm_resource_group" "rg" {
12  name = "test-resource-group"
13  location = eastus
14}

Run terraform init and then terraform plan to ensure we have the syntax right. If that was successful then you will now see a .terraform directory has been created.

Whenever you change the providers block you will need to rerun terraform init. For other changes you can just re-run the plan command.

My run looked something like this

 1⚡  terraform init
 2
 3Initializing the backend...
 4
 5Initializing provider plugins...
 6- Finding hashicorp/azurerm versions matching "~> 2.0"...
 7- Installing hashicorp/azurerm v2.74.0...
 8- Installed hashicorp/azurerm v2.74.0 (signed by HashiCorp)
 9
10Terraform has created a lock file .terraform.lock.hcl to record the provider
11selections it made above. Include this file in your version control repository
12so that Terraform can guarantee to make the same selections by default when
13you run "terraform init" in the future.
14
15Terraform has been successfully initialized!
16# note: I trimmed the output, you will see more
17
18⚡ terraform plan
19
20Terraform used the selected providers to generate the following execution plan. Resource actions are indicated
21with the following symbols:
22  + create
23
24Terraform will perform the following actions:
25
26  # azurerm_resource_group.rg will be created
27  + resource "azurerm_resource_group" "rg" {
28      + id       = (known after apply)
29      + location = "eastus"
30      + name     = "test-resource-group"
31    }
32
33Plan: 1 to add, 0 to change, 0 to destroy.
34# note: I trimmed the output, you will see more

If everything looks good, lets create that resource group using terraform apply. Note that you will prompted to confirm the creation of resources. Eventually this will cost money, so please pay attention to what you create.

 1⚡ terraform apply
 2
 3Terraform used the selected providers to generate the following execution plan. Resource actions are indicated
 4with the following symbols:
 5  + create
 6
 7Terraform will perform the following actions:
 8
 9  # azurerm_resource_group.rg will be created
10  + resource "azurerm_resource_group" "rg" {
11      + id       = (known after apply)
12      + location = "eastus"
13      + name     = "test-resource-group"
14    }
15
16Plan: 1 to add, 0 to change, 0 to destroy.
17
18Do you want to perform these actions?
19  Terraform will perform the actions described above.
20  Only 'yes' will be accepted to approve.
21
22  Enter a value: yes
23
24azurerm_resource_group.rg: Creating...
25azurerm_resource_group.rg: Creation complete after 1s [id=/subscriptions/7c4de52a-a467-40ad-b304-219534ba76e3/resourceGroups/test-resource-group]
26
27Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

After a few seconds you should see your new resource group in the Azure Portal

Resource Groups listing in Azure Portal

or use the command line

1⚡  az group show --name test-resource-group --query 'properties.provisioningState' --out tsv
2Succeeded

Before we move onto then next step, lets destroy the resource group using terraform destroy and you can check it with the cli or portal.

Add Static Web App

Now that we have a resource group, lets put a static web app into it. The terraform looks like this

1# add to blog.tf
2resource "azurerm_static_site" "web" {
3  name = "web-myblog-prod-eastus"
4  resource_group_name = azurerm_resource_group.rg.name
5  location = "eastus"
6}

and run it

1⚡  terraform plan 
2  ...
3Plan: 2 to add, 0 to change, 0 to destroy.

looks good, lets apply it

 1⚡  terraform apply
 2
 3Terraform used ....
 4
 5...
 6
 7azurerm_static_site.web: Creating...
 8 9│ Error: failed creating Static Site: (Name "web-myblog-prod-eastus" / Resource Group "rg-myblog-prod-eastus"): web.StaticSitesClient#CreateOrUpdateStaticSite: Failure sending request: StatusCode=0 -- Original Error: Code="LocationNotAvailableForResourceType" Message="The provided location 'eastus' is not available for resource type 'Microsoft.Web/staticSites'. List of available regions for the resource type is 'westus2,centralus,eastus2,westeurope,eastasia'."
1011│   with azurerm_static_site.web,
12│   on blog.tf line 30, in resource "azurerm_static_site" "web":
13│   30: resource "azurerm_static_site" "web" {

From the helpful error message, it looks like Azure Static websites aren't rolled out into every region. Azure is growing and routinely rolls out new services by region. Keep this in mind when you plan out your infrastructure. It caused me some pain because this resulted in some of my services split across regions.

Terraform Variables

Now we have 2 resources to edit the location, both the resource group and web app need to be updated to used useast2.

Run a terraform destroy and refactor the terraform file to use variables as opposed to hardcoded values.

I like using the Azure convention where resource names should be in the form {resourceType}-{name}-{tier/environment}-{region} so we will do that as well.

Adding some local variables to terraform looks like

1# file: blog.tf
2locals {
3  name = "myblog"
4  location = "eastus2"
5}

and use them like so:

 1# file: blog.tf
 2resource "azurerm_resource_group" "rg" {
 3  name = "rg-${local.name}-prod-${local.location}"
 4  location = local.location
 5  tags = local.common_tags
 6}
 7
 8resource "azurerm_static_site" "web" {
 9  name = "web-${local.name}-prod-${local.location}"
10  resource_group_name = azurerm_resource_group.rg.name
11  location = local.location
12}

Running terraform plan will check the syntax and display the interpolated strings

1# azurerm_resource_group.rg will be created
2  + resource "azurerm_resource_group" "rg" {
3      + id       = (known after apply)
4      + location = "eastus2"
5      + name     = "rg-myblog-prod-eastus"

While we are at it, lets add some tags to our variables. Tags are indispensible to help understand and organize as your grow your cloud.

I usually add a common_tags to the locals. so now our terraform file looks like this;

 1locals {
 2  name = "myblog"
 3  location = "eastus2"
 4  common_tags = {
 5      created_by = "youremail@...."
 6      tier = "production"
 7      inspiration = "https://aaronheld.com"
 8  }
 9}
10
11terraform {
12  required_providers {
13    azurerm = {
14      source = "hashicorp/azurerm"
15      version = "~>2.0"
16    }
17  }
18}
19
20provider "azurerm" {
21  features {}
22}
23
24resource "azurerm_resource_group" "rg" {
25  name = "rg-${local.name}-prod-${local.location}"
26  location = local.location
27  tags = local.common_tags
28}
29
30resource "azurerm_static_site" "web" {
31  name = "web-${local.name}-prod-${local.location}"
32  resource_group_name = azurerm_resource_group.rg.name
33  location = local.location
34  tags = local.common_tags
35}

Run this using terraform apply and check your work

 1⚡  az group show -n rg-myblog-prod-eastus2
 2
 3{
 4  "id": "/subscriptions/XXXXXXXXXX/resourceGroups/rg-myblog-prod-eastus2",
 5  "location": "eastus2",
 6  "managedBy": null,
 7  "name": "rg-myblog-prod-eastus2",
 8  "properties": {
 9    "provisioningState": "Succeeded"
10  },
11  "tags": {
12    "created_by": "youremail@....",
13    "inspiration": "https://aaronheld.com",
14    "tier": "production"
15  },
16  "type": "Microsoft.Resources/resourceGroups"
17}

see if the static web app deployed

1⚡  az staticwebapp show web-myblog-prod-eastus2

if you want to get the default hostname

1⚡  az staticwebapp show -n web-myblog-prod-eastus2 --query defaultHostname --out tsv
2
3# open in a browser
4# osx
5⚡  open http://`az staticwebapp show -n web-myblog-prod-eastus2 --query defaultHostname -o tsv --only-show-errors`
6# linux
7⚡  firefox http://`az staticwebapp show -n web-myblog-prod-eastus2 --query defaultHostname -o tsv --only-show-errors`

finally, lets destroy the resources and move onto deploying a static app from github.

1⚡  terraform destroy

Summary

In this article we used Terraform to script the creation of an Azure Static web app. We introduced variables and some scripting that will be the foundation of our infrastructure code as we progress.

The next step is to get some content to our website.