使用 Azure CLI 建立單一資料庫並設定防火牆規則Use the Azure CLI to create a single database and configure a firewall rule

適用於: Azure SQL Database

此 Azure CLI 指令碼範例會在 Azure SQL Database 中建立單一資料庫,並設定伺服器層級防火牆規則。This Azure CLI script example creates a single database in Azure SQL Database and configures a server-level firewall rule. 成功執行指令碼後,即可從所有 Azure 服務與所設定的 IP 位址存取資料庫。After the script has been successfully run, the database can be accessed from all Azure services and the configured IP address.

如果您選擇在本機安裝和使用 CLI,本主題會要求您執行 Azure CLI 2.0 版或更新版本。If you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.0 or later. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級,請參閱安裝 Azure CLIIf you need to install or upgrade, see Install the Azure CLI.

範例指令碼Sample script

登入 AzureSign in to Azure

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

執行指令碼Run the script

#!/bin/bash
location="East US"
randomIdentifier=random123

resource="resource-$randomIdentifier"
server="server-$randomIdentifier"
database="database-$randomIdentifier"

login="sampleLogin"
password="samplePassword123!"

startIP=0.0.0.0
endIP=0.0.0.0

echo "Creating $resource..."
az group create --name $resource --location "$location"

echo "Creating $server in $location..."
az sql server create --name $server --resource-group $resource --location "$location" --admin-user $login --admin-password $password

echo "Configuring firewall..."
az sql server firewall-rule create --resource-group $resource --server $server -n AllowYourIp --start-ip-address $startIP --end-ip-address $endIP

echo "Creating $database on $server..."
az sql db create --resource-group $resource --server $server --name $database --sample-name AdventureWorksLT --edition GeneralPurpose --family Gen4 --capacity 1 --zone-redundant false # zone redundancy is only supported on premium and business critical service tiers

清除部署Clean up deployment

使用下列命令來移除資源群組及其所有相關聯的資源。Use the following command to remove the resource group and all resources associated with it.

az group delete --name $resource

範例參考Sample reference

此指令碼會使用下列命令。This script uses the following commands. 下表中的每個命令都會連結至命令特定的文件。Each command in the table links to command-specific documentation.

CommandCommand 描述Description
az sql serveraz sql server 伺服器命令Server commands
az sql server firewallaz sql server firewall 伺服器防火牆命令。Server firewall commands.
az sql dbaz sql db 資料庫命令。Database commands.

後續步驟Next steps

如需 Azure CLI 的詳細資訊,請參閱 Azure CLI 文件For more information on the Azure CLI, see Azure CLI documentation.

其他的 SQL Database CLI 指令碼範例可於 Azure SQL Database 文件中找到。Additional SQL Database CLI script samples can be found in the Azure SQL Database documentation.