简体   繁体   English

如何在 Google App Engine 标准环境中使用 Google Cloud Build 或其他方法设置环境变量?

[英]How to set environment variables using Google Cloud Build or other method in Google App Engine Standard Environment?

Is there anyway to inject environment variables from Cloud Build into the App Engine Standard environment?无论如何将 Cloud Build 中的环境变量注入 App Engine 标准环境?

I do not want to push my environment variables to GitHub inside the app.yaml or .env .我不想将我的环境变量推送到app.yaml.env Thus, when Cloud Build pulls and deploys it is missing the .env file and the server is unable to complete some requests.因此,当 Cloud Build 拉取和部署时,它缺少.env文件并且服务器无法完成某些请求。

I am trying to avoid using Datastore as the async nature of Datastore will make the code a lot more messy.我试图避免使用 Datastore,因为 Datastore 的异步特性会使代码更加混乱。 I tried to use encrypted secrets found here , but that doesn't seem to work as I added the secrets to app deploy and they do not make their way into the deployment, so I assume this is not the use case for Cloud Build.我尝试使用在此处找到的加密机密,但这似乎不起作用,因为我将机密添加到应用程序部署中并且它们没有进入部署,因此我认为这不是 Cloud Build 的用例。

I also tried the tutorial here , to import the .env file into App Engine Standard from storage, but since Standard does not have local storage I assume it goes into the void.我还尝试了此处的教程,将.env文件从存储导入 App Engine Standard,但由于 Standard 没有本地存储,我认为它无效。

So is there anyway to inject the .env into App Engine Standard environment without using Datastore, or committing app.yaml or .env to change control?那么,是否可以在不使用 Datastore 或提交app.yaml.env来更改控制的情况下将.env注入 App Engine 标准环境? Potentially using Cloud Build, KMS, or some type of storage?可能使用 Cloud Build、KMS 或某种类型的存储?

Here is what I tried for cloudbuild.yaml :这是我为cloudbuild.yaml的尝试:

steps:
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy"]
  secretEnv: ['SECRET1', 'SECRET2', 'SECRET3', 'SECRET4', 'SECRET5']
timeout: "1600s"

secrets:
- kmsKeyName: projects/<Project-Name>/locations/global/keyRings/<Key-Ring-Name>/cryptoKeys/<Key-Name>
  secretEnv:
    SECRET1: <encrypted-key-base64 here>
    SECRET2: <encrypted-key-base64 here>
    SECRET3: <encrypted-key-base64 here> 
    SECRET4: <encrypted-key-base64 here> 
    SECRET5: <encrypted-key-base64 here>

Here is a tutorial on how to securely store env vars in your cloud build (triggers) settings and import them into your app.这是一个关于如何在您的云构建(触发器)设置中安全地存储环境变量并将它们导入您的应用程序的教程

Basically there are three steps:基本上分为三个步骤:

  1. Add your env vars to the 'variables' section in one of your build trigger settings将您的环境变量添加到构建触发器设置之一的“变量”部分

    Screenshot of where to add variables in build triggers在构建触发器中添加变量的位置的屏幕截图

    By convention variables set in the build trigger must begin with an underscore (_)按照惯例,在构建触发器中设置的变量必须以下划线 (_) 开头

  2. Configure cloudbuild.yaml (on the second step in the code example) to read in variables from your build trigger, set them as env vars, and write all env vars in a local .env file配置cloudbuild.yaml (在代码示例的第二步)以从构建触发器中读取变量,将它们设置为 env vars,并将所有 env vars 写入本地 .env 文件中

    Add couldbuild.yaml (below) to your project root directorycouldbuild.yaml (如下)添加到您的项目根目录

 steps: - name: node:10.15.1 entrypoint: npm args: ["install"] - name: node:10.15.1 entrypoint: npm args: ["run", "create-env"] env: - 'MY_SECRET_KEY=${_MY_SECRET_KEY}' - name: "gcr.io/cloud-builders/gcloud" args: ["app", "deploy"] timeout: "1600s"

