ansible之loops,ansibleloops


有时候,你想在一个task进行很多重复的操作,例如创建用户、安装包、或者重复执行一个操作直到某个希望的状态。

Standard Loops 标准循环

为了少打一些字,可以这样写重复的任务:

- name: add several users
  user:
    name: "{{ item }}"
    state: present
    groups: "wheel"
  with_items:
     - testuser1
     - testuser2

如果有定义了yaml格式的list在变量文件中,或变量段落,可以这样做:

with_items: "{{ somelist }}"

上面的例子,等价于:

- name: add user testuser1
  user:
    name: "testuser1"
    state: present
    groups: "wheel"
- name: add user testuser2
  user:
    name: "testuser2"
    state: present
    groups: "wheel"

所以呢,用loops更加灵活。

yum和apt模块可以用with_item来执行较少的包管理事务。

  • 注意
    用with_items来迭代的时候,其值不一定是字符串,还可以是哈希(hashes):
- name: add several users
  user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  with_items:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }

这样会更加灵活。

loops其实是with_<lookup>的组合,所以任何<lookup>都可以当做源来迭代,上面的例子就是用了items这个<lookup>

Looping over Hashes从哈希列表循环

假设我定义了这样一个变量:

---
users:
  alice:
    name: Alice Appleworth
    telephone: 123-456-7890
  bob:
    name: Bob Bananarama
    telephone: 987-654-3210

我现在要打印出名字和电话,可以用with_dict从哈希中取值:

tasks:
  - name: Print phone records
    debug:
      msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    with_dict: "{{ users }}"

格式化输出,挺好用的。

Looping over Files 从文件中循环

with_file可以遍历文件列表的内容,item将按顺序设置为每个文件的内容:

---
- hosts: all

  tasks:

    # emit a debug message containing the content of each file.
    - debug:
        msg: "{{ item }}"
      with_file:
        - first_example_file
        - second_example_file

假如第一个文件内容为hello,第二个文件内容为world,那么上面的执行结果如下:

TASK [debug msg={{ item }}] ******************************************************
ok: [localhost] => (item=hello) => {
    "item": "hello",
    "msg": "hello"
}
ok: [localhost] => (item=world) => {
    "item": "world",
    "msg": "world"
}

相关内容

    暂无相关文章