- 进入到
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’] }