I have a below yml file samplelambda1.yml
Mappings:
Environments:
dev:
DefaultLambdaConcurrency: '10'
test:
DefaultLambdaConcurrency: '10'
staging:
DefaultLambdaConcurrency: '10'
production:
DefaultLambdaConcurrency: '10'
I have multiple files like samplelambda2,3,4....30
I need to add another mapping to all the yml file with help of python script, how can we do it? I tried string replace but its a complicated operation to open a file and replace multiple lines.
production-new:
DefaultLambdaConcurrency: '10'
CodePudding user response:
The question shows no effort (no offence but OP should try his approach and post wherever he's stuck) so here is just the hint.
import os
for filename in os.listdir(directory):
// read each YAML using this: https://stackoverflow.com/a/1774043/5353128
// add your key value in the read YAML dict.
// Use yaml.dump() to save the content back to file.
CodePudding user response:
You can handle yaml files in python with pyyaml. To add to the existing yaml you could do something like:
import yaml
with open("file_append.yaml", "r") as fs:
append_dict = yaml.load(fs, Loader=yaml.SafeLoader)
append_to = ["file_1.yaml"]
for file_name in append_to:
with open(file_name, "r") as fs:
target_dict = yaml.load(fs, Loader=yaml.SafeLoader)
target_dict["Mappings"]["Environments"] = {**target_dict["Mappings"]["Environments"], **append_dict}
with open(file_name, "w") as fs:
yaml.dump(target_dict, fs)
Output:
Mappings:
Environments:
dev:
DefaultLambdaConcurrency: '10'
production:
DefaultLambdaConcurrency: '10'
production-new:
DefaultLambdaConcurrency: '10'
staging:
DefaultLambdaConcurrency: '10'
test:
DefaultLambdaConcurrency: '10'