How to share a variable between 2 config files?

In config/config.exs there’s this:


a1 = 123

# [.........]
# using a1 here ....
# key123: a1

import_config("config2.exs)

But in config/config2.exs the variable a1 won’t be visible.

Why not? And how to make it visible in config2.exs too? A simple solution, without unnecessary complexity.

You are doing it the other way around. Put import_config("config.exs") at the bottom (or top?) of your config/config2.exs.

The way you are doing it now you’ll override variables from config.exs with those inside config2.exs.

Why do you assume that I want to avoid to overwrite them in config2? But the question isn’t about it.

I misread, it seems.

Why not?

Because config/config.exs and config/config2.ex are two different scripts. Everyone with his own context/bindings.

And how to make it visible in config2.exs too?

It doesn’t work.

A simple solution, without unnecessary complexity.

A solution would be to save the value in an env var and use System.get_env/1 in the config files.

I have 100 applications and each of them has 100 variables in a config file, similar to the one that I’ve shown. All on a single machine. How do you propose that I manage that with env variables? I’d have to come up with naming all those variables first, and the names would have to be unique accross the OS, that is, 100*100 = 10000 names. And then I’d have to store all of them in ~/.profile

That sounds like a very large and very configurable project.

The problem your try to solve is to split up a huge config file. And at the same time, to hold a series of values to use this in the configuration.

Maybe you can do something like this in config/config.exs:

values = [
  foo: 1,
  bar: 7,
  baz: "asdf"
]

"config/app1.exs"
|> File.read!()
|> Code.eval_string(values)

and in config/app1.ex

import Config

config :app1, bar: bar

That’s vise versa and is precisely what I don’t need. I need to specify nil values in the main config and then assign data to them in a personalized config file which would be outside of .git., and then, optionally, keep using them futher in the main config.

I’ve tried this and it didn’t work

config/config.exs:

  Code.eval_file("config/data1.exs")
  IO.puts("***test1: #{test1}") # undefined !

config/data1.exs:


  test1 = 777

Why isn’t test1 visible in the main file?

It is available, though not implicitly, but via the return value of Code.eval_file.

2 Likes

It works!!!

1 Like