I\'m trying to run a PHP script that is triggered by a cron script (in cron.d). The script is triggered properly but it is missing the Elastic Beanstalk \"Environment Variab
I spent several hours trying to figure out how to pass Environment Variables to PHP CLI. I tried:
$ source /opt/elasticbeanstalk/support/envvars.d/sysenv
No matter what I tried, env variables won't pass to PHP CLI.
When I log to my EC2 instance as ec2-user and do this: $ echo $ENVIRONMENT
I get prod
. If I do it as $ sudo su
and then $ echo $ENVIRONMENT
I get prod
.
If I manually run the PHP CLI file (used in cronjob) my script works. When it runs automatically (via cronjob) Environment Variables are not passed to my script.
Here's what I did. Put this in your cronjob entry script:
$variables = '/opt/elasticbeanstalk/support/envvars.d/sysenv';
if (file_exists($variables) && is_file($variables)) {
$contents = file_get_contents($variables);
foreach(explode("\n", $contents) as $line) {
if (empty($line)) continue;
$new_line = str_replace('export ', '', $line);
$first_part = strpos($new_line, '=');
$last_part = substr($new_line, $first_part, strlen($new_line));
$variable_value = str_replace(array('=', '"'), array('',''), $last_part);
$variable_name = substr($new_line, 0, $first_part);
putenv($variable_name."=".$variable_value);
}
}
It extracts each line from /opt/elasticbeanstalk/support/envvars.d/sysenv
file, removes the export
part, gets the variable name & value, and sets it via putenv() function.