Search code examples
djangogitlabenvironment-variablesgitlab-ci

How to set the variables from .env file when using Django and Gitlab CI/CD?


I'm trying to run the tests of my Django app in Gitlab CI/CD. The process fails every time with an error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty..

I assume this is because I have not my .env file available in the repository and that file contains for example the SECRET_KEY -variable which is then used in the settings.py like this: SECRET_KEY = os.getenv('SECRET_KEY').

So what would be the proper way to set these variables so my tests would pass?


Solution

  • One good way is to add the secret in CI variable. Then export it in target repo.

    http://your/gilab/url/project/-/settings/ci_cd > Expand variables

    Add a variable named SECRET_KEY, with the value, select type variable. Then in .gitlab-ci.yml, add following in concerned job.

     before_script:
        # to export variable to target environment
        - export SECRET_KEY=$SECRET_KEY  
        # to check if OK
        - env 
    

    When set up the variable, you might select on which environment (dev, staging, prod) if you have many env.