A question that comes up on these forums is how to schedule/trigger a command on the host system from a container-based HA install. I had this question myself and it seems the usual answer is to give ssh access to the host from the container and use ssh to execute the command.
This opens up a potential attack vector to the host were someone to get access to your HA instance. While i’m not particularly worried about this, I decided to see what would be involved in setting this up without ssh. It turns out to be quite do-able, and seems more secure, using a named pipe.
The following assumes you want to run a script on the host called some_script.sh
. In my case this is located in $HOME/bin
.
Note: My host OS is Linux (Raspbian v11). I’ll be interested to hear if there are any wrinkles with other host OS setups (Mac, Windows).
Step 1: Create a named pipe
On the host:
cd /usr/share/hassio/homeassistant
sudo mkdir pipes
cd pipes
sudo mkfifo host_executor_queue
I’ve chosen to name the pipe host_executor_queue
but you can name yours whatever you like.
Step 2: Create a script for monitoring the pipe
Again on the host, put this script somewhere and make it executable. Mine is $HOME/bin/monitor_ha_queue.sh
:
#!/bin/bash
pipe=/usr/share/hassio/homeassistant/pipes/host_executor_queue
while true; do
if read line < $pipe; then
case $line in
some_script)
$HOME/bin/some_script.sh
;;
esac
fi
done
You can add a cron job to start this on boot (you may have to set $HOME
in your cron file):
@reboot $HOME/bin/monitor_ha_queue.sh
and start it right away via
nohup $HOME/bin/monitor_ha_queue.sh >&/dev/null &
Step 3: Add a shell command to your HA configuration
Add the following to your configuration.yaml
:
shell_command:
some_command: echo some_script > /config/pipes/host_executor_queue
and restart HA.
Step 4: Set up the automation in HA
At this point the shell command is available in HA, so e.g., you can add a script via the UI with action “Call Service > Shell Command: some_command” and trigger this script however you like.
Adding more commands
Going forward, adding additional commands is easy:
- Add shell command to
configuration.yaml
. - Add another case to the switch statement in
monitor_ha_queue.sh
and restart the monitor. - Restart HA.