Loop循环

标准循环

为了保持简洁,重复的任务可以用以下简写的方式:

  1. - name: add several users
  2. user: name={{ item }} state=present groups=wheel
  3. with_items:
  4. - testuser1
  5. - testuser2

如果你在变量文件中或者 ‘vars’ 区域定义了一组YAML列表,你也可以这样做:

  1. vars:
  2. somelist: ["testuser1", "testuser2"]
  3. tasks:
  4. -name: add several user
  5. user: name={{ item }} state=present groups=wheel
  6. with_items: "{{somelist}}"

使用 ‘with_items’ 用于迭代的条目类型不仅仅支持简单的字符串列表.如果你有一个哈希列表,那么你可以用以下方式来引用子项:

  1. - name: add several users
  2. user: name={{ item.name }} state=present groups={{ item.groups }}
  3. with_items:
  4. - { name: 'testuser1', groups: 'wheel' }
  5. - { name: 'testuser2', groups: 'root' }

注意:如果同时使用 when 和 with_items (或其它循环声明),when声明会为每个条目单独执行.请参见 the_when_statement 示例.

嵌套循环

循环也可以嵌套:

  1. - name: give users access to multiple databases
  2. mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
  3. with_nested:
  4. - [ 'alice', 'bob' ]
  5. - [ 'clientdb', 'employeedb', 'providerd']

或者

  1. - name: give users access to multiple databases
  2. mysql_user: name={{ item.0 }} priv={{ item.1 }}.*:ALL append_privs=yes password=foo
  3. with_nested:
  4. - [ 'alice', 'bob' ]
  5. - [ 'clientdb', 'employeedb', 'providerd']

对哈希表使用循环

  1. ---
  2. vars:
  3. alice:
  4. name: Alice Appleworth
  5. telephone: 123-456-7890
  6. bob:
  7. name: Bob Bananarama
  8. telephone: 987-654-3210
  9. tasks:
  10. - name: Print phone records
  11. debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
  12. with_dict: "{{users}}"

对文件列表使用循环

with_fileglob 可以以非递归的方式来模式匹配单个目录中的文件.如下面所示:

  1. tasks:
  2. # first ensure our target directory exists
  3. - file: dest=/etc/fooapp state=directory
  4. # copy each file over that matches the given pattern
  5. - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
  6. with_fileglob:
  7. - /playbooks/files/fooapp/*