文章目录
- 一、Template模块
- 1、准备template模板文件
- 2、修改主机清单文件
- 3、编写playbook
- 4、执行playbook
- 5、准备测试网页
- 6、访问测试
- 二、tags模块
- 1、编写脚本
- 2、执行tags="xx01"
- 3、执行tags="xx02"
一、Template模块
- Jinja是基于Python的模块引擎。Template类是Jinja的一个重要组件,可以看做是一个编译过的模板文件,用来产生目标文本,传递Python的变量给模板去替换模板中的标记。
- 是一种创建配置文件的工具,在配置文件中,有一些数据会有动态的改变(如:ip、主机名、端口、用户、页面路径等)需要使用变量来表示
- template模块就是将变量和动态文件结合起来,最终生成一个配置文件(需要动态改变)
- 文件配置使用jinjia2模板语言编写,一定是以.j2结尾
1、准备template模板文件
- 先准备一个以.j2为后缀的template模板文件,设置引用的变量
- 模板文件使用test1曾用的httpd.conf配置文件
cp nginx.conf nginx.conf.j2
vim nginx.conf.j2
listen {{nginx_port}};
server_name {{server_name}};
root {{root_dir}};

2、修改主机清单文件
- 修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量
vim /etc/ansible/hosts [webservers]
192.168.10.12 nginx_port=192.168.10.12:80 server_name=www.liu.com:80 root_dir=/etc/nginx/htdocs
[dbservers]
192.168.10.13 nginx_port=192.168.10.13:80 server_name=www.yan.com:80 root_dir=/etc/nginx/htdocs

vim /etc/hosts
192.168.10.12 www.liu.com
192.168.10.13 www.yan.com

3、编写playbook
vim deam05.yaml
---
- name: install nginxhosts: allremote_user: rootvars:- pck: nginx- ser: nginxtasks:- name: install nginx pckyum: name={{pck}} state=latest- name: install configure filetemplate: src=/opt/nginx.conf.j2 dest=/etc/nginx/nginx.confnotify:- restart nginx- name: create root dirfile: path=/etc/nginx/htdocs state=directory- name: start nginx serverservice: name={{ser}} enabled=true state=startedhandlers:- name: restart nginxservice: name={{ser}} state=restarted

4、执行playbook
ansible-playbook deam05.yaml

5、准备测试网页
ansible 192.168.10.12 -m shell -a "echo 'this is template liu' > /etc/nginx/htdocs/index.html"
ansible 192.168.10.13 -m shell -a "echo 'this is template yan' > /etc/nginx/htdocs/index.html"

6、访问测试
curl 192.168.10.12
curl 192.168.10.13
curl www.liu.com
curl www.yan.com

二、tags模块
- 可以在一个playbook中为某个或某些任务定义“标签”,在执行此playbook时通过ansible-playbook命令使用–tags选项能实现仅运行指定的tasks。
- playbook还提供了一个特殊的tags为always。作用就是当使用always当tags的task时,无论执行哪一个tags时,定义有always的tags都会执行。
1、编写脚本
vim deam06.yaml
---
- name: tagshosts: webserversremote_user: roottasks:- name: mkdir directoryfile: path=/opt/liuyanfen/ state=directorytags:- always- name: touch filefile: path=/opt/liuyanfen/test state=touchtags:- xx01- name: copy hosts filecopy: src=/etc/hosts dest=/opt/hoststags:- xx02

2、执行tags=“xx01”
ansible-playbook deam06.yaml --tags="xx01"

ansible webservers -a "ls -l /opt/liuyanfen"

3、执行tags=“xx02”
ansible webservers -m file -a "path=/opt/liuyanfen/ state=absent"
ansible webservers -a "ls -l /opt/liuyanfen"

ansible-playbook deam06.yaml --tags="xx02"

ansible webservers -a "ls -l /opt/liuyanfen"
ansible webservers -a "ls -l /opt/hosts"
