2.6 迭代
Ansible提供了很多种循环结构,一般都命名为with_items,作用等同于 loop 循环。
vim test4.yaml - hosts: dbservers gather_facts: false tasks: - name: create directories file: path: "{{item}}" state: directory with_items: #等同于 loop: - /tmp/test1 - /tmp/test2 - name: add users user: name={{item.name}} state=present groups={{item.groups}} with_items: - name: test1 groups: wheel - name: test2 groups: root 或 with_items: - {name:'test1', groups:'wheel'} - {name:'test2', groups:'root'} ansible-playbook test3.yaml
2.7 Templates 模块
Jinja是基于Python的模板引擎。Template类是Jinja的一个重要组件,可以看作是一个编译过的模板文件,用来产生目标文本,传递Python的变量给模板去替换模板中的标记。
1.先准备一个以 .j2 为后缀的 template 模板文件,设置引用的变量
cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2 vim /opt/httpd.conf.j2 Listen {{http_port}} #42行,修改 ServerName {{server_name}} #95行,修改 DocumentRoot "{{root_dir}}" #119行,修改
2.修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量
vim /etc/ansible/hosts [webservers] 192.168.147.106 http_port=192.168.147.106:80 server_name=www.zhangsan.com:80 root_dir=/etc/httpd/htdocs [dbservers] 192.168.147.107 http_port=192.168.147.107:80 server_name=www.lisi.com:80 root_dir=/etc/httpd/htdocs
3.编写 playbook
vim apache.yaml --- - hosts: all remote_user: root vars: - package: httpd - service: httpd tasks: - name: install httpd package yum: name={{package}} state=latest - name: install configure file template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #使用template模板 notify: - restart httpd - name: create root dir file: path=/etc/httpd/htdocs state=directory - name: start httpd server service: name={{service}} enabled=true state=started handlers: - name: restart httpd service: name={{service}} state=restarted ansible-playbook apache.yaml
2.8 tags 模块
可以在一个 playbook 中为某个或某些任务定义“标签”,在执行此 playbook 时通过 ansible-playbook 命令使用 --tags 选项能实现仅运行指定的tasks。
playbook还提供了一个特殊的 tags 为 always 。作用就是当使用 always 当 tags 的 task 时,无论执行哪一个 tags 时,定义有 always 的tags 都会执行。
vim webhosts.yaml - hosts: webservers remote_user: root tasks: - name: Copy hosts file copy: src=/etc/hosts dest=/opt/hosts tags: - only #可自定义 - name: touch file file: path=/opt/testhost state=touch tags: - always #表示始终要运行的代码 ansible-playbook webhosts.yaml --tags="only"
vim dbhosts.yaml - hosts: dbservers remote_user: root tasks: - name: Copy hosts file copy: src=/etc/hosts dest=/opt/hosts tags: - only - name: touch file file: path=/opt/testhost state=touch ansible-playbook dbhosts.yaml --tags="only"
分别去两台被管理主机上去查看文件创建情况