简体   繁体   中英

Having a problem to parse Yaml file with python

I have the below section in YML file and I'm trying to read the IP address and hostname of the servers in order to verify that I don't have duplication (can see each IP once and each hostname)

I'm failing at the first stage while trying to ready the IP address. WIll be happy to get help with both reading and verify there is no duplication

Thank you

import yaml


with open(r'.\environment.yml') as file:
    environment = yaml.load(file, Loader=yaml.FullLoader)
print(environment ['server_details']['ip'])
YML File
server_details: - {ip: "{{ yum_repository.ip }}" , hostname: "{{ yum_repository.hostname }}"} - {ip: "{{ cloudera_managment_server.ip }}" , hostname: "{{ cloudera_managment_server.hostname }}"} - {ip: "{{ postgres_server.ip }}" , hostname: "{{ postgres_server.hostname }}"} - {ip: 10.201.51.30 , hostname: master1} - {ip: 10.201.51.31 , hostname: master2} - {ip: 10.201.51.32 , hostname: master3} - {ip: 10.201.51.36 , hostname: worker1} - {ip: 10.201.51.37 , hostname: worker2} - {ip: 10.201.51.38 , hostname: worker3} - {ip: 10.201.51.39 , hostname: kafka1} - {ip: 10.201.51.40 , hostname: kafka2} - {ip: 10.201.51.41 , hostname: kafka3} - {ip: 10.201.51.44 , hostname: gw1}

As @AdamSmith mentioned, you should traverse(or index) list first.

import yaml


with open(r'.\environment.yml') as file:
    environment = yaml.load(file, Loader=yaml.FullLoader)
for server_detail in environment['server_details']:
    print(server_detail['ip'])

You can make it list, too

ip_list = [server_detail['ip'] for server_detail in environment['server_details']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM