Azure CLI 简单入门

2,048 阅读2分钟

Azure CLI 是什么

Azure 命令行接口 (CLI) 是用于管理 Azure 资源的 Microsoft 跨平台命令行体验。 Azure CLI 易于学习,是构建适用于 Azure 资源的自定义自动化功能的完美工具。

通俗的说就是:可以让我们通过一系列的命令行接口来管理我们的Azure 资源,如部署应用,设置防火墙,数据库导出备份等等。

如何使用

首先我们下载一个 Azure CLI客户端,点这里下载,下载完成后,我们可以通过 Windows PowerShell 查看azure cli 的版本,输入  az --version可查看版本号。
P.S:最新版Azure CLI 的命令都是以 “az”开头,可以通过Windows 命令提示符、Windows PowerShell、**浏览器 + Azure Cloud Shell 等三种方式运行。这里我们使用 Windows PowerShell 这个工具来实现我们的命令。

Part1-登录

登录命令如下:az login  ,如果用到的是由世纪互联运营的中国版Azure ,请先执行 az cloud set -n AzureChinaCloud  以切换到中国区登录。
连接你的账户的命令是:Connect-AzAccount  ,中国区是:Connect-AzAccount -Environment AzureChinaCloud

Part2-部署

这里部署的是一个应用服务

az webapp deployment source config-zip --resource-group GroupName --name AppName --src D:\MyProject\Publish\Publish.zip
  • GroupName 是你的资源组名称
  • AppName 是你的应用名称
  • src 后面的是你的部署文件路径(文件只能是zip)

Part3-数据库

防火墙

这里利用了 这个网址2019.ip138.com/ic.asp 的获取本机IP的接口然后修改对应防火墙规则的IP地址。

param($Server)
$Ip = Invoke-WebRequest -Uri "http://2019.ip138.com/ic.asp"
$str=$null
if ($Ip.StatusCode -eq 200)
{
  [string]$str = $Ip.ParsedHtml.body.innerHTML
  $StartIndex = $str.IndexOf("[")
  $EndIndex = $str.IndexOf("]")
  $length = $EndIndex - $StartIndex - 1
  $ip = $str.Substring($StartIndex + 1, $length)
  $ip
}
else
{
  Write-Warning "Bad Request"
}
az sql server firewall-rule update -g groupname -s $Server -n firefulename --start-ip-address $Ip --end-ip-address $Ip
  • groupname  是你的资源组名称
  • firefulename 是你的防火墙规则名称

备份

若提示登录凭据已失效,中国区需执行:Connect-AzAccount -Environment AzureChinaCloud
再执行以下命令(文中导出路径已固定本地文件夹,可自行调整):

$today=Get-Date
$dbName="yourdbname"
$bacName=$dbName+"-"+$today.ToString('yyyy-M-d-H-m')+".bacpac"
$Secure_String_Pwd=ConvertTo-SecureString "yourpassword" -AsPlainText -Force
$exportRequest = New-AzSqlDatabaseExport -ResourceGroupName YourGroupName -ServerName YourServer -DatabaseName $dbName -StorageKeytype StorageAccessKey -StorageKey storagekeythisVwZJQg4go430testww5S+L3r32OPHxSuzRABCWWCv4N/YWEX6rln8JWUQhckA== -StorageUri https://yourstorage.blob.core.chinacloudapi.cn/database-container/$bacName -AdministratorLogin youraccount -AdministratorLoginPassword $Secure_String_Pwd
$exportRequest
Start-Sleep -s 90
$ctx = New-AzStorageContext -ConnectionString "yourconnectionstringstr"
$ContainerName='yourcontainer'
Get-AzStorageblobcontent -Blob $bacName `
  -Container $containerName `
  -Destination 'D:\yourlocal\backup' `
  -Context $ctx

Part4-存储

导出Blob

$ctx = New-AzStorageContext -ConnectionString "yourconnectionstring"
$bacName="yourblobname"
$ContainerName='yourcontainer'
Get-AzStorageblobcontent -Blob $bacName `
  -Container $containerName `
  -Destination 'D:\yourlocal\backup' `
  -Context $ctx

参考资料