python - CircleCI 没有获取运行步骤中定义的环境变量?

标签 python django yaml circleci

我正在尝试为 Django 项目运行 CircleCI 测试,其中 manage.py 确定要应用的 settings.py 版本(development. pystaging.pyproduction.py)来自环境变量 ENV_ROLE。以前,ENV_ROLE 如果未定义则默认设置为 development,但我正在更改它以便 Django 抛出 ImproperlyConfigured 如果未定义则出错。

为了使测试通过,我需要在我们的 CircleCI 测试环境中定义 ENV_ROLE 环境变量。正在关注https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-step ,我已将以下内容添加到 run 步骤:

      - run:
          environment:
            ENV_ROLE: development

但是,我仍然从 CircleCI 收到此错误:

#!/bin/bash -eo pipefail
cd lucy-web
source venv/bin/activate
python manage.py compilescss --verbosity 0
python manage.py collectstatic --clear --no-input --verbosity 0
flake8
python manage.py test
Traceback (most recent call last):
  File "/root/lucy/lucy_web/lucy-web/env.py", line 5, in <module>
    ENV_ROLE = os.environ['ENV_ROLE']
  File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'ENV_ROLE'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 4, in <module>
    from env import ENV_ROLE
  File "/root/lucy/lucy_web/lucy-web/env.py", line 8, in <module>
    "No 'ENV_ROLE' environment variable is defined. "
django.core.exceptions.ImproperlyConfigured: No 'ENV_ROLE' environment variable is defined. Please define it as 'development', 'staging', or 'production'.
Exited with code 1

这是完整的.circleci/config.yml:

version: 2
jobs:
  build:
    working_directory: ~/lucy/lucy_web/
    docker:
      - image: python:3.6.5
        environment:
          DATABASE_URL: ...
      - image: jannkleen/docker-postgres-gis-hstore
        environment:
          POSTGRES_USER: ...
          POSTGRES_DB: ...
      - image: redis:4.0.9-alpine
    steps:
      - checkout
      - restore_cache:
          key: deps1-{{ .Branch }}-{{ checksum "lucy-web/requirements.txt" }}
      - run:
          name: Install Python deps in a venv
          command: |
            cd lucy-web
            python3 -m venv venv
            . venv/bin/activate
            pip3 install -r requirements.txt
      - save_cache:
          key: deps1-{{ .Branch }}-{{ checksum "lucy-web/requirements.txt" }}
          paths:
            - "venv"
      - run:
          environment:
            ENV_ROLE: development
          command: |
            cd lucy-web
            source venv/bin/activate
            python manage.py compilescss --verbosity 0
            python manage.py collectstatic --clear --no-input --verbosity 0
            flake8
            python manage.py test
      - store_artifacts:
          path: test-reports/
          destination: tr1
      - store_test_results:
          path: test-reports/
  app_test:
    working_directory: ~/lucy/lucy_app
    docker:
      - image: node:8
    steps:
      - checkout
      - run:
          command: |
            cd lucy-app
            yarn install
            yarn lint
            yarn jest
workflows:
  version: 2
  build_and_test:
    jobs:
      - build
      - app_test

Django 项目修改了manage.py:

#!/usr/bin/env python
import os
import sys
from dotenv import load_dotenv, find_dotenv

if __name__ == "__main__":
    # Set environment variables from .env file
    load_dotenv(find_dotenv())

    # Determine which settings to apply (development, staging, or production)
    from env import ENV_ROLE
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", f"lucy.settings.{ENV_ROLE}")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django  # noqa: F401
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)

其中 env.py 检查是否定义了 ENV_ROLE 环境变量,否则抛出 ImproperlyConfigured 错误:

import os
from django.core.exceptions import ImproperlyConfigured

try:
    ENV_ROLE = os.environ['ENV_ROLE']
except KeyError:
    raise ImproperlyConfigured(
        "No 'ENV_ROLE' environment variable is defined. "
        "Please define it as 'development', 'staging', or 'production'.")

我不明白为什么 CircleCI 没有“获取”ENV_ROLE 环境变量?我的语法或对文档的理解有问题吗?

最佳答案

我在使用 circleCI + GAE 时遇到了类似的问题;我认为我在 .circleCI/config.yml 中设置的变量实际上从未进入应用程序,因为 GAE 运行的构建过程没有将它们传输进来。相反,我需要:

  • 制作多个 app.yaml 文件(在我的例子中是 app-staging.yaml 和 app-prod.yaml)
  • 更新 .circleci/config.yml 以在每个命令语句中使用它们,例如:

    命令:gcloud app deploy app-staging.yaml

关于python - CircleCI 没有获取运行步骤中定义的环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50614189/

相关文章:

python - PyInstaller 中的 Kivy Garden - 试图跟踪导入时卡住了

python - Apache 和 Python 线程处理奇怪的结果

python - Celeryd - 发送有关日志级别错误及以上的电子邮件

yaml - 在 RStudio 中使用类 "lesson.yaml"编写漩涡类(class) "text"时添加新的行/换行符

web - Jekyll 通过文件包含源代码

java - 在 Azure DevOps 管道中为测试用例创建特定工作项(Bug)--Selenium

python - PyTorch - 参数不变

python - ggplot2/图九 : How to plot grouped chart for a melted df?

python - django:如果 QueryDict 中不存在,则分配 None 值

django - 如何在 django : Storage or database 中存储 google oauth token