建立 Web 應用程式並從本機 Git 存放庫部署程式碼

此範例指令碼會在 App Service 中建立 Web 應用程式及其相關資源,然後從本機 Git 存放庫中部署 Web 應用程式程式碼。

您可以視需要使用 Azure PowerShell 指南 中的指示以更新為最新的 Azure PowerShell,然後執行 Connect-AzAccount 來建立與 Azure 的連線。 此外,應用程式程式碼必須認可到本機 Git 儲存機制。

範例指令碼

注意

建議您使用 Azure Az PowerShell 模組來與 Azure 互動。 請參閱安裝 Azure PowerShell 以開始使用。 若要了解如何移轉至 Az PowerShell 模組,請參閱將 Azure PowerShell 從 AzureRM 移轉至 Az

$gitdirectory="<Replace with path to local Git repo>"
$webappname="mywebapp$(Get-Random)"

cd $gitdirectory

# Create a web app and set up Git deployement.
New-AzWebApp -Name $webappname

# Configure GitHub deployment from your GitHub repo and deploy once.
$PropertiesObject = @{
    scmType = "LocalGit";
}
Set-AzResource -Properties $PropertiesObject -ResourceGroupName $webappname `
-ResourceType Microsoft.Web/sites/config -ResourceName $webappname/web `
-ApiVersion 2015-08-01 -Force

# Get publishing profile for the web app
$xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname `
-ResourceGroupName $webappname `
-OutputFile null)

# Extract connection information from publishing profile
$username = $xml.SelectNodes("//publishProfile[@publishMethod=`"MSDeploy`"]/@userName").value
$password = $xml.SelectNodes("//publishProfile[@publishMethod=`"MSDeploy`"]/@userPWD").value

# Set git remote
git remote add azure https://${username}:$password@$webappname.scm.azurewebsites.net:443/$webappname.git

# Push your code to the new Azure remote
git push azure master

清除部署

在執行過指令碼範例之後,您可以使用下列命令來移除資源群組、Web 應用程式和所有相關資源。

Remove-AzResourceGroup -Name $webappname -Force

指令碼說明

此指令碼會使用下列命令。 下表中的每個命令都會連結至命令特定的文件。

Command 注意
New-AzWebApp 建立具有必要資源群組和 App Service 群組的 Web 應用程式。 如果目前的目錄包含 Git 存放庫,也要新增 azure 遠端。
Set-AzResource 修改資源群組中的資源。
Get-AzWebAppPublishingProfile 取得 Web 應用程式的發行設定檔。

下一步

如需有關 Azure PowerShell 模組的詳細資訊,請參閱 Azure PowerShell 文件

您可以在 Azure PowerShell 範例中找到適用於 App Service Web Apps 的其他 Azure PowerShell 範例。