playbook使用循环

一、背景

在使用playbook创建多个用户、安装多个程序、开始多个服务…的时候,而不是一对一,这样写起来既麻烦且多余,这个时候就需要使用到循环。

二、方法

2.1 使用item…loop

---
- name: use playbook
  hosts: PC02
  tasks:
  - name: crete user
    user:
      name: "{{ item }}"
    loop:
      - user: huange
      - user: liaoge

2.2 数组列表的方式

---
- name: use playbook
  hosts: PC02
  tasks:
  - name: crete user
    user:
      name: "{{ item.user }}"
      group: "{{ item.group }}"
    loop:
      - user: huange
        group: Huan
      - user: liaoge
        group: Huan

2.3 字典方式

---
- name: use playbook
  hosts: PC02
  tasks:
  - name: crete user
    user:
      name: "{{ item.user }}"
      group: "{{ item.group }}"
    loop:
      - { user: "huange" , group: "Huan" }
      - { user: "liaoge" , group: "Huan" }

2.4 register和loop一起使用(输出结果)

---
- name: use playbook
  hosts: PC02
  tasks:
  - name: crete user
    user:
      name: "{{ item }}"
    register: echo_result
    loop:
      - user: huange
      - user: liaoge
  - name: debug
      var: echo_result.results

你可能感兴趣的:(ansible,ansible)