Ansible如何删除AWS路由表指定条目及转换接口输出格式
格式不匹配的原因
这是Ansible AWS类模块的常规设计逻辑:ec2_vpc_route_table_info作为查询类模块,会返回AWS API输出的完整原生字段,包含origin、state、interface_id这类创建路由时不需要的冗余参数,且字段命名和操作类模块不统一:创建路由时用dest统一指代目标CIDR,而查询返回结果会拆分为destination_cidr_block(IPv4)和destination_ipv6_cidr_block(IPv6)两个独立字段,因此无法直接复用。
转换方法
你可以通过Jinja2的列表过滤+字段重构直接完成格式转换,完整的任务示例如下:
1. 先查询路由表全量数据
- name: 获取目标路由表信息 ec2_vpc_route_table_info: region: your_region route_table_ids: - rtb-somestring register: rt_query_result
2. 过滤并转换格式后更新路由表
比如你要删除实例ID为i-to-delete对应的路由,示例代码如下:
- name: 同步删除指定实例对应的路由条目 ec2_vpc_route_table: region: your_region vpc_id: "vpc-somestring" purge_subnets: false purge_routes: true # 开启全量替换路由,才会删除你过滤掉的条目 lookup: id route_table_id: rtb-somestring routes: >- {% set filtered_routes = rt_query_result.route_tables[0].all_routes | rejectattr('instance_id', 'eq', 'i-to-delete') %} {% set formatted_routes = [] %} {% for route in filtered_routes %} {% set _ = formatted_routes.append({ 'dest': route.destination_cidr_block if route.destination_cidr_block else route.destination_ipv6_cidr_block, 'gateway_id': route.gateway_id if route.gateway_id else omit, 'instance_id': route.instance_id if route.instance_id else omit }) %} {% endfor %} {{ formatted_routes }}
注意事项
purge_routes: true会用你传入的路由列表全量覆盖现有路由,一定要确认过滤规则正确,避免误删local网关等默认路由- 过滤规则可以按需调整,比如按
dest匹配要删除的网段,修改rejectattr的参数即可
内容的提问来源于stack exchange,提问作者SipSeb
相关产品推荐
相关产品推荐

