【问题标题】:Constructing a loop in Ansible在 Ansible 中构建循环
【发布时间】:2019-10-20 14:49:30
【问题描述】:

我正在编写一个设置网络的 Ansible 角色。对于每种类型的接口(以太网、绑定、网桥和 vlan),我创建了一个包含相关数据的变量。 这个想法是我必须创建一个循环,该循环运行列表变量('bridge_ports')中元素的次数,并且每次传递都通过模板创建一个配置文件。

桥接接口的部分变量如下所示:

my_network__bridge_interface:
    address: "192.168.1.48",
    bootproto: "static",
    bridge_ports:
        - eth0
        - eth1
    device: "br-mgmt",
    ...

为了通过,我尝试了一个 with_subelements 循环 - 但这并不顺利。

- name: Create the network configuration file for the port on the bridge devices
  template:
    src: "{{ ansible_os_family }}.bridge_port.j2"
    dest: "{{ my_network__ifconf_path }}/ifcfg-{{ item.1 }}"
  with_subelements
    - "{{ my_network__bridge_interface }}"
    - bridge_ports
  when: device_conf.type == 'bridge'
  register: my_network__bridge_port_result

当我运行代码时,出现错误消息:“在迭代项'{}'中找不到'bridge_ports'键”。

我可以看到我以错误的方式使用 with_subelements,但我真的不知道我需要什么类型的循环。

【问题讨论】:

标签: loops ansible


【解决方案1】:

问题在于 yml 定义。以下 yml 有效:

my_network__bridge_interface:

  - address: "192.168.1.48"
    bootproto: static
    bridge_ports:
      - eth0
      - eth1
    device: br-mgmt   

剧本-->

    ---
    - hosts: localhost
      tasks:
        - include_vars: vars.yml
        - debug:
            msg: "{{ item.1 }}"
          with_subelements:
            - "{{ my_network__bridge_interface }}"
            - bridge_ports

输出 -->

TASK [debug] ****************************************************************************************************************************
ok: [localhost] => (item=[{u'device': u'br-mgmt', u'bootproto': u'static', u'address': u'192.168.1.48'}, u'eth0']) => {
    "msg": "eth0"
}
ok: [localhost] => (item=[{u'device': u'br-mgmt', u'bootproto': u'static', u'address': u'192.168.1.48'}, u'eth1']) => {
    "msg": "eth1"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多