0

So I've built a Django application, and used the AWS CodeStar Django template (EC2, EB).

The first thing I did was change the SECRET_KEY to pull from an environment variable like so os.environ['DJANGO_SECRET_KEY']. I ssh'ed into the EC2 instance and added this variable, and I also added this variable to the EB environment (in modify configuration).

However, CodeBuild still breaks on the build. Where do I need to add this environment variable?

Marquistador
  • 1,841
  • 19
  • 26
  • What is the actual error ? Can you please post it with traceback ? – Sumeet Kumar May 19 '18 at 22:18
  • It was a 'KeyError' --> i.e. os.environ returns an dict of all of the env variables, but the variable simply didn't exist in the build environment. – Marquistador May 20 '18 at 15:16
  • Just to add to the conversation, I struggled a lot to solve some problems related with my environment variables not being found, all of which was caused because my SECRET_KEY variable contained prohibited characters. Check [this answer](https://stackoverflow.com/questions/2821043/allowed-characters-in-linux-environment-variable-names) for more details – reojased Jun 12 '20 at 21:05

2 Answers2

1

In order for the build to go through, I discovered that you need to go to AWS CodeBuild, click on 'Edit Project' for the build project in question.

At the bottom of the page, you will see 'Show Advanced Settings'. Here you can see that you are able to add environment variables to the build environment. This is how I got this to work.

** Note, this may not be the proper course of action for the SECRET_KEY, however, this applies to any environment variables that are not detected during CodeBuild's build step.

Marquistador
  • 1,841
  • 19
  • 26
1

The codebuild environment variable is not a good option for secret keys instead you can use ec2 parameter store. Goto EC2 > parameter store > create parameter > add name and secret string.

you can get via aws cli aws ssm get-parameter --name "SECRET_KEY"

Another way in code build you can simply

buildspec.yml

version: 0.2
    env:
      parameter-store:
        SECRET_KEY : "SECRET_KEY" 
 phases:
  install:
   commands:
        echo $SECRET_KEY

adding secret to parameter store

owais
  • 4,752
  • 5
  • 31
  • 41
  • We're running into the same problem. We store our variables in SSM, but want to pass the stage (dev/test/prod) through as a CodeBuild environment variable, which is used to pull the right variable from ssm. How do you access CodeBuild environment variables in python? – Craig Jul 23 '18 at 16:41
  • 1
    echo $SECRET_KEY >> your_env_file.py :) . your python code can read from there. – owais Jul 23 '18 at 17:04