Wednesday, January 5, 2022

Home Assistant Renew DHCP Lease

This is a workaround for a problem with Home Assistant running in a Virtual Machine and not renewing a DHCP lease thus losing the connection to the local network after the lease runs out. You can define an automation that will periodically run a script that pokes the network interface forcing a lease renewal. I did it a while ago so I hope I remember all the elements required to make the workaround work.

The rest api that allows to poke the network interface of the home assistant os is not accessible from outside of the instance. You need to install the "Terminal & SSH" add-on to get access to the os running home assistant.

Once you "hack the system" and get inside the home assistant via ssh, inside the config directory, define a script that pokes the card:

curl -X POST \
    -H "Authorization: Bearer $SUPERVISOR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"enabled":"True"}' \
    http://supervisor/network/interface/enp0s3/update

Where enp0s3 is the name of the network interface, it might well be different in you setup.

The script needs to be inside the config directory because config directory is special, contents are not deleted on restart for one.

Once you got access to the home assistant os, it is easy to see there seems to be cron available, but I tried in vain to use it. Not only is cron not running the crontab, but also any cron configs are wiped on restart.

Instead you can define a home assistant automation that will invoke the script.

Add to config/automations.yaml:

- id: renew-dhcp-lease
  alias: "Renew DHCP lease"
  trigger:
    - platform: time
      at: "21:35:00"
  action:
    - service: shell_command.cycle_network

Add to config/configuration.yaml:

shell_command:
  cycle_network: bash cycle-network.sh

This will trigger the action at 21:35 each day, which was good enough for me.