ansible 提供的loops 循环可以有效的提高工作效率,比方说需要创建多个用户,之前需要建立多个task,现在使用loops 可以快速完成。
标准loops 循环:下面是官方给的参考,参考链接 http://docs.ansible.com/ansible/latest/playbooks_loops.html#standard-loops
- name: add several users
user:
name: "{{ item }}"
state: present
groups: "wheel"
with_items:
- testuser1
- testuser2
备注:复制上面的代码,直接执行是不成功的,刚学loops 循环 直接运行无论如何也不能成功,遇到了很多坑。
需要改写如下:
--- - hosts: web tasks: - name: add several users user: name: "{{ item }}" state: present groups: "wheel" with_items: - testuser1 - testuser2
执行 stands.yml ansible-playbook stands.yml
执行效果如下
查看用户是否创建成功
ansible web -m shell -a "id tsetuser1"
用户创建成功
实战演示: 使用loops 循环安装PHP
--- - hosts: web gather_facts: False tasks: - name: install php packages yum: name: "{{ item }}" state: latest with_items: - gcc-c++ - php - php-devel - php-fpm
关于 yum 模块的其他用法,以httpd 为列
name: 安装最新版本的apache
yum: name=httpd state=latest
- name: 移除apache
yum: name=httpd state=absent
- name: 安装一个特殊版本的apache
yum: name=httpd-2.2.29-1.4.amzn1 state=present
- name: 升级所有的软件包
yum: name=* state=latest
- name: 从一个远程yum仓库安装nginx
yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
- name: 从本地仓库安装nginx
yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
- name: 安装整个Development tools相关的软件包
yum: name="@Development tools" state=present
执行 ansible-playbook yum_install_php.yml
执行过程如下
检查php 是否安装成功
ansible web -m shell -a "php -v "
PHP 安装成功