ansible——playbook的模块
Posted 封玖FJ
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ansible——playbook的模块相关的知识,希望对你有一定的参考价值。
playbook的模块
1. 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行,修改 <Directory "root_dir"> #131修改 配置目录访问权限
2. 修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量
vim /etc/ansible/hosts
[webservers]
192.168.163.136 http_port=192.168.163.136:80 server_name=www.lisi.com:80 root_dir=/etc/httpd/htdocs
[dbservers]
192.168.163.139 http_port=192.168.163.139:80 server_name=www.zhangsan.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
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
4. 制作测试网页
ansible 192.168.163.138 -m shell -a "echo this is lisi template test > /etc/httpd/htdocs/index.html" #制作网页测试文件
ansible 192.168.163.139 -m shell -a "echo this is zhangsan template test > /etc/httpd/htdocs/index.html"
http://192.168.163.138
http://192.168.163.139
#登录访问查看
2. 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"
ansible webservers -a "ls /opt/"
----------------------------------------------------------------
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"
以上是关于ansible——playbook的模块的主要内容,如果未能解决你的问题,请参考以下文章