Referencing other environment variables in .env

Published 1 week ago by JussiMannisto

Hi,

When defining environment variables in the .env file, is there a way of referencing a variable that was defined earlier? I'd like to do something like this:

INDEX_NAME=dev_index
UPDATE_INDEXER_COMMAND="/some-path/indexer.sh $INDEX_NAME --update"
LIVE_INDEXER_COMMAND="/some-path/indexer.sh $INDEX_NAME --live"
...
Chris1904

I don't fully understand, but that's not what env variables are used for.

How about storing them in a config file?

JussiMannisto

My only goal is to reduce repetition in the .env file. The index name is environment specific, and it is repeated many times in the environment variables.

Of course I can write it out manually on each row, or use a placeholder and insert it in code. But if there's a way of injecting INDEX_NAME to other variables, that would be more elegant.

robrogers3

that's not how the .env files work.

they are simply read in and parsed as is.

if you need to do something more elegant than try looking at how config works.

i.e.

$foo = config(env('FOO', 'bar')) <-- that way you don't have to put it in .env.

but that also defeats the purpose of keeping things secret.

JussiMannisto

@robrogers3 That is not true.

Laravel's documentation tells that they use the DotEnv PHP library for environment configuration. From its source code I found out that it supports nested variables, which is exactly what I needed. See the function Dotenv\Loader->resolveNestedVariables for reference.

Here's an example for anyone looking for a solution:

INDEX_NAME=dev_index
UPDATE_INDEXER_COMMAND="/some-path/indexer.sh ${INDEX_NAME} --update"
LIVE_INDEXER_COMMAND="/some-path/indexer.sh ${INDEX_NAME} --live"

Please sign in or create an account to participate in this conversation.