首页 > 解决方案 > 如何在 Github CI/CD 的构建过程中注入环境变量?

问题描述

我正在使用 Gatsby 和 Contentful 创建一个博客网站,用于学习目的。我想部署我的网站以使用 Github 操作来激增。我正在使用gatsby-source-contentful插件在构建时从 Contentful 获取我的内容。该插件需要spaceIdaccessToken访问我的内容空间。在我的本地机器上进行开发期间,我使用保存在.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可以成功配置插件?

标签: environment-variablesgatsbygithub-actionscontentful

解决方案


内容丰富的 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 存储库中,您可以定义一个秘密并将其公开为环境变量。您可以在Github 操作文档中找到更多信息。一旦您通过操作的秘密公开了环境变量,它应该可以正常工作。


推荐阅读