创建具有命名存储帐户连接的函数应用

此 Azure Functions 示例脚本先创建一个函数应用,然后将该函数连接到 Azure 存储帐户。 创建的包含存储连接字符串的应用设置可以与存储触发器或绑定配合使用。

如果没有 Azure 订阅,可在开始前创建一个试用帐户

先决条件

可以使用本地 Azure CLI。

  • 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。

  • 本地 Azure CLI,请了解如何安装 Azure CLI。 如果在 Windows 或 macOS 上运行,请考虑在 Docker 容器中运行 Azure CLI。 有关详细信息,请参阅如何在 Docker 容器中运行 Azure CLI

    • 通过使用 az login 命令登录到 Azure CLI。 若要完成身份验证过程,请遵循终端中显示的步骤。 有关其他登录选项,请参阅使用 Azure CLI 登录

    • 出现提示时,请在首次使用时安装 Azure CLI 扩展。 有关扩展详细信息,请参阅使用 Azure CLI 的扩展

    • 运行 az version 以查找安装的版本和依赖库。 若要升级到最新版本,请运行 az upgrade

示例脚本

运行脚本

#!/bin/bash

# <FullScript>
# Function app and storage account names must be unique.

# Variable block
let "randomIdentifier=$RANDOM*$RANDOM"
location="chinanorth2"
resourceGroup="msdocs-azure-functions-rg-$randomIdentifier"
tag="create-function-app-connect-to-storage-account"
functionApp="msdocs-serverless-function-$randomIdentifier"
skuStorage="Standard_LRS"
functionsVersion="4"

# Create a resource group
echo "Creating $resourceGroup in "$location"..."
az group create --name $resourceGroup --location "$location" --tags $tag

# Create an Azure storage account in the resource group.
echo "Creating $storage"
az storage account create --name $storage --location "$location" --resource-group $resourceGroup --sku $skuStorage

# Create a serverless function app in the resource group.
echo "Creating $functionApp"
az functionapp create --name $functionApp --resource-group $resourceGroup --storage-account $storage --consumption-plan-location "$location" --functions-version $functionsVersion

# Get the storage account connection string. 
connstr=$(az storage account show-connection-string --name $storage --resource-group $resourceGroup --query connectionString --output tsv)

# Update function app settings to connect to the storage account.
az functionapp config appsettings set --name $functionApp --resource-group $resourceGroup --settings StorageConStr=$connstr
# </FullScript>

# echo "Deleting all resources"
# az group delete --name $resourceGroup -y

清理资源

使用 az group delete 命令删除资源组以及与其关联的所有资源 - 除非你持续需要这些资源。 其中一些资源在创建和删除时可能要稍等片刻。

az group delete --name $resourceGroup

示例参考

此脚本使用以下命令。 表中的每条命令均链接到特定于命令的文档。

命令 说明
az group create 使用相关位置创建资源组。
az storage account create 创建存储帐户。
az functionapp create 在无服务器消耗计划中创建函数应用。
az storage account show-connection-string 获取帐户的连接字符串。
az functionapp config appsettings set 将连接字符串设置为函数应用中的应用设置。

后续步骤

有关 Azure CLI 的详细信息,请参阅 Azure CLI 文档

可以在 Azure Functions 文档中找到其他 Azure Functions CLI 脚本示例。