简介
基于已知的文件结构,自动加载某些vars_files,tasks以及handlers。以便playbook更好的调用。roles相比playbook的结构更加清晰有层次
例如:我们无论安装什么软件都会安装时间同步服务,那么playbook要编写时间同步服务的task,此时我们可以将时间同步服务task任务编写好,等到使用的时候进行调用就可以了
最好在编写roles的时候,最好能将一个task拆分为一个文件,方便后续复用(彻底打散)
练习一:配置memcached
目录结构
实现流程
创建roles的目录结构,手动或使用ansible-galaxy init test
编写roles的功能,也就是tasks
最后playbook引用roles编写好的tasks
操作
ansible-galaxy init test
手动创建配置memcached
mkdir -p memcached/{tasks,handlers,templates}
目录结构(引用文件自动会创建在 memcached 下的memcacheds下的memcached.yml这个案例创建在外面也行)
cd memcached
vim tasks/main.yml
- name: installed memcached server
yum: name=memcached state=present
- name: configure memcached server
template: src=memcached.j2 dest=/etc/sysconfig/memcached
notify: service memcached restart
- name: started memcached server
service: name=memcached state=started enabled=yes
vim templates/memcached.j2
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""
vim handlers/main.yml
- name: service memcached restart
service: name=memcached state=restarted
vim ../site.yml
- hosts: webserver
roles:
- memcached
打散方式:
打散后的结构(不建议继续打散)
进入tasks目录
vim install.yml
- name: installed memcached server
yum: name=memcached state=present
vim configure.yml
- name: configure memcached server
template: src=memcached.j2 dest=/etc/sysconfig/memcached
notify: service memcached restart
vim start.yml
- name: started memcached server
service: name=memcached state=started enabled=yes
引入所有
vim main.yml
- include_tasks: install.yml
- include_tasks: configure.yml
- include_tasks: start.yml
执行结果
最后修改配置文件
vim templates/memcached.j2
然后再次执行检测是否触发restart
练习二:配置nginx+php
cd /root/project/
mkdir {nginx,php}/{tasks,handlers,templates,groupvars} -pv
vim nginx/tasks/main.yml
- name: installed nginx server
yum: name=nginx state=present
- name: configure nginx server
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: service nginx restart
- name: started nginx server
service: name=nginx state=started enabled=yes
vim nginx/handlers/main.yml
- name: service nginx restart
service: name=nginx state=restarted
vim nginx/templates/nginx.conf.j2
拷一份nginx配置文件即可
cat /etc/nginx/nginx.conf >nginx/templates/nginx.conf.j2
单独指定启动nginx
vim site.yml
- hosts: webserver
roles:
- role: memcached
tags: memcached
- role: nginx
tags: nginx
ansible-playbook site.yml -t nginx
发布者:LJH,转发请注明出处:https://www.ljh.cool/7193.html