Ansible系列基础篇 1.7.2、PlayBook之循环

一、循环定义

 循环可迭代对象,重复处理每条信息。

 基础示例:

---
- hosts: test70
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items:
    - 1
    - 2
    - 3
    # 也可以 with_items: [1,2,3]

  

使用内置变量循环,示例如下:

---
- hosts: test70
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items: "{{groups.ungrouped}}"

  

复杂字段的循环,示例如下:

---
- hosts: test70
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item.test1}}"
    with_items:
    - { test1: a, test2: b }
    - { test1: c, test2: d }

  

循环结果的存储与读取,通过register,把模块执行的结果存储到变量中,命令的结果,以列表形式存在returnvalue.results,示例如下:

---
- hosts: test70
  gather_facts: no
  tasks:
  - shell: "{{item}}"
    with_items:
    - "ls /opt"
    - "ls /home"
    register: returnvalue
  - debug:
      msg: "{{item.stdout}}"
    with_items: "{{returnvalue.results}}"

  

二、循环特殊关键字

2.1、with_list

当处理单层的简单列表时,with_list与with_items没有任何区别,只有在处理上例中的"嵌套列表"时,才会体现出区别,区别就是,with_items会将嵌套在内的小列表"拉平",拉平后循环处理所有元素,而with_list则不会"拉平"嵌套的列表,with_list只会循环的处理列表(最外层列表)中的每一项。

with_items的嵌套的列表(序列中的序列),示例如下:

# 结果为 1, 2, 3, a, b
# 每个循环的列表项,也展开
---
- hosts: test70
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items:
    - [ 1, 2, 3 ]
    - [ a, b ]

  

使用with_list:

# 结果为 [1, 2, 3], [a, b]
# 外层列表循环,每个项的列表内容不循环
---
- hosts: test70
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_list:
    - [ 1, 2, 3 ]
    - [ a, b ]

  

2.2、with_flattened

该关键字与with_items效果完全相同

2.3、with_together

两列表一一对应聚合,示例如下:

# 结果为: [1, a], [2, b], [3, c]
---
- hosts: test70
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{ item }}"
    with_together:
    - [ 1, 2, 3 ]
    - [ a, b, c ]

如果两列表长度不一致,一一对应时,无数据的,用null补齐。 

 2.4、with_cartesian

1

原文地址:https://www.cnblogs.com/wangsl1204/p/14193882.html