Add create-env script to package.jsoncreate-env脚本添加到package.json

 "scripts": { "create-env": "printenv > .env" },

  1. Read env vars from .env to your app (config.js)将 .env 中的 env vars 读取到您的应用程序 (config.js)

    Install dotenv package安装 dotenv 包

    npm i dotenv -S

    Add a config.js to your appconfig.js添加到您的应用程序

 // Import all env vars from .env file require('dotenv').config() export const MY_SECRET_KEY = process.env.MY_SECRET_KEY console.log(MY_SECRET_KEY) // => Hello

Done!完毕! Now you may deploy your app by triggering the cloud build and your app will have access to the env vars.现在您可以通过触发云构建来部署您的应用程序,您的应用程序将可以访问环境变量。

I have another solution, if someone is still interested in this.如果有人仍然对此感兴趣,我还有另一个解决方案。 This should work on all languages, because environment variables are added directly into app.yaml file这应该适用于所有语言,因为环境变量直接添加到app.yaml文件中

  1. Add substitution variable in build trigger (as described in this answer ).在构建触发器中添加替换变量(如本答案所述)。

  2. Add environment variables to app.yaml in a way they can be easily substituted with build trigger variables.以一种可以轻松替换为构建触发器变量的方式将环境变量添加到app.yaml Like this:像这样:

    env_variables:
     SECRET_KEY: %SECRET_KEY%
  1. Add a step in cloudbuild.yaml to substitute all %XXX% variables inside app.yaml with their values from build trigger.cloudbuild.yaml添加一个步骤,将app.yaml所有%XXX%变量替换为它们来自构建触发器的值。
    - name: 'gcr.io/cloud-builders/gcloud'
      entrypoint: bash
      args:
      - '-c'
      - |
      sed -i 's/%SECRET_KEY%/'${_SECRET_KEY}'/g' app.yaml
      gcloud app deploy  app.yaml

The highfivebrian answer is great, but I'm adding my slightly different solution. highfivebrian 的回答很好,但我要添加我略有不同的解决方案。

1). 1). In the root project folder we need the cloudbuild.yaml file but I'll call it buildsetttings.yaml , because first one name have a problem在根项目文件夹中,我们需要 cloudbuild.yaml 文件,但我将其命名为buildsetttings.yaml ,因为第一个名称有问题

In buildsetttings.yaml I added this code:在 buildsetttings.yaml 我添加了这段代码:

 steps: - name: node entrypoint: npm args: ['install'] - name: node entrypoint: npm env: - 'DB_URL=${_DB_URL}' - 'SENDGRID_API_KEY=${_SENDGRID_API_KEY}' - 'CLIENT_ID=${_CLIENT_ID}' args: ['run', 'create-app-yaml'] - name: 'gcr.io/cloud-builders/gcloud' args: ['app', 'deploy']

buildsetttings.yaml will be create app.yaml file in the Cloud Build, using a npm create-app-yaml command. buildsetttings.yaml 将使用 npm create-app-yaml命令在 Cloud Build 中创建 app.yaml 文件。 Tip: app.yaml file we will then use to deploy our app to GCP App Engine.提示:我们随后将使用 app.yaml 文件将我们的应用程序部署到 GCP App Engine。

2). 2). In the root folder(near buildsetttings.yaml) we need to create create-app-yaml.js which will run in Cloud Build after it is called from buildsetttings.yaml.在根文件夹(靠近 buildsetttings.yaml)中,我们需要创建create-app-yaml.js ,它将在从 buildsetttings.yaml 调用后在 Cloud Build 中运行。

In buildsetttings.yaml I added this code:在 buildsetttings.yaml 我添加了这段代码:

 require('dotenv').config(); const fs = require('fs'); const appYamlContent = `runtime: nodejs14 env_variables: DB_URL: ${process.env.DB_URL} SENDGRID_API_KEY: ${process.env.SENDGRID_API_KEY} CLIENT_ID: ${process.env.CLIENT_ID}`; fs.writeFileSync('./app.yaml', appYamlContent);

