I provisioned with terraform the following resources:
- Azure Database for MySQL server
- Azure App Service Plan
- Azure WebApp
- Azure KeyVault
I enabled the managed identity on the webapp and in the Key Vault defined a policy to allow the webapp to access the KeyVault secrets.
First I tried to deploy a simple php application which tries to get the database credentials from the KeyVault and connect to the database.
However, I got an error that the webapp cannot access the KeyVault.
Then I tried to use the Webapp advanced tools and curl from the webapp console to get the access token from the metadata service:
curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2023-01-01&resource=https://vault.azure.net' \
-H 'Metadata:true'
I got the following error:
__ __ __ __ _ __
/ //_/_ _ ____/ /_ __/ / (_) /____
/ ,< / / / / __ / / / / / / / __/ _
/ /| / /_/ / /_/ / /_/ / /___/ / /_/ __/
/_/ |_\__,_/\__,_/\__,_/_____/_/\__/\___/
DEBUG CONSOLE | AZURE APP SERVICE ON LINUX
Documentation: [http://aka.ms/webapp-linux]()
Kudu Version : 20240822.2
Commit : a86ad9d31002b0e2111a20f21ebaeae4be986b94
kudu_ssh_user@webapp-web_kudu_6306b30e78:/$ curl -H "Metadata: true" \
"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net"
curl: (7) Failed to connect to 169.254.169.254 port 80 after 0 ms: Couldn't connect to server
kudu_ssh_user@webapp-web_kudu_6306b30e78:/$
In the Azure console CLI I was able to run the curl command and get the access token for the keyvault, and use the token then in the php application to get the secrets from the KeyVault.
It worked like a charm.
Here is the terraform code fir the app:
locals {
app_service_plan_name = "asp-${var.project_name}"
webapp_name = "webapp-${var.project_name}"
}
#
# create the service plan for the webapp
#
resource "azurerm_service_plan" "webapp_serviceplan" {
name = local.app_service_plan_name
location = var.location
resource_group_name = var.resource_group_name
os_type = "Linux"
sku_name = "F1" # Free tier
}
#create the webapp using the "azurerm_linux_web_app" resource
resource "azurerm_linux_web_app" "webapp" {
name = local.webapp_name
location = var.location
resource_group_name = var.resource_group_name
service_plan_id = azurerm_service_plan.webapp_serviceplan.id
site_config {
always_on = false
application_stack {
php_version = "8.3"
}
}
# enable the managed identity for the webapp
identity {
type = "SystemAssigned"
}
}