简体   繁体   中英

Cloud Build env variables not passed to Django app on GAE

I have a Django app running on Google AppEngine Standard environment. I've set up a cloud build trigger from my master branch in Github to run the following steps:

steps:
  - name: 'python:3.7'
    entrypoint: python3
    args: ['-m', 'pip', 'install', '--target', '.', '--requirement', 'requirements.txt']
  - name: 'python:3.7'
    entrypoint: python3
    args: ['./manage.py', 'collectstatic', '--noinput']
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['app', 'deploy', 'app.yaml']
    env:
    - 'SHORT_SHA=$SHORT_SHA'
    - 'TAG_NAME=$TAG_NAME'

I can see under the Execution Details tab on Cloud Build that the variables were actually set.

The problem is, SHORT_SHA and TAG_NAME aren't accessible from my Django app (followed instructions at https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values#using_user-defined_substitutions ). But if I set them in my app.yaml file with hardcoded values under env_variables , then my Django app can access those hardcoded values (and the values set in my build don't overwrite those hardcoded in app.yaml).

Why is this? Am I accessing them/setting them incorrectly? Should I be setting them in app.yaml somehow?

I even printed the whole os.environ dictionary in one of my views to see if they were just there with different names or something, but they're not present in there.

Not the cleanest solution, but I used this medium post as a guidance to my solution. I hypothesize that runserver command isn't being passed those env variables, and that those variables are only used for the app deploy command.

  1. Write a Python script to dump the current environment variables in a .env file in project dir
  2. In your settings file, read env variables from the.env file (I used django-environ library for this)
  3. Add a step to cloud build file that runs your new Python script and pass env variables in that step (you're essentially dumping these variables into a .env file in this step)
  - name: 'python:3.7'
    entrypoint: python3
    args: ['./create_env_file.py']
    env:
    - 'SHORT_SHA=$SHORT_SHA'
    - 'TAG_NAME=$TAG_NAME'
  1. Set the variables through Substitution Variables section in Edit Trigger page in Cloud Build
  2. Now your application should have these env variables when app deploy happens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM