Accessing OS environment variables in rules

Hi All,

I have a Dockerized OpenHAB setup that needs to work in multiple environments (I have a PROD environment driving my house on an Odroid SBC, and a DEVEL on my laptop). The environments need to be completely independent from each other so that I can develop my Items, Things, Rules…etc on my laptop without having any effect on the in-production OpenHAB.

Both environments have a separate account on OpenHAB Cloud.

I would like to provide each environment a different admin email address to which the rules can send notification messages when a problem arises.

The typical solution with a Java application that a setting is simply provided as an environment variable and query it with java.lang.System.getEnv(). This doesn’t work in the .rules file, I get a "no viable alternative at input ‘System’ " error message. It looks like java.lang.Sytem cannot be accessed at all from a rule file.

How do I solve this elegantly, without maintaining separate rule/item files for the environments?

Any help is appreciated !

Honestly, switch to scripted automation and code your Rules using Python, JavaScript, or Groovy. See https://openhab-scripters.github.io/openhab-helper-libraries/index.html for the current state of the art. If you want to use Python, see [beta testers wanted!] Jython addon w/ helper libraries (requires OH 2.5).

With the Helper Libraries, there is a stnadardized “configuration.py” file you can put such configuration information into and import it into your Rules.

If you are to stick with Rules DSL, my recommendation would be to use Design Pattern: Separation of Behaviors so you only ever send the email from one Rule, or put the email address into a String Item.

Thanks, I will look into scripted automation.

This is what I did for a similar purpose :

configuration.py

...
import socket
hostname = socket.gethostname()
isProduction = hostname != "neo2dev"
...

Example usage for Telegram :

telegram.py

from core.rules import rule
from core.triggers import when
from configuration import lesactions, actionKind, isProduction
from personal.notification import notification
from personal.utils import setEnabledThing

@rule("Telegram : Init Telegram")
@when("System started")
def telegram_start(event):
	devbot = "telegram:telegramBot:devbot"
	prodbot = "telegram:telegramBot:prodbot"

	setEnabledThing(devbot, False if isProduction else True)
	setEnabledThing(prodbot, True if isProduction else False)

	targetBot = prodbot if isProduction else devbot
	
	lesactions[actionKind.telegram] = actions.get("telegram",targetBot)
	notification(u"Telegram binding initialized for '{}'".format(targetBot))

You can actually access the JVM environment variables like you do in Java from Jython. Just import the same package and use the same function. I’m using this to get the config path so that I can write an automatically generated sitemap.