Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS ElasticBeanstalk ENV Vars not working

I'm hosting my PHP project on AWS EC2 servers, using Elastic Beanstalk. I've set up my ENV Vars using php dotenv, which seem to be getting my vars just fine from my root .env file:

DbConnect.php:

require '../vendor/autoload.php';
$dotenv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();

$DB_HOST = getenv('DB_HOST');
$DB_USERNAME = getenv('DB_USERNAME');
$DB_PASSWORD = getenv('DB_PASSWORD');
$DB_DATABASE = getenv('DB_DATABASE');

$mysqli = new mysqli($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);

So, in AWS Management Console, I set up the same named ENV vars within software configuration, git pushed, and re eb-deployed. I'm getting a 500 error because the EC2 ENV vars don't seem to be picking up.

enter image description here

Is there something else I need to do?


Update:

eb printenv displayed the correct env var values.

like image 718
user3871 Avatar asked Jun 17 '15 23:06

user3871


People also ask

Where are environment variables stored Elastic Beanstalk?

Python. Environment properties are written to the /opt/python/current/env file, which is sourced into the virtualenv stack where the application runs. For more information, see Using the Elastic Beanstalk Python platform.


1 Answers

Quote from https://github.com/vlucas/phpdotenv

phpdotenv is made for development environments, and generally should not be used in production. In production, the actual environment variables should be set so that there is no overhead of loading the .env file on each request. This can be achieved via an automated deployment process with tools like Vagrant, chef, or Puppet, or can be set manually with cloud hosts like Pagodabox and Heroku.

You will have php fatal error if you do not have .env file

Fatal error: Uncaught exception 'Dotenv\Exception\InvalidPathException' with message 'Unable to read the environment file at /home/vagrant/Code/project/.env.' in /home/vagrant/Code/project/vendor/vlucas/phpdotenv/src/Loader.php on line 75

If you would like Below is the sample code that you can set Environment Variable to check, it only load the Dotenv class if it is on local / testing environment

if(getenv('APP_ENV') === 'local' || getenv('APP_ENV') === 'testing')
{
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
}

Or another method is check the .env file exist or not

$filePath = rtrim(__DIR__, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR . '.env';
if(is_file($filePath) && is_readable($filePath))
{
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
}
like image 150
Shiro Avatar answered Oct 05 '22 19:10

Shiro