Setting config for libraries inside Livebook
Published on November 19, 2022 · 2 min read · 0 reading right now · 1 views
In elixir, when you are working with libraries that require setting some configurations such as access keys, the traditional way is to put configs inside the
config/
directory.
For example, using
ex_aws
library
, we need to set
access_key_id
and
secret_access_key
in the config.
So, inside our
config/dev.exs
(or
config/prod.exs
), we put the following code:
import Config
config :ex_aws,
access_key_id: [{:system, "AWS_ACCESS_KEY_ID"}, :instance_role],
secret_access_key: [{:system, "AWS_SECRET_ACCESS_KEY"}, :instance_role]
and it works as intended. The problem arises when you want to use this library(or similar ones that require setting config) inside livebook. You can't really use the above code to set the configurations.
Well, it turns out livebook(or rather
Mix
) has a different way to set these configs.
Let's see an example:
Imagine a library named
very_cool_library
that requires
cool_name
to be set through config. Lets use
Mix.install
to install this library.
Mix.install([:very_cool_library])
Now, we need to set
cool_name
through config. To do that,
Mix.install
takes an optional keyword list argument named
config
(how convenient). The value of
config
should be a keyword list, and the keyword list must contain the library's name for which we want to add config.
Mix.install([:very_cool_library], config: [
very_cool_library: []
])
The value of this library name key is another keyword list. We can put in the key and value of the config that the library requires. Here's the full code:
Mix.install([:very_cool_library], config: [
very_cool_library: [
cool_name: "Mario"
]
])
And that's it! Everything should work as flawlessley.
Taking our previous example of
ex_aws
library which requires
access_key_id
and
secret_access_key
to be set through config, here's the equivalent for livebook:
Mix.install([:ex_aws], config: [
ex_aws: [
access_key_id: [{:system, "<AWS_ACCESS_KEY_ID>"}, :instance_role], # or key as a string
secret_access_key: [{:system, "<AWS_SECRET_ACCESS_KEY>"}, :instance_role] # or key as a string
]
])
Setting config with new livebook secrets feature
With release of livebook 0.7 , you can using secrets within your livebook without exposing it to others(which one would've easily done with the above approach).
Set the livebook secret with keys "AWS_ACCESS_KEY_ID" and "AWS_SECRET_ACCESS_KEY".
Now, just use this key with prefix "LB_" inside the config(livebook fills in the secrets that start with "LB" automatically):
Mix.install([:ex_aws], config: [
ex_aws: [
access_key_id: [{:system, "LB_AWS_ACCESS_KEY_ID"}, :instance_role],
secret_access_key: [{:system, "LB_AWS_SECRET_ACCESS_KEY"}, :instance_role]
]
])
and everything should work as expected! No more accidental secret sharing with others.