Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to read specific lines of list in yaml to python

I have 2 files, first is ip_list.yaml which is

globals:
  hosted_zone: "test.com"
  endpoint_prefix: defalt
  ip_v4:
    - 123
    - 234
    - 456
      
  ip_v6:
    - 123
    - 234
    - 345

and the other one is network.py

# Creating IP rules sets
        ip_set_v4 = wafv2.CfnIPSet(
            self,
            "IPSetv4",
            addresses=[
                # how do i parse the ip_v4 from ip_list.yaml
            ],
            ip_address_version="IPV4",
            name="ipv4-set",
            scope="CLOUDFRONT",
        )

        ip_set_v6 = wafv2.CfnIPSet(
            self,
            "IPSetv6",
            addresses=[
                # how do i parse the ip_v6 from ip_list.yaml
            ],
            ip_address_version="IPV6",
            name="ipv6-set",
            scope="CLOUDFRONT",
        )

how do i read only all values under ip_v4 and ip_v6 from ip_list.yaml then respectively put them in network.py addresses for both ip_set_v4 and ip_set_v6? (where i put the comment in network.py)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the pyyaml library to parse the YAML file and extract the values you need like this-

import yaml

# Load the YAML file
with open("ip_list.yaml", "r") as f:
    data = yaml.safe_load(f)

# Extract the values for ip_v4 and ip_v6
ip_v4 = data["globals"]["ip_v4"]
ip_v6 = data["globals"]["ip_v6"]

# Use the values in the network.py script
ip_set_v4 = wafv2.CfnIPSet(
    self,
    "IPSetv4",
    addresses=ip_v4,     # <-----------------
    ip_address_version="IPV4",
    name="ipv4-set",
    scope="CLOUDFRONT",
)

ip_set_v6 = wafv2.CfnIPSet(
    self,
    "IPSetv6",
    addresses=ip_v6,     # <-----------------
    ip_address_version="IPV6",
    name="ipv6-set",
    scope="CLOUDFRONT",
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading