AZD 基础知识 - 了解 Azure Developer CLI AZD 基础知识 - 核心概念与基础 章节导航: 课程主页:AZD 初学者指南 当前章节:第1章 - 基础与快速入门 ⬅️ 上一章:课程概览 ➡️ 下一章:安装与设置 下一章节:第2章:以 AI 为核心的开发 简介 本课程将向您介绍 Azure Developer CLI (azd),这是一款强大的命令行工具,可加速从本地开发到 Azure 部署的过程。您将学习 azd 的基本概念、核心功能,并了解它如何简化云原生应用的部署。
章节导航:
本课程将向您介绍 Azure Developer CLI (azd),这是一款强大的命令行工具,可加速从本地开发到 Azure 部署的过程。您将学习 azd 的基本概念、核心功能,并了解它如何简化云原生应用的部署。
完成本课程后,您将能够:
完成本课程后,您将能够:
Azure Developer CLI (azd) 是一个命令行工具,旨在加速从本地开发到 Azure 部署的过程。它简化了在 Azure 上构建、部署和管理云原生应用的流程。
让我们比较一下部署一个简单的带数据库的 Web 应用:
# Step 1: Create resource group az group create --name myapp-rg --location eastus # Step 2: Create App Service Plan az appservice plan create --name myapp-plan \ --resource-group myapp-rg \ --sku B1 --is-linux # Step 3: Create Web App az webapp create --name myapp-web-unique123 \ --resource-group myapp-rg \ --plan myapp-plan \ --runtime "NODE:18-lts" # Step 4: Create Cosmos DB account (10-15 minutes) az cosmosdb create --name myapp-cosmos-unique123 \ --resource-group myapp-rg \ --kind MongoDB # Step 5: Create database az cosmosdb mongodb database create \ --account-name myapp-cosmos-unique123 \ --resource-group myapp-rg \ --name tododb # Step 6: Create collection az cosmosdb mongodb collection create \ --account-name myapp-cosmos-unique123 \ --resource-group myapp-rg \ --database-name tododb \ --name todos # Step 7: Get connection string CONN_STR=$(az cosmosdb keys list \ --name myapp-cosmos-unique123 \ --resource-group myapp-rg \ --type connection-strings \ --query "connectionStrings[0].connectionString" -o tsv) # Step 8: Configure app settings az webapp config appsettings set \ --name myapp-web-unique123 \ --resource-group myapp-rg \ --settings MONGODB_URI="$CONN_STR" # Step 9: Enable logging az webapp log config --name myapp-web-unique123 \ --resource-group myapp-rg \ --application-logging filesystem \ --detailed-error-messages true # Step 10: Set up Application Insights az monitor app-insights component create \ --app myapp-insights \ --location eastus \ --resource-group myapp-rg # Step 11: Link App Insights to Web App INSTRUMENTATION_KEY=$(az monitor app-insights component show \ --app myapp-insights \ --resource-group myapp-rg \ --query "instrumentationKey" -o tsv) az webapp config appsettings set \ --name myapp-web-unique123 \ --resource-group myapp-rg \ --settings APPINSIGHTS_INSTRUMENTATIONKEY="$INSTRUMENTATION_KEY" # Step 12: Build application locally npm install npm run build # Step 13: Create deployment package zip -r app.zip . -x "*.git*" "node_modules/*" # Step 14: Deploy application az webapp deployment source config-zip \ --resource-group myapp-rg \ --name myapp-web-unique123 \ --src app.zip # Step 15: Wait and pray it works # (No automated validation, manual testing required)
问题:
# Step 1: Initialize from template azd init --template todo-nodejs-mongo # Step 2: Authenticate azd auth login # Step 3: Create environment azd env new dev # Step 4: Preview changes (optional but recommended) azd provision --preview # Step 5: Deploy everything azd up # ✨ Done! Everything is deployed, configured, and monitored
优势:
| 指标 | 手动部署 | AZD 部署 | 改善 |
|---|---|---|---|
| 命令数 | 15+ | 5 | 减少 67% |
| 时间 | 30-45 分钟 | 10-15 分钟 | 快 60% |
| 错误率 | ~40% | <5% | 减少 88% |
| 一致性 | 低(手动) | 100%(自动化) | 完美 |
| 团队入门时间 | 2-4 小时 | 30 分钟 | 快 75% |
| 回滚时间 | 30+ 分钟(手动) | 2 分钟(自动化) | 快 93% |
模板是 azd 的基础。它包含:
环境代表不同的部署目标:
每个环境都有自己的:
服务是您应用的构建模块:
# Browse available templates azd template list # Initialize from a template azd init --template <template-name>
# Complete deployment workflow azd up # Provision + Deploy this is hands off for first time setup # NEW: Preview infrastructure changes before deployment (SAFE) azd provision --preview # Simulate infrastructure deployment without making changes azd provision # Create Azure resources if you update the infrastructure use this azd deploy # Deploy application code or redeploy application code once update azd down # Clean up resources
azd provision --preview 命令是安全部署的变革者:
# Example preview workflow azd provision --preview # See what will change # Review the output, discuss with team azd provision # Apply changes with confidence
工作流说明:
# Create and manage environments azd env new <environment-name> azd env select <environment-name> azd env list
一个典型的 azd 项目结构:
my-app/ ├── .azd/ # azd configuration │ └── config.json ├── .azure/ # Azure deployment artifacts ├── .devcontainer/ # Development container config ├── .github/workflows/ # GitHub Actions ├── .vscode/ # VS Code settings ├── infra/ # Infrastructure code │ ├── main.bicep # Main infrastructure template │ ├── main.parameters.json │ └── modules/ # Reusable modules ├── src/ # Application source code │ ├── api/ # Backend services │ └── web/ # Frontend application ├── azure.yaml # azd project configuration └── README.md
主要项目配置文件:
name: my-awesome-app metadata: template: my-template@1.0.0 services: web: project: ./src/web language: js host: appservice api: project: ./src/api language: js host: appservice hooks: preprovision: shell: pwsh run: echo "Preparing to provision..."
特定环境的配置:
{ "version": 1, "defaultEnvironment": "dev", "environments": { "dev": { "subscriptionId": "your-subscription-id", "location": "eastus" } } }
** 学习提示:** 按顺序完成这些练习,以逐步提升您的 AZD 技能。
目标: 创建一个 AZD 项目并探索其结构
步骤:
# Use a proven template azd init --template todo-nodejs-mongo # Explore the generated files ls -la # View all files including hidden ones # Key files created: # - azure.yaml (main config) # - infra/ (infrastructure code) # - src/ (application code)
✅ 成功: 您拥有 azure.yaml、infra/ 和 src/ 目录
目标: 完成端到端部署
步骤:
# 1. Authenticate az login && azd auth login # 2. Create environment azd env new dev azd env set AZURE_LOCATION eastus # 3. Preview changes (RECOMMENDED) azd provision --preview # 4. Deploy everything azd up # 5. Verify deployment azd show # View your app URL
预计时间: 10-15 分钟
✅ 成功: 应用 URL 在浏览器中打开
目标: 部署到开发和预生产环境
步骤:
# Already have dev, create staging azd env new staging azd env set AZURE_LOCATION westus2 azd up # Switch between them azd env list azd env select dev
✅ 成功: Azure Portal 中有两个独立的资源组
azd down --force --purge当您需要完全重置时:
azd down --force --purge
它的作用:
--force:无确认提示--purge:删除所有本地状态和 Azure 资源使用场景:
# Method 1: Use existing template azd init --template todo-nodejs-mongo # Method 2: Start from scratch azd init # Method 3: Use current directory azd init .
# Set up development environment azd auth login azd env new dev azd env select dev # Deploy everything azd up # Make changes and redeploy azd deploy # Clean up when done azd down --force --purge # command in the Azure Developer CLI is a **hard reset** for your environment—especially useful when you're troubleshooting failed deployments, cleaning up orphaned resources, or prepping for a fresh redeploy.
azd down --force --purgeazd down --force --purge 命令是完全拆除 azd 环境及所有相关资源的强大方式。以下是每个标志的作用:
--force
--purge
删除 所有相关元数据,包括:
环境状态
本地 .azure 文件夹
缓存的部署信息
防止 azd "记住" 之前的部署,这可能导致资源组不匹配或过时的注册表引用问题。
当您因遗留状态或部分部署问题而在 azd up 上遇到障碍时,这个组合可以确保 干净的开始。
它在手动删除 Azure Portal 中的资源后,或切换模板、环境或资源组命名约定时特别有用。
# Create staging environment azd env new staging azd env select staging azd up # Switch back to dev azd env select dev # Compare environments azd env list
理解身份验证对于成功的 azd 部署至关重要。Azure 使用多种身份验证方法,而 azd 利用与其他 Azure 工具相同的凭据链。
az login)在使用 azd 之前,您需要通过 Azure 进行身份验证。最常见的方法是使用 Azure CLI:
# Interactive login (opens browser) az login # Login with specific tenant az login --tenant <tenant-id> # Login with service principal az login --service-principal -u <app-id> -p <password> --tenant <tenant-id> # Check current login status az account show # List available subscriptions az account list --output table # Set default subscription az account set --subscription <subscription-id>
DefaultAzureCredential 是一种凭据类型,通过自动尝试特定顺序的多个凭据源提供简化的身份验证体验:
# Set environment variables for service principal export AZURE_CLIENT_ID="<app-id>" export AZURE_CLIENT_SECRET="<password>" export AZURE_TENANT_ID="<tenant-id>"
自动用于:
适用于 Azure 资源,例如:
# Check if running on Azure resource with managed identity az account show --query "user.type" --output tsv # Returns: "servicePrincipal" if using managed identity
az login 凭据(本地开发最常用)# Method 1: Use Azure CLI (Recommended for development) az login azd auth login # Uses existing Azure CLI credentials # Method 2: Direct azd authentication azd auth login --use-device-code # For headless environments # Method 3: Check authentication status azd auth login --check-status # Method 4: Logout and re-authenticate azd auth logout azd auth login
# 1. Login with Azure CLI az login # 2. Verify correct subscription az account show az account set --subscription "Your Subscription Name" # 3. Use azd with existing credentials azd auth login
# GitHub Actions example - name: Azure Login uses: azure/login@v1 with: creds: ${{ secrets.AZURE_CREDENTIALS }} - name: Deploy with azd run: | azd auth login --client-id ${{ secrets.AZURE_CLIENT_ID }} \ --client-secret ${{ secrets.AZURE_CLIENT_SECRET }} \ --tenant-id ${{ secrets.AZURE_TENANT_ID }} azd up --no-prompt
# Solution: Set default subscription az account list --output table az account set --subscription "<subscription-id>" azd env set AZURE_SUBSCRIPTION_ID "<subscription-id>"
# Solution: Check and assign required roles az role assignment list --assignee $(az account show --query user.name --output tsv) # Common required roles: # - Contributor (for resource management) # - User Access Administrator (for role assignments)
# Solution: Re-authenticate az logout az login azd auth logout azd auth login
# Personal development account az login azd auth login
# Use specific tenant for organization az login --tenant contoso.onmicrosoft.com azd auth login
# Switch between tenants az login --tenant tenant1.onmicrosoft.com # Deploy to tenant 1 azd up az login --tenant tenant2.onmicrosoft.com # Deploy to tenant 2 azd up
# Debug authentication issues azd auth login --check-status az account show az account get-access-token # Common diagnostic commands whoami # Current user context az ad signed-in-user show # Azure AD user details az group list # Test resource access
azd down --force --purgeazd template list # Browse templates azd template show <template> # Template details azd init --help # Initialization options
azd show # Project overview azd env show # Current environment azd config list # Configuration settings
azd monitor # Open Azure portal azd pipeline config # Set up CI/CD azd logs # View application logs
# Good azd env new production-east azd init --template web-app-secure # Avoid azd env new env1 azd init --template template1
** 继续学习第1章:**
** 准备好进入下一章了吗?**
问:AZD 和 Azure CLI 有什么区别?
答:Azure CLI (az) 用于管理单个 Azure 资源,而 AZD (azd) 用于管理整个应用程序:
# Azure CLI - Low-level resource management az webapp create --name myapp --resource-group rg az sql server create --name myserver --resource-group rg # ...many more commands needed # AZD - Application-level management azd up # Deploys entire app with all resources
可以这样理解:
az = 操作单个乐高积木azd = 操作完整的乐高套装问:使用 AZD 需要了解 Bicep 或 Terraform 吗?
答:不需要!可以从模板开始:
# Use existing template - no IaC knowledge needed azd init --template todo-nodejs-mongo azd up
之后可以学习 Bicep 来定制基础设施。模板提供了可学习的工作示例。
问:运行 AZD 模板需要多少钱?
答:费用因模板而异。大多数开发模板每月费用在 $50-150 之间:
# Preview costs before deploying azd provision --preview # Always cleanup when not using azd down --force --purge # Removes all resources
小贴士: 使用免费层(如果有):
问:我可以将 AZD 与现有的 Azure 资源一起使用吗?
答:可以,但从头开始会更容易。AZD 在管理完整生命周期时效果最佳。对于现有资源:
# Option 1: Import existing resources (advanced) azd init # Then modify infra/ to reference existing resources # Option 2: Start fresh (recommended) azd init --template matching-your-stack azd up # Creates new environment
问:如何与团队成员共享我的项目?
答:将 AZD 项目提交到 Git(但不要提交 .azure 文件夹):
# Already in .gitignore by default .azure/ # Contains secrets and environment data *.env # Environment variables # Team members then: git clone <your-repo> azd auth login azd env new <their-name>-dev azd up
每个人都可以从相同的模板中获得相同的基础设施。
问:“azd up” 中途失败了。我该怎么办?
答:检查错误,修复后重试:
# View detailed logs azd show # Common fixes: # 1. If quota exceeded: azd env set AZURE_LOCATION "westus2" # Try different region # 2. If resource name conflict: azd down --force --purge # Clean slate azd up # Retry # 3. If auth expired: az login azd auth login azd up
最常见的问题: 选择了错误的 Azure 订阅
az account list --output table az account set --subscription "<correct-subscription>"
问:如何仅部署代码更改而不重新配置?
答:使用 azd deploy 而不是 azd up:
azd up # First time: provision + deploy (slow) # Make code changes... azd deploy # Subsequent times: deploy only (fast)
速度对比:
azd up:10-15 分钟(配置基础设施)azd deploy:2-5 分钟(仅代码)问:我可以自定义基础设施模板吗?
答:可以!编辑 infra/ 中的 Bicep 文件:
# After azd init cd infra/ code main.bicep # Edit in VS Code # Preview changes azd provision --preview # Apply changes azd provision
提示: 从小处开始 - 先更改 SKU:
// infra/main.bicep sku: { name: 'B1' // Change to 'P1V2' for production }
问:如何删除 AZD 创建的所有内容?
答:一个命令即可删除所有资源:
azd down --force --purge # This deletes: # - All Azure resources # - Resource group # - Local environment state # - Cached deployment data
务必在以下情况下运行此命令:
节省成本: 删除未使用的资源 = $0 费用
问:如果我在 Azure 门户中意外删除了资源怎么办?
答:AZD 状态可能会不同步。建议采用清理重置的方法:
# 1. Remove local state azd down --force --purge # 2. Start fresh azd up # Alternative: Let AZD detect and fix azd provision # Will create missing resources
问:我可以在 CI/CD 流水线中使用 AZD 吗?
答:可以!GitHub Actions 示例:
# .github/workflows/deploy.yml name: Deploy with AZD on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install azd run: curl -fsSL https://aka.ms/install-azd.sh | bash - name: Azure Login run: | azd auth login \ --client-id ${{ secrets.AZURE_CLIENT_ID }} \ --client-secret ${{ secrets.AZURE_CLIENT_SECRET }} \ --tenant-id ${{ secrets.AZURE_TENANT_ID }} - name: Deploy run: azd up --no-prompt
问:如何处理机密和敏感数据?
答:AZD 自动集成 Azure Key Vault:
# Secrets are stored in Key Vault, not in code azd env set DATABASE_PASSWORD "$(openssl rand -base64 32)" # AZD automatically: # 1. Creates Key Vault # 2. Stores secret # 3. Grants app access via Managed Identity # 4. Injects at runtime
切勿提交:
.azure/ 文件夹(包含环境数据).env 文件(本地机密)问:我可以部署到多个区域吗?
答:可以,为每个区域创建一个环境:
# East US environment azd env new prod-eastus azd env set AZURE_LOCATION eastus azd up # West Europe environment azd env new prod-westeurope azd env set AZURE_LOCATION westeurope azd up # Each environment is independent azd env list
对于真正的多区域应用,定制 Bicep 模板以同时部署到多个区域。
问:如果遇到问题,我可以在哪里寻求帮助?
azure-developer-cli小贴士: 在提问前运行:
azd show # Shows current state azd version # Shows your version
在问题中包含这些信息以加快帮助速度。
你现在已经了解了 AZD 的基础知识。选择你的路径:
azd init --template get-started-with-ai-chat 开始章节导航:
免责声明:
本文档使用AI翻译服务Co-op Translator进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。原始语言的文档应被视为权威来源。对于关键信息,建议使用专业人工翻译。我们对因使用此翻译而产生的任何误解或误读不承担责任。