Here is my yaml file
cat host.yaml
list1:
- host-1
- host-2
- host-3
- host-4
list2:
- host-5
- host-6
- host-7
- host-8
list3:
- host-9
- host-10
- host-11
- host-12
list4:
- host-13
- host-14
- host-15
- host-16
Here is my list of hosts
cat host.list
host-1
host-5
host-7
host-11
host-16
I am trying to write a program/script that takes host.yaml and host.list as input and if hosts in the host.list matches hosts in the host,yaml it should edit the yaml and remove those hosts.
In the above scenario python write_to_yaml.py host.yaml host.list should write below to yaml file.
cat host.yaml
list1:
- host-2
- host-3
- host-4
list2:
- host-6
- host-8
list3:
- host-9
- host-10
- host-12
list4:
- host-13
- host-14
- host-15
Please forgive me if this is a silly question, I am very very new to Python.
CodePudding user response:
You can do it by first installing pyyaml
via:
pip install pyyaml
And then you can use the library to read and write your yaml files like so:
import yaml
output = {}
host_set = []
# get list of hosts to exclude
with open(r'host.list') as file:
hosts = yaml.load(file, Loader=yaml.FullLoader)
host_set = set(hosts.split(" "))
# read host.yaml
with open(r'host.yaml') as file:
documents = yaml.full_load(file)
for l, hosts in documents.items():
output[l] = list(set(hosts) - host_set) # remove items from the read in list of hosts
# write to file
with open(r'output.yaml', 'w') as file:
documents = yaml.dump(output, file)