3

I need to replace values in a config file given below with some values that i will be getting from env variables . Below is the config file

vnv:
{
 endpoints: {
        directflow: {
            host = "http://xxxx.xxx.xyz.xxx.com/ver0.1/call/in.xml.gz";
        };
        incidents: {
            host = "http://xxxx.xxx.xyz.xxx.com/ver0.1/call/in.xml.gz";

        };
    };
    sleep = 30;
    timeout = 30;
};

i need to replace the host with values from environment variable. This file is not a json file. What approach should i take to substitute values here.

Shane Warne
  • 1,350
  • 11
  • 24

1 Answers1

2

you can use os.environ:

import os

host = os.environ.get('MY_ENV_HOST')

to replace in your file you can use:

import os
import re

with open('file.cfg') as fp:
    text = fp.read()

env_host = os.environ.get('MY_ENV_HOST')

host = f'http://{env_host}.com/'

new_text = re.sub(r'http://.*\.com/', host, text)

with open('file.cfg', 'w') as fp:
    fp.write(new_text)
kederrac
  • 16,819
  • 6
  • 32
  • 55