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

Ansible带条件循环配置求助:按主机名选择IP执行命令

问题修复方案

你的Ansible配置存在语法错误和可优化点,以下是具体修复方案:

修正循环写法

先解决原配置里的核心语法问题,调整后代码如下:

- name: logs
  ios_command:
    commands:
      - show ip bgp vpnv4 vrf SIG neighbors {{ item.ip }} routes
      - show ip bgp vpnv4 vrf SIG neighbors {{ item.ip }} advertised-routes
  register: grx_cfg
  when: item.when
  with_items:
    - { ip: '1.1.1.1', when: ansible_host == 'A' }
    - { ip: '2.2.2.2', when: ansible_host == 'B' }

关键修正点:

  • 补全with_items字典中when字段的冒号,符合YAML键值对语法要求
  • 去掉条件表达式外层的双引号和模板标记{{ }},直接写布尔表达式即可,Ansible会自动解析判断

更简洁的替代方案(无需循环)

如果只是根据主机名二选一执行命令,没必要用循环,直接通过条件变量定义或模板判断更高效:

方案1:命令内直接判断

- name: logs
  ios_command:
    commands:
      - show ip bgp vpnv4 vrf SIG neighbors {% if ansible_host == 'A' %}1.1.1.1{% else %}2.2.2.2{% endif %} routes
      - show ip bgp vpnv4 vrf SIG neighbors {% if ansible_host == 'A' %}1.1.1.1{% else %}2.2.2.2{% endif %} advertised-routes
  register: grx_cfg

方案2:先定义变量再引用

- name: logs
  vars:
    bgp_neighbor_ip: "{{ '1.1.1.1' if ansible_host == 'A' else '2.2.2.2' }}"
  ios_command:
    commands:
      - show ip bgp vpnv4 vrf SIG neighbors {{ bgp_neighbor_ip }} routes
      - show ip bgp vpnv4 vrf SIG neighbors {{ bgp_neighbor_ip }} advertised-routes
  register: grx_cfg

这两种写法逻辑更直接,避免了循环带来的冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:15:36