balena-cli icon indicating copy to clipboard operation
balena-cli copied to clipboard

[FEATURE] `balena login` automatically logs in with API Key Environment Variable

Open Merith-TK opened this issue 2 years ago • 1 comments

I personally have found that my local windows environment breaks my balena configs for some reason when I push, I have figured it is because half of my tools are in a scuffed state and could really use a reinstall of windows in general.

So I am moving to use gitpod to develop balena configs to deploy, however due to how the usual "balena login" command works, this makes it difficult for me to log in each time as I have to manually apply my API key and have it stored somewhere on my PC.

Gitpod, in account settings lets you set up global Environment Variables in your account, these variables apply to all gitpod workspaces that can follow a simple regex such as */* for all repos, or merith-tk/* for all of my personal repos, or even */reponame for all repos sharing a name.

So in my gitpod environment I am setting up, I am creating an bash script to automatically download and extract balena-cli and add it to $PATH, so if I can just balena login with an environment variable such as BALENA_CLI_API_TOKEN, and not have to go through that process and instead allow gitpod to automatically set it up, that would be great!

Merith-TK avatar Oct 17 '21 19:10 Merith-TK

Good suggestion @Merith-TK 👍  Some thoughts:

After balena login, the CLI stores the session token (or API key) in a file at ~/.balena/token (Linux, macOS) or %UserProfile%\_balena (Windows). This directory can be changed with the BALENARC_DATA_DIRECTORY env var. If you exposed the session/API token through a gitpod env var, your bash script could perhaps copy the env var contents to ~/.balena/token, and then the CLI would be logged in (test with balena whoami).

I think this would allow your setup to work with the CLI as it is, without further dev work. But yes, it would be nice if the CLI allowed logging in through an env var.

A note regarding session token vs. API key:

$ balena login
... Logging in to balena-cloud.com
? How would you like to login? Authentication token
? Session token or API key from the preferences page
...

If you visit the balenaCloud web dashboard, Preferences -> Access tokens, you will notice that there is a "session token" and there "API keys". Even though either can be used to login with the CLI, the session token has additional backend permissions that are required by some CLI commands, such as balena ssh <device-uuid> and balena key add (and probably a few others). So although balena login does not make it clear (needs improvement, related issues: #2257, #1097), API keys and session tokens are not fully equivalent. Another consideration is that session tokens expire after a while (2 weeks? needs confirmation) but API keys do not expire as far as I am aware.

pdcastro avatar Oct 18 '21 11:10 pdcastro