Ansible playbook中role的用法

要使用role首先要创建一个roles目录,这个目录在ansible.cfg里推荐使用/etc/ansible/roles,当然你也可以自己去指定roles的路径:

 使用role,就是把之前的Playbook进行分门别类,所以我们要先在roles目录下创建几个目录方便管理:

[root@localhost ansible]# mkdir roles/{nginx,httpd,mysql,memcache} -pv
mkdir: 已创建目录 "roles/nginx"
mkdir: 已创建目录 "roles/httpd"
mkdir: 已创建目录 "roles/mysql"
mkdir: 已创建目录 "roles/memcache"

 这里以部署nginx服务为例,大致步骤是创建用户组、创建用户并放入组中、安装nginx、修改配置文件、启动服务。

测试前先把之前安装过的nginx卸载,并将其附带的用户和用户组删掉:

[root@localhost ansible]# ansible wyh-test -m shell -a 'yum -y remove nginx'

#删除用户及其所在组
[root@localhost ansible]# ansible wyh-test -m shell -a 'userdel -r nginx'

 验证已经删除成功:

 要调用的playbook必须和roles是平级关系。进入到roles下面具体的project目录后,就要创建这个project的tasks/vars/files/templates...等目录,一般来讲,我们需要执行任务,所以一定会有tasks目录,其他目录可根据自己项目情况自行创建。这里我们创建tasks、templates目录:

 一般建议每个任务单独创建一个文件,所以我们先创建一个文件用来创建用户组。在各个任务文件中不需要再写hosts等信息,只需要定义该任务要做的事情即可:

[root@localhost tasks]# cat group.yml
- name: create group for nginx
  group: name=nginx

[root@localhost tasks]# cat user.yml
- name: create user for nginx
  user: name=nginx group=nginx system=yes shell=/sbin/nologin

[root@localhost tasks]# cat install.yml
- name: install package
  yum: name=nginx
[root@localhost tasks]# cat start.yml
- name: start nginx service
  service: name=nginx state=started enabled=yes
[root@localhost tasks]# cat restart.yml
- name: restart nginx service
  service: name=nginx state=restarted
#将本机上原始的nginx.conf拷贝到templates目录下作为模板文件
[root@localhost templates]# cp /etc/nginx/nginx.conf nginx.conf.j2

对于conf文件的修改,我们假设是对work porcessor进行了配置:

 然后再去tasks目录下创建一个文件用来调用模板文件:

[root@localhost tasks]# cat tmpl.yml
- name: copy nginx conf
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf

定义一个main.yml将上面分散的yml组合在一起:

[root@localhost tasks]# cat main.yml
- include: group.yml
- include: user.yml
- include: install.yml
- include: tmpl.yml
- include: start.yml

最后要创建一个playbook去调用整个project的任务,这个playbook必须是和roles同级:

[root@localhost ansible]# tree
.
├── ansible.cfg
├── hosts
├── nginx-deploy.yml
├── roles
│   ├── httpd
│   ├── memcache
│   ├── mysql
│   └── nginx
│       ├── tasks
│       │   ├── group.yml
│       │   ├── install.yml
│       │   ├── main.yml
│       │   ├── restart.yml
│       │   ├── start.yml
│       │   ├── tmpl.yml
│       │   └── user.yml
│       └── templates
│           └── nginx.conf.j2


[root@localhost ansible]# cat nginx-deploy.yml
- hosts: wyh-test
  remote_user: root
  roles:
    - role: nginx

执行playbook:

[root@localhost ansible]# ansible-playbook nginx-deploy.yml

验证执行结果:

验证端口:

 验证进程(cpu+1): 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QYHuiiQ

听说打赏的人工资翻倍~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值