Elixir application deployment using a CI and private Hex.pm dependencies
Last week we moved from using some of our source code from Bitbucket to properly assembled Hex.pm private dependencies. This is what I learnt during the process (Hex.pm documentation is a little smoky about this, so this can be of some help to someone).
Hex.pm structure
First of all, we must understand how Hex.pm works. It’s all built around the concept of organisation, which is a logic group of users.
As you can see, an organisation can “contain” users (each of them with read, write, or admin permissions) and the eventual packages you already have published.
Fetching a private package while building on CI
We are using Bitbucket pipelines to build the artifacts, and it’s the place where we must fetch the dependencies to build the application release.
Hex.pm grants you access to private packages if you provide a properly generated key. In order to generate it, first of all, you have to authenticate yourself:
mix hex.user auth
You will be asked for an username and a password. Pay attention: you must authenticate with a user that has write permissions. Once you have done this, you are able to generate a key for your organisation:
mix hex.organization key ORGANISATION_NAME generate --key-name KEY_NAME --api-read
This will give you a simple output like this: a6w53af8w6adfwud56fuaw5efuad
(fake :D)
This is the key you have to use to authenticate the organisation to fetch packages:
mix hex.organization auth ORGANISATION_NAME --key a6w53af8w6adfwud56fuaw5efuad
But why are we working with an organisation ?
The private package setup
The package setup must take into account the fact that it will belong to a specific organisation. This happens updating the mix.exs
for your package:
defp package do
[
organization: "YOUR_ORGANISATION_NAME"
]
end
and
def project do
[
...
package: package(),
...
]
end
this declaration means that anytime the package will interact with the remote repository, it will take into account the organisation. This is the link between the key and the private repositories fetch.
Last but not least, we must configure the Bitbucket pipeline, and it’s all about defining the key. You can achieve this in the repository settings:
At this point, we can add:
mix hex.organization auth ORGANISATION_NAME --key ${HEXPM_API_KEY}
right before we run mix deps.get
during your build.