Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Role of `?` when accessing environment variables in HOCON files

The docs say that I can access environment variables like this:

database_name = "${?DB_NAME}"

Where DB_NAME is an environment variable. Do I have to put the question mark ? or is that there to prevent a crash if it doesn't exist?

Also, are we allowed to reference a variable in a file before it is declared?

foo = "hello-${bar}"
bar = "baz"
like image 559
Blankman Avatar asked Feb 15 '17 03:02

Blankman


People also ask

What is the role of environment variables?

Environment variables help programs know what directory to install files in, where to store temporary files, and where to find user profile settings. They help shape the environment that the programs on your computer use to run.

Which function is used to access all environment variables?

The command env displays all environment variables and their values. The command printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.

How do you handle environment variables?

There are multiple solutions: you ask each developer to set the value in their environment before launching the application. you add some logic at the application's initialization to use the API key environment variable value if it exists, otherwise, fall back to the plain configuration file.

Which file required to set the environment variable is?

env files. In some situations you only need an environment variable set for only a single project. In that case . env files are a great solution.


1 Answers

1- ? means optional. If the environment variable does not exist at runtime, the whole line will be ignored, as if it didn't exists in the first place. So use it when you want optional overriding.

See Optional Env Vars section of the docs for more info.

Note that ? works for all substitutions and not just env vars.

2- Yes, you can reference a variable which is defined later in the config file (forward referencing). As long as the value exists and there is no cycle (circular dependency), the substitution will be done successfully.

Think of it like this: first the whole file will be parsed at runtime and the value of the literals will be bound to their vars, and then the substitutions will take place, so the order doesn't really matter.

like image 50
Nader Ghanbari Avatar answered Nov 14 '22 01:11

Nader Ghanbari