how to read specific lines of list in yaml to python

Question:

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)

Asked By: Jack Rogers

||

Answers:

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",
)
Answered By: Always Sunny
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.