如何在 Github CI/CD 的构建过程中注入环境变量?

How can I inject environment variables during the build process in Github CI/CD?

出于学习目的,我正在使用 Gatsby 和 Contentful 创建一个博客网站。我想使用 Github 操作部署我的网站以激增。我正在使用 gatsby-source-contentful 插件在构建时从 Contentful 获取我的内容。该插件需要 spaceIdaccessToken 才能访问我的 Contenful space。在我的本地机器上开发期间,我使用保存在 .env 文件中的环境变量向插件提供这些值。

但是,在 Github 操作的构建过程中,我收到此错误:

success open and validate gatsby-configs - 2.325s
error Invalid plugin options for "gatsby-source-contentful":

- "accessToken" is required
- "spaceId" is required
not finished load plugins - 1.002s
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! gatsby-contentful-blogsite@0.1.0 build: `tsc && gatsby build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the gatsby-contentful-blogsite@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/runner/.npm/_logs/2021-02-18T17_53_11_281Z-debug.log
Error: Process completed with exit code 1.

有没有办法告诉Github关于这些环境变量(spaceIdaccessToken)的操作,以便gatsby-source-contentful插件可以配置成功?

此处内容丰富的 DevRel。

// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: `your_space_id`,
        // Learn about environment variables: https://gatsby.dev/env-vars
        accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
      },
    },
  ],
}

在你的 gatsby 配置中,你可以像上面那样指定你的环境变量。然后在您的 GitHub 存储库中,您可以定义一个秘密并将其公开为环境变量。您可以在 the Github actions docs 中找到更多信息。通过操作的秘密公开环境变量后,它应该可以正常工作。