循环变量Ansible的多个值

时间:2018-08-15 09:00:23

标签: loops variables ansible

我正在尝试为以下代码中使用的2个变量设置多个值:

- name: Create the subnets
  os_subnet:
     cloud: "{{ item.cloud }}"
     state: present
     validate_certs: no
     no_gateway_ip: yes
     enable_dhcp: yes
     name: "{{ item.subnet }}"
     network_name: "{{ item.network }}"
     cidr: "{{ item.cidr }}"
     allocation_pool_start: "{{ item.allocation_pool_start }}"
     allocation_pool_end: "{{ item.allocation_pool_end }}"
     host_routes:
     - destination: "{{ item.destination | default(omit) }}"
       nexthop: "{{ item.nexthop | default(omit) }}"
  with_items:
  - "{{ subnets }}"
  tags: create_subnets

在我的环境中,某些子网具有不同数量的host_routes或没有。我的变量文件带有一个用于destination + nexthop的变量,现在看起来像:

--- #
subnets:
- { cloud: tenant1, network: nw, subnet: nw_subnet, cidr: 172.10.10.224/27, allocation_pool_start: 172.10.10.228, allocation_pool_end: 172.10.10.254, destination: 10.10.10.0/24, nexthop: 172.10.114.125 }

这有效。但是,如果我的destination + nexthop值不止一个,该如何进行? 我还没有尝试过复制同一行并仅在destination + nexthop最后更改,但是没有用。如果我尝试在同一列表中的同一行中添加另一个destination + nexthop,它将仅取最后一个值。

1 个答案:

答案 0 :(得分:3)

host_routes定义为子网变量中的列表:

subnets: 
- allocation_pool_end: "172.10.10.254"
  allocation_pool_start: "172.10.10.228"
  cidr: 172.10.10.224/27
  cloud: tenant1
  host_routes: 
    - destination: 10.10.10.0/24
      nexthop: "172.10.114.125"
    - destination: YYY.YYY.YYY.YYY/ZZ
      nexthop: XXX.XXX.XXX.XXX
  network: nw
  subnet: nw_subnet
- allocation_pool_end: "172.10.30.254"
  allocation_pool_start: "172.10.30.228"
  cidr: 172.10.30.224/27
  cloud: tenant2
  host_routes: 
    - destination: YYY.YYY.YYY.YYY/ZZ
      nexthop: XXX.XXX.XXX.XXX
  network: nw
  subnet: nw_subnet2

现在您可以在任务中使用它

- name: Ensure subnets are present
  os_subnet:
     cloud: "{{ item.cloud }}"
     state: present
     validate_certs: no
     no_gateway_ip: yes
     enable_dhcp: yes
     name: "{{ item.subnet }}"
     network_name: "{{ item.network }}"
     cidr: "{{ item.cidr }}"
     allocation_pool_start: "{{ item.allocation_pool_start }}"
     allocation_pool_end: "{{ item.allocation_pool_end }}"
     host_routes: "{{ item.host_routes }}"
  with_items:
  - "{{ subnets }}"
  tags: create_subnets