You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Azure Static Web Apps GitHub Action生成的预览环境appsettings

自动修改Azure Static Web Apps PR预览环境的App Settings

以下是几种无需手动在Azure门户操作的解决方案:

方法1:通过GitHub Action结合Azure CLI自动设置

每个PR预览环境的命名规则固定为 <你的静态应用名>-pr-<PR编号>,可以在CI/CD流程中添加步骤,用Azure CLI批量设置应用配置:

  1. 在GitHub仓库的Secrets and variables中添加Azure服务主体凭据(命名为AZURE_CREDENTIALS),用于授权访问Azure资源。
  2. 打开现有的Static Web Apps部署Workflow文件,在部署步骤后添加以下内容:
- name: 登录Azure并设置预览环境配置
  uses: azure/login@v1
  with:
    creds: ${{ secrets.AZURE_CREDENTIALS }}
- run: |
    az staticwebapp appsettings set \
      --name "你的静态应用名称-pr-${{ github.event.number }}" \
      --setting-names "API_URL=https://preview-api.example.com" "ENVIRONMENT=Preview"

注意:确保服务主体拥有Microsoft.Web/staticSites/configure/action权限,否则无法修改应用配置。

方法2:通过配置文件模板+环境变量替换

如果你的应用支持从staticwebapp.config.json读取配置,可以用模板文件生成对应环境的配置:

  1. 在项目根目录创建模板文件staticwebapp.config.template.json,内容示例:
{
  "routes": [],
  "appSettings": {
    "API_URL": "{{API_URL}}",
    "ENVIRONMENT": "{{ENVIRONMENT}}"
  }
}
  1. 在Workflow中添加替换步骤,生成最终的配置文件:
- name: 生成预览环境配置文件
  run: |
    sed -e 's/{{API_URL}}/${{ secrets.PREVIEW_API_URL }}/g' \
        -e 's/{{ENVIRONMENT}}/Preview/g' \
        staticwebapp.config.template.json > staticwebapp.config.json

部署时,生成的staticwebapp.config.json会被自动应用到预览环境。

方法3:直接通过部署Action的参数传递

使用azure/static-web-apps-deploy Action的app_settings参数,在部署时直接传入预览环境的配置:

- name: 部署到Azure Static Web Apps预览环境
  uses: azure/static-web-apps-deploy@v1
  with:
    azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
    repo_token: ${{ secrets.GITHUB_TOKEN }}
    action: "upload"
    app_location: "/" # 你的前端代码目录
    api_location: "api" # 若有API函数则填写,否则留空
    output_location: "dist" # 前端构建产物目录
    app_settings: |
      API_URL=https://preview-api.example.com
      ENVIRONMENT=Preview

此方法无需额外CLI步骤,直接在部署阶段完成配置注入,适合大多数场景。

内容的提问来源于stack exchange,提问作者Boris Callens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:56:13