Set Service Variable from device container

My question is similar to this:

but he is trying to set the device variable, while I’m trying to set the device service variable in python.
I tried using

from balena import Balena
import os
balena = Balena()
auth_token = os.environ['BALENA_API_KEY']
app_id = os.environ['BALENA_APP_ID']
balena.auth.login_with_token(auth_token)
balena.models.environment_variables.service_environment_variable.create(app_id, 'main', 'TEST', 'test value')

to do that in the device container, but I got an error complains it’s unauthrized. Could you please tell me what’s wrong? Do I need to give it the account credential in order to do that? The API doc didn’t give an example: Balena Python SDK - Balena Documentation.

Thank you.

Hello, That should be possible as you have described. Have you verified that the env var BALENA_API_KEY is set as expected? This is not available by default - you need to add the io.balena.features.balena-api label in docker-compose. See : Multiple containers - Balena Documentation

Hi, thank you for replying. I believe I have the BALENA_API_KEY defined as I can update/create the device variable with the example in the first link. But I can not set the service environment variable.

Hi @jasonliu, I believe what is going on is that the service_environment_variablemethod creates variables for the whole application while the BALENA_API_KEY is scoped for a single device.

If you just want to create a service variable for a single device you can use the device_service_environment_variable method.

Otherwise if you want to create a service variable for the whole application you can create a new API_KEY (under Preferences > Access Tokens) and pass that key as a variable to the device to allow it to change settings at the fleet level.

Could you tell us a bit more about your use case? What are you trying to achieve with service variables?

Thank you!

Thank you, I will try that out later.

Basically we (our company) is trying to run a program in balena container on different RPIs and that program will have a socket connection to a server.
We would like to have someone, who doesn’t have the balena cloud access, to change some of the global environment variables for devices through the socket.

This is our use case. Let me know if it make sense.

Hi again,

Thanks for the further context. Yes, what you are saying makes sense.

Beware though than when creating an API key as I explained before, that API key has the same level of the permissions as the key owner, so you should be careful to limit the permissions of that user to a single application and be sure that the third party cannot get access to that key otherwise they will be able to modify more than environment variables.

You can see more documentation about permissions here Organization management - Balena Documentation

Hi Pipex,

Thank you for pointing out the permission issue and for the provided reference.

Best,
Jason