In the module 2 exercise you followed Laura as she built a virtual machine piece by piece: network, NSG, VM, disks, snapshot and clean-up. Now you will take the equivalent journey in PaaS, and see for yourself how many of those pieces disappear. In this guided exercise you will follow Marc as he deploys a reduced version of hortalia-shop on Azure App Service: a catalogue page with four fictional products and a /health route. You will prepare the project and test it locally, publish it with a single command and also step by step, configure it with environment variables and a start-up command, look at its logs, do a zero-downtime deployment with a staging slot, scale it by hand and with an automatic rule and, at the end, delete everything. As optional extras, you will be able to connect it to a managed PostgreSQL database or automate the deployment with GitHub Actions, and you will see the same exercise summarised on Google Cloud Run. By the end you will have applied, with your own hands, the concepts of the whole of module 3.
- Goal and architecture of the lab
Marc wants to rehearse the store's complete life cycle on App Service before creating the prototype resources (rg-hortalia-shop, asp-hortalia-shop, app-hortalia-shop) he planned in Popular PaaS Providers. The lab lives in its own resource group, rg-hortalia-shop-lab, which will be deleted in full at the end.
flowchart LR
TU["Your machine or Cloud Shell"] -->|"az webapp up / deploy"| APP
NAV["Browser"] -->|"HTTPS"| APP
subgraph RG["rg-hortalia-shop-lab - spaincentral region"]
subgraph PLAN["asp-hortalia-shop-lab - Linux plan (B1, then S1)"]
APP["app-hortalia-shop-lab-XXXX<br/>production slot"]
STG["staging slot"]
APP2["app-hortalia-shop-lab-XXXX-pasos<br/>(step-by-step deployment)"]
end
PG[("Optional:<br/>psql-hortalia-shop-lab-XXXX")]
end
APP -.-> PG
Compare it with the diagram of the VM lab: there is no virtual network, no NSG, no disks and no public IP to create. The platform provides the load balancer, the HTTPS certificate and the operating system. What you do create is a plan (the capacity you pay for) and one or more applications that run on it.
- Prerequisites and cost warning
You need:
- An Azure subscription: the free account (with initial credit for the first few days), credits from educational or partner programmes, or a pay-as-you-go subscription. Check the current terms.
- The Azure CLI: in Azure Cloud Shell (a Bash terminal in the browser, already signed in) or installed on your machine.
- Python 3.12 on your machine for the local test (Cloud Shell has a preinstalled Python 3; the version may vary, and it works just as well for this exercise).
- Git (only for option B) and the
ziputility (included in Cloud Shell and in most Linux and macOS systems). - Optional, for section 17: the Google Cloud CLI (
gcloud) or Google Cloud Shell, and a Google Cloud project with billing enabled.
About the App Service tiers:
| Tier | What it allows in this exercise | Illustrative cost |
|---|---|---|
| F1 (Free) | Deploying and testing the app; limited daily CPU quota; no slots, no scaling to several instances | €0 |
| B1 (Basic) | Everything above with no daily quota; manual scaling to a few instances; no slots and no autoscaling | ~€13/month, that is, around €0.02/hour |
| S1 (Standard) | Deployment slots and autoscaling | ~€70/month, around €0.10/hour |
Tier availability may vary by region and subscription (the F1 tier, in particular, is not always available in every region or may be temporarily exhausted). If a command fails for that reason, try B1 or another European region, such as westeurope or francecentral.
Cost warning. App Service bills the plan while it exists, even if the application receives no visits and even if you "stop" it: stopping the app does not stop the plan being billed. Doing the whole exercise in two or three hours costs of the order of cents of a euro with B1, and a little more during the time you use S1 and, if you do it, the database in optional A (all figures illustrative). But if you forget to delete the resources, they will keep being billed every hour. Step 12 (clean-up) is not optional. If you interrupt the exercise, skip straight to it. As in module 2, it is a good idea to have a budget with an alert in Microsoft Cost Management.
- Step 1: create the project
Create a folder with this structure:
app.py, the application, with the "ready for PaaS" pattern from Definition and Characteristics of PaaS:
import logging
import os
import sys
from flask import Flask, jsonify, render_template
# Configuration from environment variables
APP_ENV = os.environ.get("APP_ENV", "development")
APP_VERSION = os.environ.get("APP_VERSION", "1.0")
MENSAJE_PORTADA = os.environ.get("MENSAJE_PORTADA", "Seasonal fruit and vegetables")
SECRET_KEY = os.environ.get("SECRET_KEY", "development-only")
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("hortalia-shop-lab")
app = Flask(__name__)
app.config["SECRET_KEY"] = SECRET_KEY
# Fictional catalogue (in the real store it would come from PostgreSQL)
PRODUCTS = [
{"code": "NAR-10", "name": "Table oranges", "format": "10 kg box", "price": 14.90},
{"code": "MAN-06", "name": "Fuji apples", "format": "6 kg box", "price": 12.50},
{"code": "AGU-04", "name": "Hass avocados", "format": "4 kg box", "price": 16.80},
{"code": "FRE-02", "name": "Strawberries", "format": "2 kg tray", "price": 9.40},
]
@app.route("/")
def catalogue():
log.info("Catalogue requested (environment=%s, version=%s)", APP_ENV, APP_VERSION)
return render_template("catalogue.html", products=PRODUCTS,
message=MENSAJE_PORTADA, environment=APP_ENV,
version=APP_VERSION)
@app.route("/health")
def health():
return jsonify(status="ok", version=APP_VERSION), 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "8000")),
debug=(APP_ENV == "development"))- The four configuration variables (
APP_ENV,APP_VERSION,MENSAJE_PORTADA,SECRET_KEY) are read from the environment with a default that is useful locally. We will change them from Azure without touching the code. render_template("catalogue.html", ...)looks for the template in thetemplates/folder and passes it the data by name (products,message...)./healthreturns a small JSON with code 200: we will use it for the health check.- The final block is only used locally; on Azure, gunicorn will start it.
templates/catalogue.html, the template with the Jinja2 engine that comes with Flask:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hortalia - Catalogue</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 720px; margin: 2rem auto; padding: 0 1rem; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: .5rem; border-bottom: 1px solid #ddd; text-align: left; }
footer { margin-top: 2rem; color: #666; font-size: .85rem; }
</style>
</head>
<body>
<h1>Hortalia</h1>
<p>{{ message }}</p>
<table>
<tr><th>Product</th><th>Format</th><th>Price</th></tr>
{% for p in products %}
<tr>
<td>{{ p.name }}</td>
<td>{{ p.format }}</td>
<td>€{{ "%.2f"|format(p.price) }}</td>
</tr>
{% endfor %}
</table>
<footer>Environment: {{ environment }} · Version: {{ version }}</footer>
</body>
</html>{{ message }}prints a variable; Jinja2 escapes the HTML automatically, which prevents injection if the text came from a user.{% for p in products %} ... {% endfor %}repeats the row for each product.{{ "%.2f"|format(p.price) }}formats the price with two decimal places.- The footer shows the environment and the version: it will help us see which slot is answering.
requirements.txt, the dependencies:
Flask is the framework and gunicorn the production server that App Service will use. If a dependency is missing from this file, the application will fail to start in the cloud even though it works on your machine.
.gitignore, so that what should not be in Git does not end up there:
.azure/ is a folder that az webapp up will create with the default values of your deployment; .env is where some people keep local variables, and it must never end up in the repository.
- Step 2: test the application locally
python3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -r requirements.txt
python app.pyOpen http://localhost:8000 in the browser: you will see the catalogue with the footer "Environment: development · Version: 1.0". In another terminal, check the health route and try changing the configuration without touching the code:
curl http://localhost:8000/health
# {"status":"ok","version":"1.0"}
# Stop the app (Ctrl+C) and start it with gunicorn and a different configuration
APP_ENV=local-gunicorn MENSAJE_PORTADA="Testing with gunicorn" \
gunicorn --bind 0.0.0.0:8000 --workers 2 app:appAPP_ENV=... MENSAJE_PORTADA=... gunicorn ...: in bash, puttingVARIABLE=valuein front of a command defines the variable for that command only.gunicorn --bind 0.0.0.0:8000 --workers 2 app:app: starts 2 processes that serve theappobject of theapp.pymodule, exactly as App Service will.
If with gunicorn you see the message "Testing with gunicorn" on the home page, the application is ready for the cloud. Stop gunicorn with Ctrl+C.
- Step 3: prepare the Azure session
# Only if you use the CLI on your own machine (in Cloud Shell you are already signed in)
az login
# Check the active subscription
az account show --query "{Subscription:name, Id:id}" --output table
# Lab variables
RG=rg-hortalia-shop-lab
LOC=spaincentral
PLAN=asp-hortalia-shop-lab
SUFFIX=$RANDOM
APP=app-hortalia-shop-lab-$SUFFIX
echo "Your application will be called: $APP"
# Resource group with tags
az group create --name $RG --location $LOC \
--tags proyecto=tienda entorno=laboratorio propietario=marc gestionado_por=cliSUFFIX=$RANDOM:$RANDOMis a random number generated by bash. We need it because the name of an App Service app must be unique across the whole of Azure: it is part of thehttps://<name>.azurewebsites.netURL. If somebody else has already usedapp-hortalia-shop-lab, your deployment would fail.echo: write the name down. If you close the terminal, the variables are lost; you will have to define them again with the same value (APP=app-hortalia-shop-lab-<your number>) in order to continue or to clean up.az group create ... --tags: creates the resource group with the same tags Laura uses, so that Sara can filter the lab's cost.
- Step 4: deploy with a single command (
az webapp up)
az webapp up)From the project folder (where app.py is):
az webapp up \
--name $APP \
--resource-group $RG \
--location $LOC \
--plan $PLAN \
--sku B1 \
--runtime "PYTHON:3.12" \
--logsaz webapp up: an "all in one" command designed to get you started quickly. It detects that the project is Python (fromrequirements.txt), creates the plan if it does not exist, creates the application, packages the folder into a ZIP and deploys it.--name $APP: the unique name of the application.--resource-group $RGand--location $LOC: where to create the resources.--plan $PLAN --sku B1: the name and tier of the plan. If you want to try the free tier, use--sku F1(bear in mind that you will not be able to do Step 9 without changing tier).--runtime "PYTHON:3.12": the runtime. To see the available ones:az webapp list-runtimes --os linux.--logs: enables logging and shows the logs live once the deployment finishes (press Ctrl+C to leave when you have seen it start; the app keeps running).
During the deployment, the Oryx build engine creates a virtual environment and installs requirements.txt. As the app has an app.py file with an app object, App Service starts it with gunicorn automatically. When it finishes, the output includes a JSON with data like this (example values):
{
"URL": "http://app-hortalia-shop-lab-12345.azurewebsites.net",
"appserviceplan": "asp-hortalia-shop-lab",
"location": "spaincentral",
"name": "app-hortalia-shop-lab-12345",
"os": "Linux",
"resourcegroup": "rg-hortalia-shop-lab",
"runtime_version": "PYTHON|3.12",
"sku": "BASIC"
}Open the URL your own output shows (it works with https:// too). The first request may take a few seconds while the container starts. You will see the catalogue with "Environment: development": we have not configured any variable yet.
az webapp up saves the values it used in .azure/config inside the folder. If you run it again with no parameters (az webapp up), it redeploys the code to the same app: it is the quickest way to publish a change while you are experimenting.
Notice what you have not done: choose an OS image, create a network, an NSG, a public IP or a disk, connect over SSH, install Python or a web server. All of that, which took several steps in the VM lab, has been done by the platform.
- Step 5: the same deployment, step by step
az webapp up is convenient, but in a real environment (and in scripts or IaC) it is worth knowing what it does under the hood. Let us deploy a second application on the same plan, step by step:
APP2=$APP-pasos
# 1. The plan already exists (az webapp up created it). This is how it would be created:
# az appservice plan create --resource-group $RG --name $PLAN \
# --location $LOC --is-linux --sku B1
# 2. Create the application on the existing plan
az webapp create --resource-group $RG --plan $PLAN \
--name $APP2 --runtime "PYTHON:3.12"
# 3. Ask the platform to build (install requirements.txt) on deployment
az webapp config appsettings set --resource-group $RG --name $APP2 \
--settings SCM_DO_BUILD_DURING_DEPLOYMENT=true
# 4. Package the code into a ZIP (without the virtual environment)
zip -r app.zip app.py requirements.txt templates
# 5. Deploy the ZIP
az webapp deploy --resource-group $RG --name $APP2 \
--src-path app.zip --type zip
# 6. Open the URL
echo "https://$APP2.azurewebsites.net"az appservice plan create ... --is-linux --sku B1: creates the plan, that is, the capacity (instances of a given size) on which the applications run.--is-linuxmatters: Python on App Service runs on Linux.az webapp create: creates the application inside the plan with the runtime you state. It adds no cost: both apps share the instances of the B1 plan you already pay for. It is a key App Service concept: you pay for the plan, not for the app.SCM_DO_BUILD_DURING_DEPLOYMENT=true: a platform variable stating that, when the ZIP arrives, Oryx must run to install the dependencies. Without it, the code would arrive with neither Flask nor gunicorn installed and it would fail. (az webapp upenables it for you.)zip -r app.zip ...: packages only what is needed. Do not include.venv/: it contains binaries from your system that are of no use on the platform and it makes the package huge.az webapp deploy --type zip: uploads the package. The output says whether the deployment and the build went well.
Open the URL of $APP2: you will see the same catalogue. From here on we will keep working with $APP; $APP2 will be deleted along with the resource group.
- Step 6: configuration through environment variables and a start-up command
Now we configure the app as Marc would in a real environment: with environment variables (in App Service, Application settings) and an explicit start-up command.
# A random key to sign sessions (do not type it by hand or keep it in Git)
KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
az webapp config appsettings set --resource-group $RG --name $APP \
--settings APP_ENV=lab APP_VERSION=1.0 \
MENSAJE_PORTADA="Autumn campaign: citrus fruit just in" \
SECRET_KEY="$KEY" \
--output none
az webapp config set --resource-group $RG --name $APP \
--startup-file "gunicorn --bind=0.0.0.0:8000 --workers 2 --timeout 60 app:app" \
--output nonepython3 -c "import secrets; ...": generates a random 64-character hexadecimal key with Python'ssecretsmodule and stores it in theKEYvariable.az webapp config appsettings set --settings NAME=value ...: defines the app's environment variables. The values are encrypted at rest and the app receives them as ordinary environment variables, whichos.environ.get(...)reads.--output nonestops the CLI printing the response, which would include the values (the key among them) on screen.- Every configuration change restarts the app: bear that in mind in production.
az webapp config set --startup-file "...": sets the start-up command. Although App Service would have detectedapp.pyby itself, being explicit gives you control over the processes (--workers 2), the maximum time per request (--timeout 60) and the port: the App Service Python container expects the application on port 8000.
Reload the URL: you will now see "Autumn campaign: citrus fruit just in" and "Environment: lab". You have changed the app's behaviour without redeploying the code. To see the configuration (without showing the values):
--query "[].name" is a JMESPath query that extracts only the names of the variables. In a real environment, a secret such as SECRET_KEY would be kept in Key Vault and the variable would hold a reference to it (you will see this in exercise 2).
- Step 7: check the logs
# Send the container's standard output to the platform's file system
az webapp log config --resource-group $RG --name $APP \
--docker-container-logging filesystem
# Watch the logs live
az webapp log tail --resource-group $RG --name $APPaz webapp log config --docker-container-logging filesystem: enables the capture of what the application writes to standard output (in App Service for Linux, each app runs in a container, hence the name of the parameter).az webapp log tail: shows the logs in real time. Reload the page in the browser and you will see lines such as:
It is the log.info(...) message from app.py: because we write to stdout, the platform collects it without any file being configured. You will also see gunicorn start-up messages (Booting worker with pid ...) and, if something fails, Python error tracebacks. Press Ctrl+C to leave. In production, Marc would send these logs to Application Insights or Log Analytics to keep them and query them.
- Step 8: enable the health check
az webapp config set --resource-group $RG --name $APP \
--generic-configurations '{"healthCheckPath": "/health"}' \
--output none--generic-configurations '{"healthCheckPath": "/health"}': tells the platform to poll/healthon every instance periodically. If an instance stops answering with a 2xx code over several attempts, the platform stops sending it traffic and, if it persists, replaces it.- It makes full sense with two or more instances (we will get there in Step 10): with only one, there is nowhere to divert the traffic to.
Check it from the terminal:
- Step 9: staging slot and zero-downtime swap
Deployment slots require the Standard tier or higher. We will move the plan up to S1 during this step (and bring it back down afterwards). The real prototype will use Premium v3 P0v3, which also includes them; in the lab we use S1 because you can always move to it from B1 without recreating the plan.
# 1. Move the plan up to Standard S1
az appservice plan update --resource-group $RG --name $PLAN --sku S1
# 2. Create the staging slot copying the production configuration
az webapp deployment slot create --resource-group $RG --name $APP \
--slot staging --configuration-source $APP
# 3. Make APP_ENV belong to each slot (it does not travel with the swap)
az webapp config appsettings set --resource-group $RG --name $APP \
--slot-settings APP_ENV=lab --output none
az webapp config appsettings set --resource-group $RG --name $APP --slot staging \
--slot-settings APP_ENV=staging --output noneaz appservice plan update --sku S1: changes the plan's tier without redeploying the app (there may be a brief restart).az webapp deployment slot create --slot staging --configuration-source $APP: creates a slot calledstaging, with its own URL (https://<app>-staging.azurewebsites.net), copying the configuration (variables, start-up command) from production. The slot runs on the same instances of the plan, at no extra cost.--slot-settings: marks the variable as belonging to the slot (sticky). By default, when you swap, the configuration travels with the code; variables marked as slot settings stay where they are. That way production will always say "lab" and staging will always say "staging", whatever code passes through them. It is what you do in real life with connection strings: the test database must never end up in production.
Now Marc prepares version 1.1: he adds a line to the template, just below the home page message:
And he deploys it to staging only:
az webapp config appsettings set --resource-group $RG --name $APP --slot staging \
--settings APP_VERSION=1.1 --output none
zip -r app.zip app.py requirements.txt templates
az webapp deploy --resource-group $RG --name $APP --slot staging \
--src-path app.zip --type zip
echo "Production: https://$APP.azurewebsites.net"
echo "Staging: https://$APP-staging.azurewebsites.net"Open both URLs: production is still on version 1.0 without the new line; staging shows 1.1 with "Environment: staging". Marc (and Sara) can review staging at their leisure. When everything looks right, the swap:
az webapp deployment slot swap --resource-group $RG --name $APP \
--slot staging --target-slot production- The platform first warms up the staging version with the production configuration (it starts the instances and sends them requests) and, when they answer, it swaps the routing. Visitors see no downtime.
- Result: production shows version 1.1 with the new line and "Environment: lab" (the slot variable stayed behind); staging now has 1.0.
- Rollback: if 1.1 caused problems, you just repeat the same swap command to get 1.0 back in seconds.
Notice that we did not mark APP_VERSION as a slot setting, so it has travelled with the code: production now says "Version: 1.1".
- Step 10: scale by hand and with an automatic rule
Manual (horizontal) scaling:
az appservice plan update --resource-group $RG --name $PLAN --number-of-workers 2
az appservice plan show --resource-group $RG --name $PLAN \
--query "{tier:sku.name, instances:sku.capacity}" --output table--number-of-workers 2: sets the plan to 2 instances. Every app and slot in the plan runs on both, and the platform's load balancer spreads the requests. Now the health check from Step 8 makes sense.az appservice plan show --query ...: shows the tier and the number of instances. You should seeS1and2.
An autoscaling rule (like the ones in PaaS Use Cases, at lab scale):
az monitor autoscale create --resource-group $RG \
--resource $PLAN --resource-type Microsoft.Web/serverfarms \
--name autoscale-hortalia-shop-lab \
--min-count 1 --max-count 3 --count 1
az monitor autoscale rule create --resource-group $RG \
--autoscale-name autoscale-hortalia-shop-lab \
--condition "CpuPercentage > 70 avg 5m" --scale out 1
az monitor autoscale rule create --resource-group $RG \
--autoscale-name autoscale-hortalia-shop-lab \
--condition "CpuPercentage < 30 avg 10m" --scale in 1- The autoscale setting takes control of the number of instances: between 1 and 3, starting at 1. After creating it, the plan will go back to 1 instance within a few minutes, because the CPU will be low.
- The rules add an instance if the average CPU goes above 70% for 5 minutes and remove one if it falls below 30% for 10.
- With the traffic of a single person you will not see any scale-out. If you want to trigger one, you would need a load testing tool (such as
hey,k6or Azure Load Testing), and you should do it sparingly: it is your bill.
Look at the history of scaling actions in the portal (App Service plan → Scale out → Run history) or check the configuration with:
az monitor autoscale show --resource-group $RG --name autoscale-hortalia-shop-lab \
--query "profiles[0].{min:capacity.minimum, max:capacity.maximum, rules:length(rules)}" \
--output tableWhen you have finished experimenting, if you are going to do the optional sections at your own pace, you can move the plan back down to B1 to spend less: first delete the slot and the autoscale setting (B1 does not support them) with az webapp deployment slot delete --resource-group $RG --name $APP --slot staging and az monitor autoscale delete --resource-group $RG --name autoscale-hortalia-shop-lab, and then az appservice plan update --resource-group $RG --name $PLAN --sku B1.
- Optional A: connect to PostgreSQL Flexible Server
Cost: a Burstable B1ms server with 32 GB costs of the order of €15-20/month (a few cents an hour, illustrative). It takes several minutes to create. Delete it when you finish, along with the rest of the group.
The real store will use psql-hortalia-shop with private access from the VNet. In the lab we simplify with public access restricted to Azure services:
PG=psql-hortalia-shop-lab-$SUFFIX
PG_PWD=$(python3 -c "import secrets; print('Hx' + secrets.token_urlsafe(18))")
az postgres flexible-server create --resource-group $RG --name $PG \
--location $LOC --tier Burstable --sku-name Standard_B1ms \
--storage-size 32 --version 16 \
--admin-user hortaliaadmin --admin-password "$PG_PWD" \
--database-name tienda --public-access 0.0.0.0 --yes
az webapp config appsettings set --resource-group $RG --name $APP --output none \
--settings DATABASE_URL="postgresql://hortaliaadmin:$PG_PWD@$PG.postgres.database.azure.com:5432/tienda?sslmode=require"az postgres flexible-server create: creates the managed server.--tier Burstable --sku-name Standard_B1msis the smallest size (CPU "in bursts", enough for testing);--storage-size 32is 32 GB;--version 16the major PostgreSQL version (check withaz postgres flexible-server list-skus --location $LOCor in the documentation which versions and sizes exist in the region);--database-name tiendaalso creates the database.--public-access 0.0.0.0: a special firewall rule that allows connections from Azure services. It is convenient for the lab, but it includes Azure services belonging to any customer (protected, admittedly, by the username and password). That is why the prototype will use private access.--yes: do not ask for confirmations.DATABASE_URL: the connection string as an environment variable.sslmode=requireforces the connection to be encrypted. In production, the password would go in Key Vault, or you would use Entra ID authentication with a managed identity.
In the code, all you need is to add psycopg[binary]==3.2.* to requirements.txt and a test route:
import psycopg
@app.route("/db")
def db():
url = os.environ.get("DATABASE_URL")
if not url:
return jsonify(db="not configured"), 503
with psycopg.connect(url, connect_timeout=5) as connection:
version = connection.execute("SELECT version()").fetchone()[0]
return jsonify(db="ok", version=version.split(",")[0])The route returns 503 (service unavailable) if the configuration is missing and, if not, queries the server version. Redeploy with az webapp up (or the ZIP) and open /db: you should see something like {"db":"ok","version":"PostgreSQL 16.x on x86_64-pc-linux-gnu"}. Notice that you have not installed or configured PostgreSQL: you have only chosen the size, the version and the access. The automatic backups are already running (7 days of retention by default).
- Optional B: automatic deployment with GitHub Actions
Day to day, Marc will not deploy from his laptop: every merge into the main branch must publish the version to staging automatically. Save this file as .github/workflows/desplegar.yml in the repository:
name: Deploy hortalia-shop-lab to staging
on:
push:
branches: [main]
workflow_dispatch:
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Check out the code
uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Check that the dependencies install and the app imports
run: |
pip install -r requirements.txt
python -c "import app"
- name: Sign in to Azure (OIDC, no passwords)
uses: azure/login@v2
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- name: Deploy to the staging slot
uses: azure/webapps-deploy@v3
with:
app-name: ${{ vars.AZURE_WEBAPP_NAME }}
slot-name: staging
package: .on:defines when it runs: on everypushtomainand by hand from the Actions tab (workflow_dispatch).permissions: id-token: writelets the workflow ask GitHub for an identity token, which is needed to sign in to Azure without storing any password (OIDC federation).jobs.deploy.runs-on: ubuntu-latest: the job runs on a temporary GitHub machine with Ubuntu.- The
steps, in order: check out the code (actions/checkout), install Python 3.12 (actions/setup-python), run a minimal check (install the dependencies and import the app: if it fails, nothing is deployed), sign in to Azure (azure/login) and deploy the whole folder (package: .) to thestagingslot (azure/webapps-deploy); the platform builds it with Oryx thanks toSCM_DO_BUILD_DURING_DEPLOYMENT. secrets.*andvars.*: values kept in the repository's configuration in GitHub (Settings → Secrets and variables → Actions), never in the file. The three identifiers are not passwords, but it is good practice to keep them as secrets.- Use the latest major version available of each action when you do this; the ones shown are the current ones at the time of writing this course.
For azure/login to work, somebody with permissions in Entra ID (at Hortalia, Laura) has to create an identity for the workflow: an application registration with a federated credential that trusts the repository and the main branch, and assign it a limited role (for example, Website Contributor) on the lab app only. It is the least privilege principle from The Shared Responsibility Model applied to deployments: the workflow can publish to that app and to nothing else. The swap to production is still done by Marc by hand (or with a second workflow with manual approval).
- Step 11: final verification
Before deleting, review what you have achieved:
| Check | How | Expected result |
|---|---|---|
| The app answers in production | Open https://$APP.azurewebsites.net |
Catalogue with 4 products, "Environment: lab · Version: 1.1" and the new delivery line |
| The health route works | curl -s https://$APP.azurewebsites.net/health |
{"status":"ok","version":"1.1"} |
| The configuration comes from the environment | az webapp config appsettings list ... --query "[].name" |
APP_ENV, APP_VERSION, MENSAJE_PORTADA, SECRET_KEY, SCM_DO_BUILD_DURING_DEPLOYMENT... |
| The slot exists (if you did not delete it) | az webapp deployment slot list --resource-group $RG --name $APP --output table |
staging |
| Autoscaling is configured (if you did not delete it) | az monitor autoscale show ... |
min 1, max 3, 2 rules |
| What resources are in the group | az resource list --resource-group $RG --output table |
Plan, app(s), slot, autoscale setting and, if you did optional A, the PostgreSQL server |
The last command is the most important one: it shows you everything that is being billed in the group, right before you delete it.
- Step 12: clean-up
az group delete --name $RG --yes --no-wait
# After a few minutes, check that it no longer exists
az group exists --name $RGaz group delete --name $RG: deletes the resource group and everything in it: the plan, the applications, the slot, the autoscale setting and, if you created it, the PostgreSQL server.--yes: does not ask for confirmation. Check the name carefully before running it: deleting the wrong group cannot be undone.--no-wait: returns control immediately; the deletion continues in the background.az group exists: returnsfalseonce the deletion has finished.
If you did optional B, also delete the workflow's application registration in Entra ID (or ask whoever created it to do so) and the workflow file in the repository. In your local folder, you can delete .azure/ and app.zip. Finally, the next day, take a look at Cost Management to confirm that the lab's spend has stopped.
- The same exercise on Google Cloud Run
If you want to compare with the alternative Marc noted down for module 5, the same project deploys to Cloud Run with very few changes. As we have no Dockerfile, Cloud Run will use buildpacks to build the image. The Python buildpack looks for a main.py file by default; as ours is called app.py, we state the start-up command with a Procfile in the root of the project:
web:is the name of the process that serves HTTP traffic.--bind :$PORT: Cloud Run states the port with thePORTvariable (8080 by default), unlike App Service, which expects 8000.
gcloud config set project <your-project>
gcloud run deploy hortalia-shop-lab \
--source . \
--region europe-southwest1 \
--allow-unauthenticated \
--max-instances 3 \
--set-env-vars APP_ENV=lab-cloudrun,APP_VERSION=1.1
# Clean-up
gcloud run services delete hortalia-shop-lab --region europe-southwest1 --quiet
gcloud artifacts repositories delete cloud-run-source-deploy \
--location europe-southwest1 --quietgcloud run deploy ... --source .: uploads the code, builds it with Cloud Build and deploys it. The first time it may ask you to enable several APIs (Cloud Run, Cloud Build, Artifact Registry): accept.--region europe-southwest1: Madrid.--allow-unauthenticated: public access.--max-instances 3: the instance ceiling; the default minimum is 0, so with no traffic there are no instances running (with the resulting cold start on the first visit).--set-env-vars: variables separated by commas. If a value contained commas, you would have to use a different syntax or a variables file.- Clean-up:
gcloud run services deletedeletes the service;gcloud artifacts repositories delete cloud-run-source-deploydeletes the repository where--sourcestored the built images, which take up billable storage.
Differences worth noting: Cloud Run scales to zero and bills per use (the App Service plan is always paid for); instead of slots it uses revisions with traffic splitting; and the port and the start-up command are defined differently. The application code, faithful to the twelve-factor app, has not changed by a single line.
Common Mistakes and Tips
- App name not unique.
az webapp uporaz webapp createfail with a message saying the name already exists or is not available. Use a random suffix or your initials. - Wrong port or start-up command. The log shows something like "Container ... didn't respond to HTTP pings on port: 8000". Typical causes: gunicorn listening on another port or only on
127.0.0.1, anapp:appthat does not match the name of the file or of the object, or a Python error while importing the app. Checkaz webapp log tail. - Missing dependencies.
ModuleNotFoundError: No module named 'flask'in the logs: it is missing fromrequirements.txtor, in a ZIP deployment,SCM_DO_BUILD_DURING_DEPLOYMENT=trueis missing. - Uploading the virtual environment in the ZIP. Huge packages and binaries that do not work on the platform. Exclude
.venv/. - Secrets in the code or in the repository. Use environment variables (better still, Key Vault references) and
--output nonewhen setting them, so they do not stay on screen or in the history of a shared terminal. - Thinking that "stopping" the app saves money. The plan is what is billed. To stop paying, delete the plan (or the resource group).
- Forgetting to delete. The plan is billed every hour. Step 12 is not optional.
- Trying to create slots or autoscaling on F1 or B1. They require Standard or higher; the error says so. Move up a tier or skip that step.
- Tip: save every command from the exercise in a
lab.shfile with the variables at the top. It is the first step towards the infrastructure as code of 02-05, which applies to App Service too (Terraform has resources such asazurerm_linux_web_app).
Exercises
Exercise 1. Add to the app an /api/products route that returns the catalogue as JSON. Deploy it to the staging slot first, check it and swap to production. Write the commands and the code.
Exercise 2. Replace the SECRET_KEY variable holding a value in clear text with a Key Vault reference read with the app's managed identity. Write the commands needed (create the Key Vault, store the secret, enable the identity, grant it permission and configure the reference).
Exercise 3. A colleague deploys the app with the ZIP and the URL shows an application error. The logs show these lines. Diagnose the two causes and explain how to fix them.
ModuleNotFoundError: No module named 'flask' Container app-hortalia-shop-lab-12345_0_1a2b didn't respond to HTTP pings on port: 8000
On top of that, their start-up command is gunicorn --bind=127.0.0.1:5000 shop:app, and their main file is called app.py.
Solutions
Solution 1. Code added to app.py:
@app.route("/api/products")
def api_products():
return jsonify(products=PRODUCTS, total=len(PRODUCTS))Commands (with the staging slot created and the plan on S1):
zip -r app.zip app.py requirements.txt templates
az webapp deploy --resource-group $RG --name $APP --slot staging \
--src-path app.zip --type zip
curl -s https://$APP-staging.azurewebsites.net/api/products
az webapp deployment slot swap --resource-group $RG --name $APP \
--slot staging --target-slot production
curl -s https://$APP.azurewebsites.net/api/productsjsonify turns the list of dictionaries into JSON and adds the Content-Type: application/json header. The first curl should return the JSON from staging and the second one, after the swap, from production. Common mistake: deploying to staging with az webapp up, which does not support slots and would publish straight to production.
Solution 2.
KV=kv-hshop-lab-$SUFFIX # 3-24 characters, unique across Azure
# 1. Key Vault with role-based authorization (RBAC)
az keyvault create --resource-group $RG --name $KV --location $LOC \
--enable-rbac-authorization true
# 2. Store the secret (your user needs a role such as "Key Vault Secrets Officer")
az keyvault secret set --vault-name $KV --name secret-key \
--value "$(python3 -c 'import secrets; print(secrets.token_hex(32))')" --output none
# 3. Enable the app's managed identity and get its ID
PRINCIPAL=$(az webapp identity assign --resource-group $RG --name $APP \
--query principalId --output tsv)
# 4. Give the app read-only permission on secrets in that Key Vault
az role assignment create --assignee-object-id $PRINCIPAL \
--assignee-principal-type ServicePrincipal \
--role "Key Vault Secrets User" \
--scope $(az keyvault show --name $KV --query id --output tsv)
# 5. Configure the reference
az webapp config appsettings set --resource-group $RG --name $APP --output none \
--settings SECRET_KEY="@Microsoft.KeyVault(VaultName=$KV;SecretName=secret-key)"- Step 1 creates the vault; with RBAC, permissions are granted through Azure roles.
- Step 3 gives the app its own identity in Entra ID, with no password to store.
- Step 4 applies least privilege: the app can only read secrets, and only from that Key Vault.
- In step 5, the variable no longer holds the secret but a reference. App Service resolves the value with the identity and hands it to the app as an ordinary variable: the code does not change. In the portal, the variable appears with a green tick if the reference resolves correctly.
Common mistake: creating the reference before the role assignment has propagated (it can take a few minutes); the app would receive the literal text @Microsoft.KeyVault(...). Restart the app after a few minutes.
Solution 3. Two causes:
- Dependencies not installed (
No module named 'flask'):SCM_DO_BUILD_DURING_DEPLOYMENT=trueis missing from the configuration, so the platform did not run Oryx when it received the ZIP (or Flask is not inrequirements.txt). Fix:az webapp config appsettings set ... --settings SCM_DO_BUILD_DURING_DEPLOYMENT=true, checkrequirements.txtand redeploy. - Wrong start-up command (it does not answer on port 8000): gunicorn listens on
127.0.0.1:5000, that is, only inside the container and on another port, and on top of that it looks for theshopmodule, which does not exist. Fix:az webapp config set ... --startup-file "gunicorn --bind=0.0.0.0:8000 --workers 2 --timeout 60 app:app".
Tip: when you hit a start-up error, always read the logs from the bottom up: the first Python exception usually explains all the other messages.
Conclusion
In this exercise you have gone through the full life cycle of an application on PaaS: you have prepared a Flask app faithful to the twelve-factor app and tested it locally with gunicorn, you have deployed it with az webapp up and step by step (plan, application and ZIP deployment), you have configured it with environment variables and a start-up command, you have watched its logs live, you have enabled the health check, you have published a new version to a staging slot and taken it to production with a zero-downtime swap, you have scaled it by hand and with an automatic rule, you have seen how to connect a managed database and automate the deployment with GitHub Actions without passwords, you have deleted the whole lab and you have repeated the deployment on Cloud Run without changing the code.
With this exercise we close module 3. You have learnt what Platform as a Service is and what its characteristics are, the types of platform (applications, managed databases, containers and serverless), the providers that offer it, its use cases and how to deploy an application on it from start to finish. Marc now has a clear path for the hortalia-shop store: App Service in spaincentral with autoscaling for Christmas, managed and private PostgreSQL, a stock API that queries the ERP without exposing it and functions for the scheduled tasks; and he has seen what he has stopped doing (patches, disks, load balancers) and what is still his: the code, the dependencies, the data, the secrets and the access configuration. But Hortalia has other systems where it does not want to manage even that much. The ageing mail server and the customer base scattered across Excel spreadsheets do not make the company any different from its competitors, and nobody at Hortalia wants to write or maintain the code of a mail server or a CRM: what they want is to use them. In module 4 we will climb the last step of the stack to study Software as a Service, starting with Definition and Characteristics of SaaS.
