Parse environment variable from yaml with pyyaml

Viewed 1180

I have the following yaml file:

config:
  username: admin
  password: ${SERVICE_PASSWORD}
  service: https://${SERVICE_HOST}/service

How could I load the password and host values from the environment?

1 Answers

In order to load environment variables you need to add some boilerplate to help pyyaml find and resolve these values:

import yaml, re, os

env_pattern = re.compile(r".*?\${(.*?)}.*?")
def env_constructor(loader, node):
    value = loader.construct_scalar(node)
    for group in env_pattern.findall(value):
        value = value.replace(f"${{{group}}}", os.environ.get(group))
    return value

yaml.add_implicit_resolver("!pathex", env_pattern)
yaml.add_constructor("!pathex", env_constructor)

print(yaml.load("""
config:
  username: admin
  password: ${SERVICE_PASSWORD}
  service: https://${SERVICE_HOST}/service
"""))
Related