This code using a npm package dotenv (add it to package.json) and get variables from Cloud Build Trigger Variables and create with they app.yaml file.此代码使用 npm package dotenv (将其添加到 package.json)并从 Cloud Build Trigger Variables 获取变量并使用它们创建 app.yaml 文件。

3). 3). app.yaml file was created in the Cloud build and our last step(name: 'gcr.io/cloud-builders/gcloud') in the buildsetttings.yaml, using app.yaml file, deploy the project to the Google Cloud App Engine. app.yaml 文件是在 Cloud build 中创建的,我们的最后一步(名称:'gcr.io/cloud-builders/gcloud')在 buildsetttings.yaml 中使用 app.yaml 文件将项目部署到 Google Cloud App Engine .

Success!成功!

In short, it works like this : buildsetttings.yaml run "create-app-yaml.js" in the Cloud Build, after which dynamically creates an app.yaml file by adding variables from Cloud Build Trigger Variables, then makes a deployment in the App Engine.简而言之,它是这样工作的:buildsetttings.yaml 在 Cloud Build 中运行“create-app-yaml.js”,然后通过从 Cloud Build Trigger Variables 添加变量动态创建 app.yaml 文件,然后在 Cloud Build 中进行部署应用引擎。

Notes:笔记:

  • Delete the file app.yamlin from you project, because it will be create dynamically in the Cloud Build.从您的项目中删除文件 app.yamlin,因为它将在 Cloud Build 中动态创建。 Also delete cloudbuild.yaml file, because instead we use buildsetttings.yaml.同时删除 cloudbuild.yaml 文件,因为我们使用 buildsetttings.yaml。

  • package.json: package.json:

代码

  • Cloud Build Trigger Variables:云构建触发器变量:

GCP 构建云 nodejs

As of 2020/11/13 .截至2020/11/13 It seem like .env will work only at that step and in the next step an invisible .env will no longer there.似乎.env只会在那一步起作用,而在下一步中,一个不可见的.env将不再存在。

If you get stuck do try consume that printed .env it in 1 step like this...如果你遇到困难,请尝试像这样在 1 步中使用打印的.env ......
in cloudbuild.yamlcloudbuild.yaml

# [START cloudbuild_yarn_node]
steps:
  # Install
  - name: node
    entrypoint: yarn
    args: ["install"]
  # Build
  - name: node
    entrypoint: yarn
    env:
      - "FOO=${_FOO}"
    args: ["env-build"]

and in package.json add thispackage.json添加这个

{
  "scripts": {
    "env-build": "printenv > .env && yarn build",
  }
}

in index.jsindex.js

require('dotenv').config();
console.log(process.env.FOO);

Took me an hour to figure this out.我花了一个小时才弄明白。

First, I created secret using gcp secret manager and uploaded my env file there.首先,我使用 gcp secret manager 创建了 secret 并在那里上传了我的 env 文件。 Second, I called the secret in cloudbuild.yaml on run time and created a file with name of '.env' using echo.其次,我在运行时调用了 cloudbuild.yaml 中的秘密,并使用 echo 创建了一个名为“.env”的文件。

Example例子

steps: 
- id: "Injecting ENV"
  name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: bash
  args:
      - '-c'
      - |
        echo $$ENV > .env
  secretEnv: ['ENV']


availableSecrets: 
  - versionName: projects/<Project-Name>/secrets/environment-variables/versions/1
    env: 'ENV'
timeout: 900s

Based on your preferences that you have highlighted (Cloud Build, KMS).根据您突出显示的首选项(Cloud Build、KMS)。 The Google Secrets link that you had mentioned involves storing sensitive data at build or runtime using Cloud KMS : KeyRing and CryptoKey.您提到的 Google Secrets 链接涉及使用Cloud KMS在构建或运行时存储敏感数据:KeyRing 和 CryptoKey。 However, Google offers other Secret Management Solutions using Cloud KMS as well.但是,Google 也使用 Cloud KMS 提供其他机密管理解决方案。

