在本章中,我将为您介绍 Ansible 中的循环操作,以及如何在您的 Ansible Playbook 中日常使用它们。

循环的作用

循环用于自动化重复性任务。计算机擅长执行重复性任务,而人类则容易出错。重复执行一组语句的过程称为迭代。Ansible 提供了几种迭代语句,例如 loop 和 with_items。with_items 依赖于插件。

示例 1:简单的循环

文件名:loop_simple.yml

---
- name: Check services
  hosts: all
  tasks:
    - name: httpd and mariadb are running
      ansible.builtin.service:
        name: "{{ item }}"
        state: started
      loop:
        - httpd
        - mariadb
  • 功能:简单的循环会遍历一个项目列表。loop 语句添加到任务中,其值为需要迭代的项目列表。循环变量 item 在每次迭代中表示当前值。

示例 2:循环遍历字典或哈希

文件名:loop_hash_or_dict.yml

---
- name: Users exist and are in the correct groups
  hosts: all
  tasks:
    - name: Users exist and are in the correct groups
      ansible.builtin.user:
        name: "{{ item.name }}"
        state: present
        groups: "{{ item.group }}"
      loop:
        - name: alice
          group: wheel
        - name: bob
          group: root
  • 功能:循环列表中的项目可以是复杂的字典或哈希,而不仅仅是简单值。在本例中,每个字典包含两个键:name 和 group。当前迭代项的值可以通过 item.name 和 item.group 获取。

with_* 语句

with_* 语句是 Ansible 提供的另一种循环方式,用于处理不同类型的列表或数据结构。

with_items

  • 功能:与 loop 类似,用于简单的字符串列表或字典/哈希列表。
  • 特点:如果提供的是嵌套列表,会自动展平为单层列表。

with_file

  • 功能:需要一个控制节点上的文件名列表。循环变量 item 包含文件的内容。

with_sequence

  • 功能:根据数值序列生成一个值列表,需要参数来定义序列。

示例 3:使用 with_items

文件名:loop_with_items.yml

---
- name: Example with_items
  hosts: all
  vars:
    data:
      - alice
      - bob
  tasks:
    - name: Print values of data
      ansible.builtin.debug:
        msg: "{{ item }}"
      with_items: "{{ data }}"
  • 功能:变量 data 是一个字符串列表。任务“Print values of data” 使用 with_items 逐项迭代并打印到屏幕上。

总结

循环语句非常适用于自动化重复性任务。循环是成功编写 Ansible Playbook 的基础。通过循环,您可以更高效地处理多个项目或数据结构,而无需为每个项目编写重复的代码。