ansible:roles学习笔记

  • 进入到tasks目录中创建任务

任务一:创建组

[root@localhost tasks]# cat group.yml


  • name: create group

group: name=nginx

任务二:创建用户

[root@localhost tasks]# cat user.yml


  • name: create user

user: name=nginx group=nginx system=yes shell=/sbin/nologin

任务三:安装服务

[root@localhost tasks]# cat yum.yml


  • name: install nginx

yum: name=nginx

任务四:服务启动

[root@localhost tasks]# cat start.yml


  • name: start service

service: name=nginx state=started enabled=yes

任务五:重启服务(可以放在handlers里)

[root@localhost tasks]# cat restart.yml


  • name: restart service

service: name=nginx state=restarted

任务六:调用模板

[root@localhost tasks]# cat temp.yml


  • name: copy conf

template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf

  • 进入模板文件夹目录中创建模板文件

模板一:创建nginx配置文件模板(以下只说明改动部分)

启动的进程数,其他配置不变

worker_processes {{ ansible_processor_vcpus+2 }};

  • tasks目录创建总的调用文件main.yml

[root@localhost tasks]# cat main.yml


  • include: group.yml

  • include: user.yml

  • include: yum.yml

  • include: temp.yml

  • include: start.yml

  • 回到ansible目录下创建剧本(与roles平级)

创建nginx_roles.yml剧本

[root@localhost ansible]# cat nginx_roles.yml


  • hosts: web

remote_user: root

roles:

  • role: nginx
  • 测试执行剧本,测试成功后就可以实际执行了(我的是测试成功的)

[root@localhost ansible]# ansible-playbook -C nginx_roles.yml

测试成功后执行

[root@localhost ansible]# ansible-playbook nginx_roles.yml

  • 此roles的所有文件结构

[root@localhost ~]# tree /ansible/

/ansible/

├── nginx_roles.yml

└── roles

├── httpd

├── mysql

└── nginx

├── tasks

│ ├── group.yml

│ ├── main.yml

│ ├── restart.yml

│ ├── start.yml

│ ├── temp.yml

│ ├── user.yml

│ └── yum.yml

└── templates

└── nginx.conf.j2

6 directories, 9 files

  • 其他的项目服务做法类似就不写了

同时运行多个角色

  • 比如我要在远程主机上同时安装nginx和PHP两个服务

  • hosts: web

remote_user: root

roles:

  • role: nginx

  • role: php

  • 不如我想在本项目中调用其他项目中的文件,可以这样写:

include: roles/httpd/tasks/file.yml

  • 标签:tags,可以给项目定义标签,调用时使用标签,运行时加-t 标签就会只执行带有标签的项目,而且还可以加条件判断等

roles:

  • { role: nginx, tags: [‘web’,‘nginx’] }
  • 19
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值