Here are a couple of other options you can use while storing Secrets :以下是您在存储 Secrets 时可以使用的其他几个选项:

Option 1 : You can store Secrets in code that are encrypted with a key from Cloud KMS.选项 1 :您可以将Secret存储使用 Cloud KMS 中的密钥加密的代码 (This is typically used by encrypting your secret at the application layer.) (这通常用于在应用程序层加密您的秘密。)

Benefit: Provides a layer of security from insider threats because it restricts access to the code with a corresponding key .优点:提供一层安全防范内部威胁,因为它使用相应的密钥限制对代码的访问

[You can find some additional information about these options on the Google Documentation here .] [您可以在此处的 Google 文档中找到有关这些选项的一些其他信息。]

Option 2: You can Store Secrets inside a Google Storage Bucket where your data is at rest encryption.选项 2:您可以将Secrets存储在 Google Storage Bucket 中,您的数据在其中进行静态加密。 (Similar to option 1 this has the ability to limit access to secrets to a small group of Developers.) (与选项 1 类似,它可以将机密访问权限限制为一小组开发人员。)

Benefit: Storing your secrets in a separate location ensures that if a breach of your code repository has occurred , your secrets may still be protected .)好处:单独的位置确保,如果发生违反您的代码库,你的秘密可能仍然会受到保护存储你的秘密)。

[Note: Google recommends that you use two projects for proper separation of duties . [注意:Google 建议您使用两个项目进行适当的职责分离 One project will use Cloud KMS to manage the keys and the other project will use Cloud Storage to store the secrets.]一个项目将使用 Cloud KMS 来管理密钥,而另一个项目将使用 Cloud Storage 来存储机密。]

If the options listed above still do not meet your needs, I have found a StackOverflow question that shares a similar objective as your project.如果上面列出的选项仍然不能满足您的需求,我发现了一个StackOverflow 问题,它与您的项目有着相似的目标。 (ie: Storing environment variables in GAE without Datastore) (即:在没有Datastore 的情况下在 GAE 中存储环境变量)

The solution provided on this link illustrates the use of storing keys in a client_secrets.json file that gets excluded when uploading to git by listing it in .gitignore.链接上提供的解决方案说明了在 client_secrets.json 文件中存储密钥的用法,该文件在上传到 git 时被排除在 .gitignore 中。 You can find some Google examples (Python) of usage here .您可以在此处找到一些Google 使用示例(Python)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有 4GB RAM 的 Google Cloud Platform App Engine 标准环境 - Google Cloud Platform App Engine Standard environment with 4GB RAM 谷歌云构建和部署到 Kubernetes 环境变量 - Google Cloud Build and Deploy to Kubernetes environment variables Google App Engine 如何从灵活环境转变为标准环境 - How do change from Google App Engine from Flexible Environment to Standard environment 如何在 Google App Engine 柔性环境中设置 jetty 线程池 - how to set the jetty thread pool in Google App Engine flexible environment 根据另一个环境变量设置 Google Cloud Run 环境变量值 - Set Google Cloud Run environment variables value based on another environment variable 使用 appengine “django.core.exceptions.ImproperlyConfigured:设置 SECRET_KEY 环境变量”在 Google 云上部署 Django 应用程序时出错 - Error in deploying Django app on Google cloud using appengine "django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable" 将 App Engine flexible 降级到 App Engine 标准环境 - Downgrade App engine flexible to app engine standard environment 如何使用 go 1.11 和 Google App Engine Standard 验证私有 Go 模块 - How to authenticate a private Go Module using go 1.11 and Google App Engine Standard 无法在 App Engine 标准环境 (GCP) 中部署预构建映像 - Unable to deploy pre built image in app engine standard environment (GCP) 我应该使用哪种开发环境来使用 Python 开发 Google App Engine? - Which development environment should I use for developing Google App Engine with Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM