Get HA Secrets in AppDaemon

I needed to access Home Assistants Secrets in AppDaemon and couldn’t find a built-in solution, so I created the following app:

import appdaemon.plugins.hass.hassapi as hass

class Secrets(hass.Hass):

    def initialize(self):
        self.secrets_file = "/home/homeassistant/.homeassistant/secrets.yaml"
        self.listen_event(self.load_secrets, "plugin_started")

    def load_secrets(self, event, kwargs, b):

        self.config["secrets"]["settings"] = {}

        f = open(self.secrets_file, "r")
        for line in f:
            if ":" in line:
                line_parts = line.split(":", 1)
                self.config["secrets"]["settings"][line_parts[0].strip()] = line_parts[1].strip()
        f.close()

    def get_secret(self, key):
        if key in self.config["secrets"]["settings"]:
            return self.config["secrets"]["settings"][key]
        else:
            return None

The code isn’t perfect and can certainly be improved, but it does the job. You can retrieve a Secret in any App using:

secrets = self.get_app('secrets')
my_secret_value = secrets.get_secret('my_secret_name')

or you could just access the value directly, without loading in the app, using:

my_secret_value = self.config["secrets"]["settings"]["my_secret_name"]

Secrets get reloaded whenever HA is restarted. I hope someone finds this useful.

Hello @Sitrate,

Thanks for this. But you don’t need this as, as AD caters for using secrets data within the app config.

You can pass the secrets within the config using the standard way !secrets, then use self.args to retrieve the data within your app. For example

test_app:
    class: MyClass
    module: test_app
    token: !secrets mytoken

In the app self.args["token] will give you the data in your secrets file.

Regards

2 Likes

Thanks @Odianosen25. I didn’t know that was an option. I’m forever reinventing the wheel! Thanks again.