针对大型项目使用Roles进行编排,更便利
目录结构编排
一键安装httpd并提供服务
创建目录结构
[[email protected] ansible]# mkdir -p roles/httpd/{tasks,files,vars}
[[email protected] ansible]# cd roles/httpd/tasks
[[email protected] roles]#touch httpd/{files/main.yml,tasks/{groupadd.yml,install.yml,main.yml,restart.yml,useradd.yml},vars/main.yml}
目录结构创建好了,接下来开始配置
[[email protected] ~]# cd /root/ansible/roles/httpd/tasks
首先配置main.yml将所有的配置全部包含进来
[[email protected] tasks]# cat main.yml
---
- include: groupadd.yml
- include: useradd.yml
- include: install.yml
- include: restart.yml
配置添加用户组
[[email protected] tasks]# cat groupadd.yml
---
- name: add group httpd
group: name=web state=present
配置添加用户
[[email protected] tasks]# cat useradd.yml
---
- name: add group httpd
user: name=httpd groups=web system=yes state=present
配置安装httpd
[[email protected] tasks]# cat install.yml
---
- name: Install Httpd
yum: name=httpd state=present
配置restart httpd
[[email protected] tasks]# cat restart.yml
---
- name: Restart Httpd
service: name=httpd state=restarted
配置主yml文件
[[email protected] roles]# pwd
/root/ansible/roles
[[email protected] roles]# cat installhttpd.yml
---
- hosts: test
remote_user: root
roles:
- role: httpd
测试
提供配置网站文件
[[email protected] files]# pwd
/root/ansible/roles/httpd/files
[[email protected] files]# cat index.html
<h1> test </h1>
创建copy模块的文件
[[email protected] tasks]# cat filecp.yml
---
- name: Cp DocumentFile
copy: src=index.html dest=/var/www/html/index.html
将文件包含至main
[[email protected] tasks]# cat main.yml
---
- include: groupadd.yml
- include: useradd.yml
- include: install.yml
- include: restart.yml
- include: filecp.yml
测试:
roles还可以引用
例:
[[email protected] roles]# pwd
/root/ansible/roles
[[email protected] roles]# cp httpd/ nginx -rf
[[email protected] roles]# cd nginx/tasks/
[[email protected] tasks]# rm -rf *
[[email protected] roles]# cd nginx/tasks/
[[email protected] tasks]# cat main.yml
---
- include: httpd/tasks/restart.yml
[[email protected] roles]# cp installhttpd.yml installnginx.yml
[[email protected] roles]# cat installnginx.yml
---
- hosts: test
remote_user: root
roles:
- role: nginx
测试:
拓展:
1、一次性执行多个roles
2、对roles进行打标签,可单独执行
测试
3、多重标签
执行web项目