Playbook 使用迭代 with_items
迭代:当有需要重复性执行的任务时,可以使用迭代机制
对迭代项的引用,固定变量名为 “item
”
要在 task 中使用 with_items
给定要迭代的元素列表
列表元素格式:
- 字符串
- 字典
示例1:循环创建用户
---
- hosts: websrvs
remote_user: root
tasks:
- name: add several users
user: name= state=present groups=wheel
with_items:
- testuser1
- testuser2
# 上面语句的功能等同于下面的语句
- name: add user testuser1
user: name=testuser1 state=present groups=wheel
- name: add user testuser2
user: name=testuser2 state=present groups=wheel
示例2:循环删除文件
---
# remove mariadb server
- hosts: appsrvs:!192.168.38.8
remote_user: root
tasks:
- name: stop service
shell: /etc/init.d/mysqld stop
- name: delete files and dir
file: path= 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
- /data/mysql
- name: delete user
user: name=mysql state=absent remove=yes
示例3:循环安装软件
---
- hosts:websrvs
remote_user: root
tasks
- name: install some packages
yum: name= state=present
with_items:
- nginx
- memcached
- php-fpm
示例4:循环拷贝文件及安装软件
---
- hosts: websrvs
remote_user: root
tasks:
- name: copy file
copy: src= dest=/tmp/
with_items:
- file1
- file2
- file3
- name: yum install httpd
yum: name= state=present
with_items:
- apr
- apr-util
- httpd
迭代嵌套子变量:在迭代中,还可以嵌套子变量,关联多个变量在一起使用
示例1:
---
- hosts: websrvs
remote_user: root
tasks:
- name: add some groups
group: name= state=present
with_items:
- nginx
- mysql
- apache
- name: add some users
user: name= group= state=present
with_items:
- { name: 'nginx', group: 'nginx' }
- { name: 'mysql', group: 'mysql' }
- { name: 'apache', group: 'apache' }
示例2:
---
- hosts: websrvs
remote_user: root
tasks:
- name: add some groups
group: name= state=present
with_items:
- g1
- g2
- g3
- name: add some users
user: name= group= home= create_home=yes state=present
with_items:
- { name: 'user1', group: 'g1', home: '/data/user1' }
- { name: 'user2', group: 'g2', home: '/data/user2' }
- { name: 'user3', group: 'g3', home: '/data/user3' }