迭代:当有需要重复性执行的任务时,可以使用迭代机制
对迭代项的引用,固定变量名为 “item”
要在task中使用with_items给定要迭代的元素列表

列表元素格式:

字符串
字典

范例:

cat with_items.yaml 
- hosts: test
  remote_user: root
  tasks:
    - name: add several users
      user: name={{ item }} state=present groups=wheel
      with_items: 
        - testuser1
        - testuser2
cat with_items2.yaml 
- hosts: test
  tasks:
    - name: install some package
      yum: name={{ item }} state=present
      with_items:
        - nginx
        - memcached
        - php-fpm

迭代嵌套子变量:在迭代中,还可以嵌套子变量,关联多个变量在一起使用
示例:

cat with_itmes3.yaml 
- hosts: test
  tasks:
    - name: add some groups
      group: name={{ item }} state=present
      with_items:
        - g1
        - g2
        - g3
    - name: add some users
      user: name={{ item.name }} group={{ item.group }} state=present
      with_items:
        - { name: 'user1', group: 'g1' }
        - { name: 'user2', group: 'g2' }
        - { name: 'user3', group: 'g3' }