Home > OS >  How do I read a yaml file and outputting the yaml file values as environment variables?
How do I read a yaml file and outputting the yaml file values as environment variables?

Time:05-05

I have my environment variables stored in a YAML file. The YAML file is used by a third party service for deployment.

I was wondering if there is a way to source the YAML file I am using, so that I can get access to my database credentials to run a migration once the app has been deployed?

example YAML:

env_variables:
  DATABASE_CONNECTION_ADDRESS: 'localhost'
  DATABASE_PORT: '5432'
  DATABASE_NAME: 'a-db'
  DATABASE_USERNAME: 'user'
  DATABASE_PASSWORD: 'password'
  IS_DEBUG: 'false'
  GS_BUCKET_NAME: image-bucket

My main motivation is that this deployment is running in a pipeline and I do not want to maintain the duplication of each of these environment variables in their own secret, and storing this YAML file as a secret so the third party service has access to it.

CodePudding user response:

If you have Python installed in your environment and can install ruamel.yaml in there you can source the output of the following one-liner:

python -c 'from pathlib import Path; from ruamel.yaml import YAML; print("".join([f"{k}={v}\n" for k, v in YAML().load(Path("example.yaml"))["env_variables"].items()]))' 

Its output is:

DATABASE_CONNECTION_ADDRESS=localhost
DATABASE_PORT=5432
DATABASE_NAME=a-db
DATABASE_USERNAME=user
DATABASE_PASSWORD=password
IS_DEBUG=false
GS_BUCKET_NAME=image-bucket

As Jeff Schaller suggested you probably want to quote the values and escape any single quotes that might occur in the string. This can easily be achieved by changing {v} into {v!r} in the one-liner.

As program:

#!/usr/bin/env python3

from pathlib import Path
from ruamel.yaml import YAML

file_in = Path("example.yaml")

yaml = YAML()
env_data = yaml.load(file_in)["env_variables"]
print("".join([f"{k}={v!r}\n" for k, v in env_data.items()])) 
  • Related