Netlify上的分支特定环境变量

Fel*_*ger 5 git deployment environment-variables static-html netlify

我们正在为所有推送的git分支使用Netlify的自动部署.

我们希望仅将分析脚本(等)包含在主分支中,即我们的用户正在访问的网站版本.

可以在Netlify上构建环境变量,但如果可以区分某些分支的变量,我不会得到它们吗?

tal*_*ves 6

有一种方法可以根据netlify.toml文件中Netlify中的部署上下文设置环境变量.这是在使用Hugo的生产站点中使用的,但您可以使用所需的任何键来获取变量和命令.

一个例子 netlify.toml

# Global settings applied to the whole site.
[build]
  command = "yarn build"
  publish = "public"

# build a preview of the site (Drafts and Future dates also)
[context.deploy-preview]
  command = "yarn build:preview"

[build.environment]
  HUGO_ENV = "development"

[context.production.environment]
  HUGO_VERSION = "0.29"
  HUGO_ENV = "production"
# you can lock a version of hugo for a deploy preview
[context.deploy-preview.environment]
  HUGO_VERSION = "0.29"
  HUGO_ENV = "deploy" # TEST: should be deploy or something other than production
# you can lock a version of hugo for a branch-deploy (other than previews)
[context.branch-deploy.environment]
  HUGO_VERSION = "0.30"
  HUGO_ENV = "development"
Run Code Online (Sandbox Code Playgroud)

同时针对特定分支(例如:new-branch)

# build a preview of the site (Drafts and Future dates also)
[context.new-branch]
  command = "yarn build:preview"

# you can also target a specific branch
[context.new-branch.environment]
  HUGO_VERSION = "0.29"
  HUGO_ENV = "deploy" # TEST: should be deploy or something other than production
Run Code Online (Sandbox Code Playgroud)

解决方案:现在将有一个名为的环境变量HUGO_ENV,它具有一个值来了解定义的上下文(生产,开发,部署).构建语言现在可以访问这些变量,以便对构建结果中包含的内容做出决策.

注意:

  • 使用您需要的任何env变量名称和值.该示例以Hugo静态站点生成器为目标,该生成器具有getenv检索值的功能.
  • 我还没有测试使用context.branch-deploy如何定位自定义分支,所以要小心这些上下文的覆盖.
  • netlify.toml覆盖在Netlify站点上输入到浏览器控制台中的环境变量中指定的任何变量.

  • 对于无法提交到 netlify.toml 文件的秘密 env 变量,您将如何执行此操作?/ (3认同)