Activate new certificates for Hass.io

I use hass.io with the LetsEncrypt, Certbot and NGinx addons for remote access.

This is working flawlessly, and the Certificate Expiry sensor is showing the number of days that the active certificate is valid.

I noticed that although the certificates had been renewed, the sensor was still showing the counter for the old certificate. This is, because NGinx needs to be restarted to activate the new certificates. Since Home Assistant is all about automation, I decided that I wanted to automate this.

My general approach to this is, that I monitor the timestamp of the certificate file.
If it has changed, the proxy addon will be restarted.

:warning: The addon slug "00aaaa00_nginx_proxy" in the example configuration needs to be replaced by what’s used in your setup. Go to the configuration screen of the NGinx addon in your browser and copy and paste it from the url http://hassio.local:8123/hassio/addon/00aaaa00_nginx_proxy in the address bar.

homeassistant:
  whitelist_external_dirs:
    - /ssl

sensor:
  - platform: cert_expiry
    host: 'redacted.duckdns.org' # change for your setup

  - platform: filesize
    file_paths:
      - /ssl/letsencrypt/live/hassio/cert.pem # check your nginx config

  - platform: template
    sensors:
      certpem_last_updated:
        entity_id: sensor.certpem
        value_template: "{{ state_attr('sensor.certpem', 'last_updated') }}"

automation:
  - alias: "Timestamp SSL cert changed"
    trigger:
      - platform: state
        entity_id: sensor.certpem_last_updated
    condition: 
      - condition: template
        value_template: "{{ (trigger.from_state.state != 'None') }}"
    action:
      - service: hassio.addon_restart
        data:
          addon: "00aaaa00_nginx_proxy" # check your nginx config
      - service: notify.notify
        data_template:
          message: 'NGinx proxy restarted to activate new certificate'

Any suggestions are very welcome.

1 Like