-
Notifications
You must be signed in to change notification settings - Fork 4
/
yaml_env_tag.py
36 lines (31 loc) · 1.33 KB
/
yaml_env_tag.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
""" A custom YAML tag for referencing environment variables in YAML files. """
__version__ = '0.1'
import os
import yaml
from typing import Any
def construct_env_tag(loader: yaml.Loader, node: yaml.Node) -> Any:
"""Assign value of ENV variable referenced at node."""
default = None
if isinstance(node, yaml.nodes.ScalarNode):
vars = [loader.construct_scalar(node)]
elif isinstance(node, yaml.nodes.SequenceNode):
child_nodes = node.value
if len(child_nodes) > 1:
# default is resolved using YAML's (implicit) types.
default = loader.construct_object(child_nodes[-1])
child_nodes = child_nodes[:-1]
# Env Vars are resolved as string values, ignoring (implicit) types.
vars = [loader.construct_scalar(child) for child in child_nodes]
else:
raise yaml.constructor.ConstructorError(
None, None,
f'expected a scalar or sequence node, but found {node.id}',
node.start_mark
)
for var in vars:
if var in os.environ:
value = os.environ[var]
# Resolve value to Python type using YAML's implicit resolvers
tag = loader.resolve(yaml.nodes.ScalarNode, value, (True, False))
return loader.construct_object(yaml.nodes.ScalarNode(tag, value))
return default