当有需要重复性执行的任务时,可以使用迭代机制。
迭代 with_items(loop)
- 对迭代项的引用,固定内置变量名为”item”
- 要在task中使用with_items给定要迭代的元素列表
- 注意: ansible2.5版本后,可以用loop代替with_items
- 列表元素格式:字符串、字典
范例
批量创建用户
---
- hosts: webservers
tasks:
- name: add several users
user: name={{ item }} state=present group=nobody
with_items:
- testuser1
- testuser2
- testuser3
批量卸载mariadb文件
---
- hosts: webservers
tasks:
- name: Stop service
shell: /etc/init.d/mysqld stop
- name: Delete files
file: path={{ item }} state=absent
with_items:
- /usr/local/mysql
- /usr/local/mariadb-10.2.27-linux-x86_64
- /etc/init.d/mysqld
- /etc/profile.d/mysql.sh
- /etc/my.cnf
- name: Delete user
user: name=mysql state=absent remove=yes
安装多个软件包时,不建议使用循环
---
#yum使用循环会提示warning
- hosts: webservers
tasks:
- name: Install packages
yum: name={{ item }} state=present
with_items:
- nginx
- sl
- php-fpm
警告信息
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name: ['nginx', 'sl', 'php-fpm']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.xxxxxxxxxx [DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name: ['nginx', 'sl', 'php-fpm']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.1
解决办法是:直接用列表列出软件包
---
#不使用循环
- hosts: webservers
tasks:
- name: Install packages
yum:
name: [nginx,sl,php-fpm]
state: present
批量复制文件
---
- hosts: webservers
tasks:
- name: Copy file
copy: src={{ item }} dest=/tmp/{{ item }}
with_items:
- file1
- file2
- file3
迭代嵌套子变量
在迭代中,还可以嵌套子变量,关联多个变量在一起使用。
范例
批量创建组和用户并指定uid
---
- hosts: webservers
tasks:
- name: Create group
group: name={{ item }} state=present
with_items:
- group1
- group2
- group3
- name: Create user
user: name={{ item.user }} state=present group={{ item.group }} create_home=no uid={{ item.uid }}
with_items:
- {user: "user1", group: "group1", uid: "1111"}
- {user: "user2", group: "group2", uid: "2222"}
- {user: "user3", group: "group3", uid: "3333"}
util循环
until为false时才会执行循环,为true则退出循环。
范例
显示5次信息后退出
---
- hosts: webservers
tasks:
- debug:
msg: "until"
until: false
retries: 5
with_lines 逐行处理
显示进程信息
---
- hosts: webservers
tasks:
- debug:
msg: "{{ item }}"
with_lines: ps aux