openBalena preregister with Python SDK

Hello! I am working on an application which requires preregistering devices using openBalena so that some environment variables can be set for the device as soon as it turns on. As of right now we have a python script which registers the device via the Python SDK, and then modifies a template config.json file, inserting the uuid we register with Balena. The script then moves the modified file to a the boot partition of an SD card which has already been flashed.

It seems like there should be a better way to do all of this. I would like to use balena os configure as described here, but it the python SDK doesn’t seem to support it.

Is there something I’m missing that would make the process more streamlined/reliable? I know balena says throughout the documentation that it’s not a great idea to modify the config.json file directly.

Hi there, you are correct - our Python SDK currently does not implement this functionality, because this implementation is not trivial. So one way to do this, would be to wrap balena-cli in your Python script(s) and call it via the Python’s subprocess library. Alternatively, if Python has a way to natively mount/unmount FAT filesystems, you could implement it directly.

So it sounds like we may be on the right track then by modifying the config.json file with our Python script. In doing a diff of two outputs of the balena os configure, it seems that the following fields change:

  • deviceApiKey
  • registered_at
  • deviceId
  • uuid

We are currently able to generate and register a UUID just fine, but I am unsure of how to get the registered_at and deviceApiKey fields to pop into the config.json file.

In researching ourselves we discovered that the uuid and deviceId are in the device object returned by the preceding register call in python. We also discovered that registered_at is calculated client side by the CLI, and we are able to do the same thing in python. Finally, we were able to use this function to get a device API key, and insert this into our config object which is then written to the SD card.

Hi @ca1ebd, thank you for sharing your solution here. Your solution sounds good to me.