You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从ip_list.yaml读取ip_v4、ip_v6列表至Python的wafv2配置

问题描述

现有两个文件:

  • ip_list.yaml:包含globals节点下的ip_v4、ip_v6等配置
  • network.py:用于创建wafv2.CfnIPSet实例

需要实现从ip_list.yaml中读取globals下ip_v4、ip_v6的所有值,分别填入network.py中ip_set_v4与ip_set_v6的addresses参数对应位置。


现有文件内容

ip_list.yaml

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

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",
)

解决方案

通过Python内置的yaml库读取YAML文件内容,提取对应IP列表后传入参数即可,步骤如下:

  1. 安装依赖
    如果环境未安装pyyaml,先执行安装命令:
pip install pyyaml
  1. 修改network.py代码
    添加YAML读取逻辑,提取IP列表并替换到addresses参数中:
import yaml
from aws_cdk import aws_wafv2 as wafv2

# 读取配置文件
with open('ip_list.yaml', 'r') as f:
    config_data = yaml.safe_load(f)

# 提取IP列表
target_ipv4 = config_data['globals']['ip_v4']
target_ipv6 = config_data['globals']['ip_v6']

# 创建IP规则集
ip_set_v4 = wafv2.CfnIPSet(
    self,
    "IPSetv4",
    addresses=target_ipv4,
    ip_address_version="IPV4",
    name="ipv4-set",
    scope="CLOUDFRONT",
)

ip_set_v6 = wafv2.CfnIPSet(
    self,
    "IPSetv6",
    addresses=target_ipv6,
    ip_address_version="IPV6",
    name="ipv6-set",
    scope="CLOUDFRONT",
)
  1. 注意事项
  • 确保ip_list.yaml与network.py路径匹配,若不在同一目录,需填写完整文件路径
  • 实际使用时,YAML中的IP值需符合标准IPv4/IPv6格式(如192.168.1.1或2001:db8::1),否则WAF会抛出格式错误

内容的提问来源于stack exchange,提问作者Jack Rogers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:01:14