Azure Serverless Application
The Azure Serverless Application template scaffolds a Pulumi project that deploys an Azure Blob Storage account configured for static website hosting and an Azure Function for the application backend. The template ships with placeholder web and function content so the project deploys end to end out of the box.
Before you begin#
For this walkthrough, you'll need:
- The Pulumi CLI
- The Azure CLI (optional, but recommended and used in this guide)
- Permission to manage Azure Storage and App Service
For this walkthrough, you'll need:
- The Pulumi CLI
- The Azure CLI (optional, but recommended and used in this guide)
- Permission to manage Azure Storage and App Service
For this walkthrough, you'll need:
- The Pulumi CLI
- The Azure CLI (optional, but recommended and used in this guide)
- Permission to manage Azure Storage and App Service
- A current version of Go installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- The Azure CLI (optional, but recommended and used in this guide)
- Permission to manage Azure Storage and App Service
- A current version of .NET installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- The Azure CLI (optional, but recommended and used in this guide)
- Permission to manage Azure Storage and App Service
For this walkthrough, you'll need:
- A current version of the Pulumi CLI (Pulumi HCL requires no additional runtime)
- The Azure CLI (optional, but recommended and used in this guide)
- Permission to manage Azure Storage and App Service
Create a new project#
Create a new project from the template:
mkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-typescriptmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-typescriptmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-pythonmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-pythonmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-gomkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-gomkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-csharpmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-csharpmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-yamlmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-yamlmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-hclmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-azure-hclThe pulumi new command walks you through creating and configuring the new project and stack. A stack is an instance of a project, and you can have many of them (dev, staging, prod), each with its own configuration settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.
This template’s settings include:
| Key | Description | Default |
|---|---|---|
| azure-native:location | The Azure region to deploy into | WestUS |
| sitePath | The path to the folder containing the website | www |
| appPath | The path to the folder containing the functions to be deployed | app |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set azure-native:location <value>pulumi config set sitePath <value>pulumi config set appPath <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set azure-native:location "<value>"pulumi config set sitePath "<value>"pulumi config set appPath "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| azure-native:location | The Azure region to deploy into | WestUS |
| sitePath | The path to the folder containing the website | www |
| appPath | The path to the folder containing the functions to be deployed | app |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set azure-native:location <value>pulumi config set sitePath <value>pulumi config set appPath <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set azure-native:location "<value>"pulumi config set sitePath "<value>"pulumi config set appPath "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| azure-native:location | The Azure region to deploy into | WestUS |
| sitePath | The path to the folder containing the website | www |
| appPath | The path to the folder containing the functions to be deployed | app |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set azure-native:location <value>pulumi config set sitePath <value>pulumi config set appPath <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set azure-native:location "<value>"pulumi config set sitePath "<value>"pulumi config set appPath "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| azure-native:location | The Azure region to deploy into | WestUS |
| sitePath | The path to the folder containing the website | www |
| appPath | The path to the folder containing the functions to be deployed | app |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set azure-native:location <value>pulumi config set sitePath <value>pulumi config set appPath <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set azure-native:location "<value>"pulumi config set sitePath "<value>"pulumi config set appPath "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| azure-native:location | The Azure region to deploy into | WestUS |
| sitePath | The path to the folder containing the website | www |
| appPath | The path to the folder containing the functions to be deployed | app |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set azure-native:location <value>pulumi config set sitePath <value>pulumi config set appPath <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set azure-native:location "<value>"pulumi config set sitePath "<value>"pulumi config set appPath "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| azure-native:location | The Azure region to deploy into | WestUS2 |
| site_path | The path to the folder containing the website | www |
| app_path | The path to the folder containing the function to deploy | app |
| index_document | The file to use for top-level pages | index.html |
| error_document | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set azure-native:location <value>pulumi config set site_path <value>pulumi config set app_path <value>pulumi config set index_document <value>pulumi config set error_document <value>pulumi config set azure-native:location "<value>"pulumi config set site_path "<value>"pulumi config set app_path "<value>"pulumi config set index_document "<value>"pulumi config set error_document "<value>"Review the code#
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the resources it declares.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
Take a moment to open them up and have a look. Here’s what’s in index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf:
import * as pulumi from "@pulumi/pulumi";import * as azure from "@pulumi/azure-native";import * as synced from "@pulumi/synced-folder";
// Import the program's configuration settings.const config = new pulumi.Config();const sitePath = config.get("sitePath") || "www";const appPath = config.get("appPath") || "app";const indexDocument = config.get("indexDocument") || "index.html";const errorDocument = config.get("errorDocument") || "error.html";
// Create a resource group for the website.const resourceGroup = new azure.resources.ResourceGroup("resource-group", {});
// Create a blob storage account.const account = new azure.storage.StorageAccount("account", { resourceGroupName: resourceGroup.name, kind: azure.storage.Kind.StorageV2, sku: { name: azure.storage.SkuName.Standard_LRS, },});
// Create a storage container for the pages of the website.const website = new azure.storage.StorageAccountStaticWebsite("website", { accountName: account.name, resourceGroupName: resourceGroup.name, indexDocument: indexDocument, error404Document: errorDocument,});
// Use a synced folder to manage the files of the website.const syncedFolder = new synced.AzureBlobFolder("synced-folder", { path: sitePath, resourceGroupName: resourceGroup.name, storageAccountName: account.name, containerName: website.containerName,});
// Create a storage container for the serverless app.const appContainer = new azure.storage.BlobContainer("app-container", { accountName: account.name, resourceGroupName: resourceGroup.name, publicAccess: azure.storage.PublicAccess.None,});
// Upload the serverless app to the storage container.const appBlob = new azure.storage.Blob("app-blob", { accountName: account.name, resourceGroupName: resourceGroup.name, containerName: appContainer.name, source: new pulumi.asset.FileArchive(appPath),});
// Create a shared access signature to give the Function App access to the code.const signature = azure.storage.listStorageAccountServiceSASOutput({ resourceGroupName: resourceGroup.name, accountName: account.name, protocols: azure.storage.HttpProtocol.Https, sharedAccessStartTime: "2022-01-01", sharedAccessExpiryTime: "2030-01-01", resource: azure.storage.SignedResource.C, permissions: azure.storage.Permissions.R, canonicalizedResource: pulumi.interpolate`/blob/${account.name}/${appContainer.name}`,});
// Create an App Service plan for the Function App.const plan = new azure.web.AppServicePlan("plan", { resourceGroupName: resourceGroup.name, sku: { name: "Y1", tier: "Dynamic", },});
// Create the Function App.const functionApp = new azure.web.WebApp("function-app", { resourceGroupName: resourceGroup.name, serverFarmId: plan.id, kind: "FunctionApp", siteConfig: { appSettings: [ { name: "FUNCTIONS_WORKER_RUNTIME", value: "node", }, { name: "WEBSITE_NODE_DEFAULT_VERSION", value: "~22", }, { name: "FUNCTIONS_EXTENSION_VERSION", value: "~4", }, { name: "WEBSITE_RUN_FROM_PACKAGE", value: pulumi.all([account.name, appContainer.name, appBlob.name, signature]) .apply(([accountName, containerName, blobName, signature]) => `https://${accountName}.blob.core.windows.net/${containerName}/${blobName}?${signature.serviceSasToken}`), }, ], cors: { allowedOrigins: [ "*" ], }, },});
// Create a JSON configuration file for the website.const configFile = new azure.storage.Blob("config.json", { source: functionApp.defaultHostName .apply(host => new pulumi.asset.StringAsset(JSON.stringify({ api: `https://${host}/api` }))), contentType: "application/json", accountName: account.name, resourceGroupName: resourceGroup.name, containerName: website.containerName,});
// Export the URLs of the website and serverless endpoint.export const siteURL = account.primaryEndpoints.apply(primaryEndpoints => primaryEndpoints.web);export const apiURL = pulumi.interpolate`https://${functionApp.defaultHostName}/api`;import pulumiimport pulumi_azure_native as azureimport pulumi_synced_folder as synced
# Import the program's configuration settings.config = pulumi.Config()www_path = config.get("sitePath", "www")app_path = config.get("appPath", "app")index_document = config.get("indexDocument", "index.html")error_document = config.get("errorDocument", "error.html")
# Create a resource group for the website.resource_group = azure.resources.ResourceGroup("resource-group")
# Create a blob storage account.account = azure.storage.StorageAccount( "account", resource_group_name=resource_group.name, kind=azure.storage.Kind.STORAGE_V2, sku={ "name": azure.storage.SkuName.STANDARD_LRS, },)
# Create a storage container for the pages of the website.website = azure.storage.StorageAccountStaticWebsite( "website", account_name=account.name, resource_group_name=resource_group.name, index_document=index_document, error404_document=error_document,)
# Use a synced folder to manage the files of the website.synced_folder = synced.AzureBlobFolder( "synced-folder", path=www_path, resource_group_name=resource_group.name, storage_account_name=account.name, container_name=website.container_name,)
# Create a storage container for the serverless app.app_container = azure.storage.BlobContainer( "app-container", account_name=account.name, resource_group_name=resource_group.name, public_access=azure.storage.PublicAccess.NONE,)
# Upload the serverless app to the storage container.app_blob = azure.storage.Blob( "app-blob", account_name=account.name, resource_group_name=resource_group.name, container_name=app_container.name, source=pulumi.FileArchive(app_path),)
# Create a shared access signature to give the Function App access to the code.signature = ( pulumi.Output.all(resource_group.name, account.name, app_container.name) .apply( lambda args: azure.storage.list_storage_account_service_sas_output( resource_group_name=args[0], account_name=args[1], protocols=azure.storage.HttpProtocol.HTTPS, shared_access_start_time="2022-01-01", shared_access_expiry_time="2030-01-01", resource=azure.storage.SignedResource.C, permissions=azure.storage.Permissions.R, canonicalized_resource=f"/blob/{args[1]}/{args[2]}", ) ) .apply(lambda result: result.service_sas_token))
# Create an App Service plan for the Function App.plan = azure.web.AppServicePlan( "plan", resource_group_name=resource_group.name, kind="Linux", reserved=True, sku={ "name": "Y1", "tier": "Dynamic", },)
# Create the Function App.app = azure.web.WebApp( "app", resource_group_name=resource_group.name, server_farm_id=plan.id, kind="FunctionApp", site_config={ "linux_fx_version": "Python|3.12", "app_settings": [ { "name": "FUNCTIONS_WORKER_RUNTIME", "value": "python", }, { "name": "FUNCTIONS_EXTENSION_VERSION", "value": "~4", }, { "name": "WEBSITE_RUN_FROM_PACKAGE", "value": pulumi.Output.all( account.name, app_container.name, app_blob.name, signature ).apply( lambda args: f"https://{args[0]}.blob.core.windows.net/{args[1]}/{args[2]}?{args[3]}" ), }, ], "cors": { "allowed_origins": ["*"], }, },)
# Create a JSON configuration file for the website.site_config = azure.storage.Blob( "config.json", account_name=account.name, resource_group_name=resource_group.name, container_name=website.container_name, content_type="application/json", source=app.default_host_name.apply( lambda hostname: pulumi.StringAsset('{ "api": "https://' + hostname + '/api" }') ),)
# Export the URLs of the website and serverless endpoint.pulumi.export("siteURL", account.primary_endpoints.web)pulumi.export( "apiURL", app.default_host_name.apply( lambda default_host_name: f"https://{default_host_name}/api" ),)package main
import ( "archive/zip" "fmt" "io" "io/fs" "os" "os/exec" "path/filepath" "time"
resources "github.com/pulumi/pulumi-azure-native-sdk/resources/v3" storage "github.com/pulumi/pulumi-azure-native-sdk/storage/v3" web "github.com/pulumi/pulumi-azure-native-sdk/web/v3" synced "github.com/pulumi/pulumi-synced-folder/sdk/go/synced-folder" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config")
func main() { pulumi.Run(func(ctx *pulumi.Context) error {
// Import the program's configuration settings. cfg := config.New(ctx, "") sitePath := "www" if param := cfg.Get("sitePath"); param != "" { sitePath = param } appPath := "app" if param := cfg.Get("appPath"); param != "" { appPath = param } indexDocument := "index.html" if param := cfg.Get("indexDocument"); param != "" { indexDocument = param } errorDocument := "error.html" if param := cfg.Get("errorDocument"); param != "" { errorDocument = param }
// Create a resource group for the website. resourceGroup, err := resources.NewResourceGroup(ctx, "resource-group", nil) if err != nil { return err }
// Create a blob storage account. account, err := storage.NewStorageAccount(ctx, "account", &storage.StorageAccountArgs{ ResourceGroupName: resourceGroup.Name, Kind: pulumi.String("StorageV2"), Sku: &storage.SkuArgs{ Name: pulumi.String("Standard_LRS"), }, }) if err != nil { return err }
// Create a storage container for the pages of the website. website, err := storage.NewStorageAccountStaticWebsite(ctx, "website", &storage.StorageAccountStaticWebsiteArgs{ AccountName: account.Name, ResourceGroupName: resourceGroup.Name, IndexDocument: pulumi.String(indexDocument), Error404Document: pulumi.String(errorDocument), }) if err != nil { return err }
// Use a synced folder to manage the files of the website. _, err = synced.NewAzureBlobFolder(ctx, "synced-folder", &synced.AzureBlobFolderArgs{ Path: pulumi.String(sitePath), ResourceGroupName: resourceGroup.Name, StorageAccountName: account.Name, ContainerName: website.ContainerName, }) if err != nil { return err }
// Create a storage container for the serverless app. appContainer, err := storage.NewBlobContainer(ctx, "app-container", &storage.BlobContainerArgs{ AccountName: account.Name, ResourceGroupName: resourceGroup.Name, PublicAccess: storage.PublicAccessNone, }) if err != nil { return err }
// Compile the app for the Azure Linux environment. build := exec.Command("go", "build", "cmd/app.go") build.Dir = appPath build.Env = append(os.Environ(), "GOOS=linux", "GOARCH=amd64") if output, err := build.CombinedOutput(); err != nil { return fmt.Errorf("building the app: %w\n%s", err, output) }
// Package the app as a zip file. if err := zipFolder(appPath, "app.zip"); err != nil { return err }
// Upload the serverless app to the storage container. appBlob, err := storage.NewBlob(ctx, "app-blob", &storage.BlobArgs{ AccountName: account.Name, ResourceGroupName: resourceGroup.Name, ContainerName: appContainer.Name, BlobName: pulumi.String("app.zip"), Source: pulumi.NewFileAsset(filepath.Join(appPath, "app.zip")), }) if err != nil { return err }
// Create a shared access signature to give the Function App access to the code. signature := storage.ListStorageAccountServiceSASOutput(ctx, storage.ListStorageAccountServiceSASOutputArgs{ ResourceGroupName: resourceGroup.Name, AccountName: account.Name, Protocols: storage.HttpProtocolHttps, SharedAccessStartTime: pulumi.String("2022-01-01"), SharedAccessExpiryTime: pulumi.String("2030-01-01"), Resource: pulumi.String("c"), Permissions: pulumi.String("r"), CanonicalizedResource: pulumi.Sprintf("/blob/%s/%s", account.Name, appContainer.Name), })
// Create an App Service plan for the Function App. plan, err := web.NewAppServicePlan(ctx, "plan", &web.AppServicePlanArgs{ ResourceGroupName: resourceGroup.Name, Kind: pulumi.String("Linux"), Reserved: pulumi.Bool(true), Sku: &web.SkuDescriptionArgs{ Name: pulumi.String("Y1"), Tier: pulumi.String("Dynamic"), }, }) if err != nil { return err }
// Create the Function App. app, err := web.NewWebApp(ctx, "app", &web.WebAppArgs{ ResourceGroupName: resourceGroup.Name, ServerFarmId: plan.ID(), Kind: pulumi.String("FunctionApp"), SiteConfig: &web.SiteConfigArgs{ AppSettings: web.NameValuePairArray{ &web.NameValuePairArgs{ Name: pulumi.String("FUNCTIONS_WORKER_RUNTIME"), Value: pulumi.String("custom"), }, &web.NameValuePairArgs{ Name: pulumi.String("FUNCTIONS_EXTENSION_VERSION"), Value: pulumi.String("~4"), }, &web.NameValuePairArgs{ Name: pulumi.String("WEBSITE_RUN_FROM_PACKAGE"), Value: pulumi.All(account.Name, appContainer.Name, appBlob.Name, signature.ServiceSasToken()).ApplyT( func(args []interface{}) string { accountName := args[0].(string) containerName := args[1].(string) blobName := args[2].(string) token := args[3].(string) return fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s?%s", accountName, containerName, blobName, token) }).(pulumi.StringPtrInput), }, }, Cors: &web.CorsSettingsArgs{ AllowedOrigins: pulumi.StringArray{ pulumi.String("*"), }, }, }, }) if err != nil { return err }
// Create a JSON configuration file for the website. _, err = storage.NewBlob(ctx, "config.json", &storage.BlobArgs{ AccountName: account.Name, ResourceGroupName: resourceGroup.Name, ContainerName: website.ContainerName, ContentType: pulumi.StringPtr("application/json"),
Source: app.DefaultHostName.ApplyT(func(hostname string) pulumi.AssetOrArchiveOutput { config := fmt.Sprintf(`{ "api": "https://%s/api" }`, hostname) return pulumi.NewStringAsset(config).ToAssetOrArchiveOutput() }).(pulumi.AssetOrArchiveOutput), }) if err != nil { return err }
// Export the URLs of the website and serverless endpoint. ctx.Export("siteURL", account.PrimaryEndpoints.Web()) ctx.Export("apiURL", pulumi.Sprintf("https://%v/api", app.DefaultHostName))
return nil })}
// zipFolder writes the contents of a folder to a zip file in that folder. The app's// executable keeps its executable bit, and fixed timestamps keep the zip unchanged// between deployments unless its contents change.func zipFolder(dir string, name string) error { file, err := os.Create(filepath.Join(dir, name)) if err != nil { return err } defer file.Close()
archive := zip.NewWriter(file) err = filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error { if err != nil || entry.IsDir() { return err } relPath, err := filepath.Rel(dir, path) if err != nil || relPath == name { return err }
header := &zip.FileHeader{ Name: filepath.ToSlash(relPath), Method: zip.Deflate, Modified: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), } header.SetMode(0644) if relPath == "app" { header.SetMode(0755) }
writer, err := archive.CreateHeader(header) if err != nil { return err } contents, err := os.Open(path) if err != nil { return err } defer contents.Close() _, err = io.Copy(writer, contents) return err }) if err != nil { return err } return archive.Close()}using System.Collections.Generic;using System.Text.Json;using System.IO;using Pulumi;using Pulumi.Command.Local;using AzureNative = Pulumi.AzureNative;using SyncedFolder = Pulumi.SyncedFolder;
return await Deployment.RunAsync(() =>{ // Import the program's configuration settings. var config = new Config(); var sitePath = config.Get("sitePath") ?? "www"; var appPath = config.Get("appPath") ?? "app"; var indexDocument = config.Get("indexDocument") ?? "index.html"; var errorDocument = config.Get("errorDocument") ?? "error.html";
// Create a resource group for the website. var resourceGroup = new AzureNative.Resources.ResourceGroup("resource-group");
// Create a blob storage account. var account = new AzureNative.Storage.StorageAccount("account", new() { ResourceGroupName = resourceGroup.Name, Kind = AzureNative.Storage.Kind.StorageV2, Sku = new AzureNative.Storage.Inputs.SkuArgs { Name = AzureNative.Storage.SkuName.Standard_LRS, }, });
// Create a storage container for the pages of the website. var website = new AzureNative.Storage.StorageAccountStaticWebsite("website", new() { AccountName = account.Name, ResourceGroupName = resourceGroup.Name, IndexDocument = indexDocument, Error404Document = errorDocument, });
// Use a synced folder to manage the files of the website. var syncedFolder = new SyncedFolder.AzureBlobFolder("synced-folder", new() { Path = sitePath, ResourceGroupName = resourceGroup.Name, StorageAccountName = account.Name, ContainerName = website.ContainerName, });
// Create a storage container for the serverless app. var appContainer = new AzureNative.Storage.BlobContainer("app-container", new() { AccountName = account.Name, ResourceGroupName = resourceGroup.Name, PublicAccess = AzureNative.Storage.PublicAccess.None, });
// Compile the the app. var outputPath = "publish"; var publishCommand = Run.Invoke(new() { Command = $"dotnet publish --output {outputPath}", Dir = appPath, });
// Upload the serverless app to the storage container. var appBlob = new AzureNative.Storage.Blob("app-blob", new() { AccountName = account.Name, ResourceGroupName = resourceGroup.Name, ContainerName = appContainer.Name, Source = publishCommand.Apply(result => new FileArchive(Path.Combine(appPath, outputPath)) as AssetOrArchive), });
// Create a shared access signature to give the Function App access to the code. var signature = AzureNative.Storage.ListStorageAccountServiceSAS.Invoke(new() { ResourceGroupName = resourceGroup.Name, AccountName = account.Name, Protocols = AzureNative.Storage.HttpProtocol.Https, SharedAccessStartTime = "2022-01-01", SharedAccessExpiryTime = "2030-01-01", Resource = AzureNative.Storage.SignedResource.C, Permissions = AzureNative.Storage.Permissions.R, CanonicalizedResource = Output.Tuple(account.Name, appContainer.Name).Apply(values => $"/blob/{values.Item1}/{values.Item2}"), }).Apply(result => result.ServiceSasToken);
// Create an App Service plan for the Function App. var plan = new AzureNative.Web.AppServicePlan("plan", new() { ResourceGroupName = resourceGroup.Name, Sku = new AzureNative.Web.Inputs.SkuDescriptionArgs { Name = "Y1", Tier = "Dynamic", }, });
// Create the Function App. var app = new AzureNative.Web.WebApp("app", new() { ResourceGroupName = resourceGroup.Name, ServerFarmId = plan.Id, Kind = "FunctionApp", SiteConfig = new AzureNative.Web.Inputs.SiteConfigArgs { NetFrameworkVersion = "v8.0", DetailedErrorLoggingEnabled = true, HttpLoggingEnabled = true, AppSettings = new[] { new AzureNative.Web.Inputs.NameValuePairArgs { Name = "FUNCTIONS_WORKER_RUNTIME", Value = "dotnet", }, new AzureNative.Web.Inputs.NameValuePairArgs { Name = "FUNCTIONS_EXTENSION_VERSION", Value = "~4", }, new AzureNative.Web.Inputs.NameValuePairArgs { Name = "WEBSITE_RUN_FROM_PACKAGE", Value = Output.Tuple(account.Name, appContainer.Name, appBlob.Name, signature).Apply(values => { var accountName = values.Item1; var containerName = values.Item2; var blobName = values.Item3; var token = values.Item4; return $"https://{accountName}.blob.core.windows.net/{containerName}/{blobName}?{token}"; }), }, }, Cors = new AzureNative.Web.Inputs.CorsSettingsArgs { AllowedOrigins = new[] { "*", }, }, }, });
// Create a JSON configuration file for the website. var siteConfig = new AzureNative.Storage.Blob("config.json", new() { AccountName = account.Name, ResourceGroupName = resourceGroup.Name, ContainerName = website.ContainerName, ContentType = "application/json", Source = app.DefaultHostName.Apply(hostname => { var config = JsonSerializer.Serialize(new { api = $"https://{hostname}/api" }); return new Pulumi.StringAsset(config) as AssetOrArchive; }), });
// Export the URLs of the website and serverless endpoint. return new Dictionary<string, object?> { ["siteURL"] = account.PrimaryEndpoints.Apply(primaryEndpoints => primaryEndpoints.Web), ["apiURL"] = app.DefaultHostName.Apply(defaultHostName => $"https://{defaultHostName}/api"), };});name: my-projectdescription: A Pulumi YAML program to deploy a serverless application on Azureruntime: yaml
# Import the program's configuration settings.config: sitePath: type: string default: www appPath: type: string default: app indexDocument: type: string default: index.html errorDocument: type: string default: error.html
variables:
# Create a shared access signature allowing access to function storage. signature: fn::azure-native:storage:listStorageAccountServiceSAS: resourceGroupName: ${resource-group.name} accountName: ${account.name} protocols: https sharedAccessStartTime: "2022-01-01" sharedAccessExpiryTime: "2030-01-01" resource: c permissions: r canonicalizedResource: /blob/${account.name}/${app-container.name}
# Create a FileArchive containing the contents of the app folder. appArchive: fn::fileArchive: ${appPath}
# Create a JSON string containing the URL of the serverless app. configJSON: fn::toJSON: api: https://${app.defaultHostName}/api
# Create a StringAsset resource to convert the JSON string into a file. configFile: fn::stringAsset: ${configJSON}
resources:
# Create a resource group for the website. resource-group: type: azure-native:resources:ResourceGroup
# Create a blob storage account. account: type: azure-native:storage:StorageAccount properties: resourceGroupName: ${resource-group.name} kind: StorageV2 sku: name: Standard_LRS
# Create a storage container for the pages of the website. website: type: azure-native:storage:StorageAccountStaticWebsite properties: accountName: ${account.name} resourceGroupName: ${resource-group.name} indexDocument: ${indexDocument} error404Document: ${errorDocument}
# Use a synced folder to manage the files of the website. synced-folder: type: synced-folder:index:AzureBlobFolder properties: path: ${sitePath} resourceGroupName: ${resource-group.name} storageAccountName: ${account.name} containerName: ${website.containerName}
# Create a storage container for the serverless app. app-container: type: azure-native:storage:BlobContainer properties: accountName: ${account.name} resourceGroupName: ${resource-group.name} publicAccess: None
# Upload the serverless app to the storage container. app-blob: type: azure-native:storage:Blob properties: accountName: ${account.name} resourceGroupName: ${resource-group.name} containerName: ${app-container.name} source: ${appArchive} type: Block
# Create an App Service plan for the Function App. plan: type: azure-native:web:AppServicePlan properties: resourceGroupName: ${resource-group.name} kind: Linux reserved: true sku: name: Y1 tier: Dynamic
# Create the Function App. app: type: azure-native:web:WebApp properties: resourceGroupName: ${resource-group.name} serverFarmId: ${plan.id} kind: FunctionApp siteConfig: linuxFxVersion: Python|3.12 appSettings: - name: FUNCTIONS_WORKER_RUNTIME value: python - name: FUNCTIONS_EXTENSION_VERSION value: "~4" - name: WEBSITE_RUN_FROM_PACKAGE value: https://${account.name}.blob.core.windows.net/${app-container.name}/${app-blob.name}?${signature.serviceSasToken} cors: allowedOrigins: - "*"
# Create a JSON configuration file for the website. config.json: type: azure-native:storage:Blob properties: accountName: ${account.name} resourceGroupName: ${resource-group.name} containerName: ${website.containerName} contentType: application/json source: ${configFile} type: Block
# Export the URLs of the website and serverless endpoint.outputs: originURL: ${account.primaryEndpoints.web} apiURL: https://${app.defaultHostName}/apiterraform { required_providers { azure-native = { source = "pulumi/azure-native" } synced-folder = { source = "pulumi/synced-folder" } }}
variable "site_path" { description = "The path to the folder containing the website" type = string default = "www"}
variable "app_path" { description = "The path to the folder containing the functions to be deployed" type = string default = "app"}
variable "index_document" { description = "The file to use for top-level pages" type = string default = "index.html"}
variable "error_document" { description = "The file to use for error pages" type = string default = "error.html"}
locals { app_archive = filearchive(var.app_path) config_json = jsonencode({ api = "https://${azure-native_web_web_app.app.default_host_name}/api" }) config_file = stringasset(local.config_json)}
# Create a resource group for the website.resource "azure-native_resources_resource_group" "resource-group" {}
# Create a blob storage account.resource "azure-native_storage_storage_account" "account" { resource_group_name = azure-native_resources_resource_group.resource-group.name kind = "StorageV2" sku = { name = "Standard_LRS" }}
# Create a storage container for the pages of the website.resource "azure-native_storage_storage_account_static_website" "website" { resource_group_name = azure-native_resources_resource_group.resource-group.name account_name = azure-native_storage_storage_account.account.name index_document = var.index_document error404_document = var.error_document}
# Use a synced folder to manage the files of the website.resource "synced-folder_azure_blob_folder" "synced-folder" { path = var.site_path resource_group_name = azure-native_resources_resource_group.resource-group.name storage_account_name = azure-native_storage_storage_account.account.name container_name = azure-native_storage_storage_account_static_website.website.container_name}
# Create a storage container for the serverless app.resource "azure-native_storage_blob_container" "app-container" { resource_group_name = azure-native_resources_resource_group.resource-group.name account_name = azure-native_storage_storage_account.account.name public_access = "None"}
# Upload the serverless app to the storage container.resource "azure-native_storage_blob" "app-blob" { resource_group_name = azure-native_resources_resource_group.resource-group.name account_name = azure-native_storage_storage_account.account.name container_name = azure-native_storage_blob_container.app-container.name type = "Block" source = local.app_archive}
# Create a shared access signature allowing access to function storage.data "azure-native_storage_list_storage_account_service_s_a_s" "signature" { resource_group_name = azure-native_resources_resource_group.resource-group.name account_name = azure-native_storage_storage_account.account.name protocols = "https" shared_access_start_time = "2022-01-01" shared_access_expiry_time = "2030-01-01" resource = "c" permissions = "r" canonicalized_resource = "/blob/${azure-native_storage_storage_account.account.name}/${azure-native_storage_blob_container.app-container.name}"}
# Create an App Service plan for the Function App.resource "azure-native_web_app_service_plan" "plan" { resource_group_name = azure-native_resources_resource_group.resource-group.name kind = "Linux" reserved = true sku = { name = "Y1" tier = "Dynamic" }}
# Create the Function App.resource "azure-native_web_web_app" "app" { resource_group_name = azure-native_resources_resource_group.resource-group.name server_farm_id = azure-native_web_app_service_plan.plan.id kind = "FunctionApp"
site_config = { linux_fx_version = "Python|3.12" app_settings = [ { name = "FUNCTIONS_WORKER_RUNTIME" value = "python" }, { name = "FUNCTIONS_EXTENSION_VERSION" value = "~4" }, { name = "WEBSITE_RUN_FROM_PACKAGE" value = "https://${azure-native_storage_storage_account.account.name}.blob.core.windows.net/${azure-native_storage_blob_container.app-container.name}/${azure-native_storage_blob.app-blob.name}?${data.azure-native_storage_list_storage_account_service_s_a_s.signature.service_sas_token}" }, ] cors = { allowed_origins = ["*"] } }}
# Create a JSON configuration file for the website.resource "azure-native_storage_blob" "config" { resource_group_name = azure-native_resources_resource_group.resource-group.name account_name = azure-native_storage_storage_account.account.name container_name = azure-native_storage_storage_account_static_website.website.container_name blob_name = "config.json" content_type = "application/json" type = "Block" source = local.config_file}
# Export the URLs of the website and serverless endpoint.output "origin_url" { value = azure-native_storage_storage_account.account.primary_endpoints.web}
output "api_url" { value = "https://${azure-native_web_web_app.app.default_host_name}/api"}Deploy the project#
Deploy with pulumi up. It starts with a preview of what it’s about to create and asks before it changes anything. Choose yes to deploy.
pulumi uppulumi upPulumi adds a random suffix to most resource names, so the resource group resource-group becomes something like resource-group8f3c2a1b. This is autonaming. It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding.
When it finishes, Pulumi prints the stack’s outputs, values it only knows once the resources exist:
- siteURL
The HTTPS URL of the static website.
- apiURL
The HTTPS URL of the serverless function endpoint.
- siteURL
The HTTPS URL of the static website.
- apiURL
The HTTPS URL of the serverless function endpoint.
- siteURL
The HTTPS URL of the static website.
- apiURL
The HTTPS URL of the serverless function endpoint.
- siteURL
The HTTPS URL of the static website.
- apiURL
The HTTPS URL of the serverless function endpoint.
- originURL
The HTTPS URL of the static website.
- apiURL
The HTTPS URL of the serverless function endpoint.
- origin_url
The HTTPS URL of the static website.
- api_url
The HTTPS URL of the serverless function endpoint.
Read one any time with pulumi stack output <name>, or pass it to another command. This opens the website in your browser:
open $(pulumi stack output siteURL)xdg-open $(pulumi stack output siteURL)Start-Process $(pulumi stack output siteURL)open $(pulumi stack output siteURL)xdg-open $(pulumi stack output siteURL)Start-Process $(pulumi stack output siteURL)open $(pulumi stack output siteURL)xdg-open $(pulumi stack output siteURL)Start-Process $(pulumi stack output siteURL)open $(pulumi stack output siteURL)xdg-open $(pulumi stack output siteURL)Start-Process $(pulumi stack output siteURL)open $(pulumi stack output originURL)xdg-open $(pulumi stack output originURL)Start-Process $(pulumi stack output originURL)open $(pulumi stack output origin_url)xdg-open $(pulumi stack output origin_url)Start-Process $(pulumi stack output origin_url)The website’s button calls the function at the /data path. Call it from the terminal with curl; it prints the current time in milliseconds, like {"now": 1792591509000}. The first call can take a few seconds while the function starts.
curl -s $(pulumi stack output apiURL)/datacurl.exe -s "$(pulumi stack output apiURL)/data"curl -s $(pulumi stack output apiURL)/datacurl.exe -s "$(pulumi stack output apiURL)/data"curl -s $(pulumi stack output apiURL)/datacurl.exe -s "$(pulumi stack output apiURL)/data"curl -s $(pulumi stack output apiURL)/datacurl.exe -s "$(pulumi stack output apiURL)/data"curl -s $(pulumi stack output apiURL)/datacurl.exe -s "$(pulumi stack output apiURL)/data"curl -s $(pulumi stack output api_url)/datacurl.exe -s "$(pulumi stack output api_url)/data"Need help?
If pulumi up asks you to run az login, or says your sign-in has expired, sign in again:
az loginaz loginStill stuck? Let us know.
Customize the project#
Projects created with this template expose the following configuration settings:
- sitePath
The path to the folder containing the files of the website. Defaults to
www, which is the folder included with the template.- appPath
The path to the folder containing the serverless functions to be deployed. Defaults to
app, which is also included with the template.- indexDocument
The file to use for top-level pages. Defaults to
index.html.- errorDocument
The file to use for error pages. Defaults to
error.html.
- sitePath
The path to the folder containing the files of the website. Defaults to
www, which is the folder included with the template.- appPath
The path to the folder containing the serverless functions to be deployed. Defaults to
app, which is also included with the template.- indexDocument
The file to use for top-level pages. Defaults to
index.html.- errorDocument
The file to use for error pages. Defaults to
error.html.
- sitePath
The path to the folder containing the files of the website. Defaults to
www, which is the folder included with the template.- appPath
The path to the folder containing the serverless functions to be deployed. Defaults to
app, which is also included with the template.- indexDocument
The file to use for top-level pages. Defaults to
index.html.- errorDocument
The file to use for error pages. Defaults to
error.html.
- sitePath
The path to the folder containing the files of the website. Defaults to
www, which is the folder included with the template.- appPath
The path to the folder containing the serverless functions to be deployed. Defaults to
app, which is also included with the template.- indexDocument
The file to use for top-level pages. Defaults to
index.html.- errorDocument
The file to use for error pages. Defaults to
error.html.
- sitePath
The path to the folder containing the files of the website. Defaults to
www, which is the folder included with the template.- appPath
The path to the folder containing the serverless functions to be deployed. Defaults to
app, which is also included with the template.- indexDocument
The file to use for top-level pages. Defaults to
index.html.- errorDocument
The file to use for error pages. Defaults to
error.html.
- site_path
The path to the folder containing the files of the website. Defaults to
www, which is the folder included with the template.- app_path
The path to the folder containing the serverless functions to be deployed. Defaults to
app, which is also included with the template.- index_document
The file to use for top-level pages. Defaults to
index.html.- error_document
The file to use for error pages. Defaults to
error.html.
All of these settings are optional and may be adjusted either by editing the stack configuration file directly (by default, Pulumi.dev.yaml) or by changing their values with pulumi config set.
For example, to deploy a website from another folder on your computer, replacing ../my-existing-website/build with the path to your site’s files:
pulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set sitePath ../my-existing-website/buildpulumi uppulumi config set site_path ../my-existing-website/buildpulumi uppulumi config set site_path ../my-existing-website/buildpulumi upChanging the error page#
The error page is what the website returns for a path it doesn’t have. Point it at the home page instead, then ask for a page that doesn’t exist. curl prints the home page, with What time is it?, in place of the template’s Oops! That page wasn't found. If it still prints the old error page, wait a few seconds and run curl again:
pulumi config set errorDocument index.htmlpulumi upcurl -s $(pulumi stack output siteURL)no-such-pagepulumi config set errorDocument index.htmlpulumi upcurl.exe -s "$(pulumi stack output siteURL)no-such-page"pulumi config set errorDocument index.htmlpulumi upcurl -s $(pulumi stack output siteURL)no-such-pagepulumi config set errorDocument index.htmlpulumi upcurl.exe -s "$(pulumi stack output siteURL)no-such-page"pulumi config set errorDocument index.htmlpulumi upcurl -s $(pulumi stack output siteURL)no-such-pagepulumi config set errorDocument index.htmlpulumi upcurl.exe -s "$(pulumi stack output siteURL)no-such-page"pulumi config set errorDocument index.htmlpulumi upcurl -s $(pulumi stack output siteURL)no-such-pagepulumi config set errorDocument index.htmlpulumi upcurl.exe -s "$(pulumi stack output siteURL)no-such-page"pulumi config set errorDocument index.htmlpulumi upcurl -s $(pulumi stack output originURL)no-such-pagepulumi config set errorDocument index.htmlpulumi upcurl.exe -s "$(pulumi stack output originURL)no-such-page"pulumi config set error_document index.htmlpulumi upcurl -s $(pulumi stack output origin_url)no-such-pagepulumi config set error_document index.htmlpulumi upcurl.exe -s "$(pulumi stack output origin_url)no-such-page"To see what else you can add, browse the Azure Native provider in the Pulumi Registry.
Cleaning up#
You can cleanly destroy the stack and all of its infrastructure with pulumi destroy:
pulumi destroypulumi destroyLearn more#
- Browse other architecture templates in the Templates gallery.
- Explore the Azure Native provider API docs in the Pulumi Registry.
- Walk through Pulumi from the ground up in Pulumi Tutorials.
- Read the latest Azure posts on the Pulumi blog.