注意:学习ansible的roles前,请一定先学习playbook!!!
注意:学习ansible的roles前,请一定先学习playbook!!!
注意:学习ansible的roles前,请一定先学习playbook!!!

官方文档:https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html

角色目录树:

1
2
3
4
5
6
7
8
9
10
11
12
13
roles/
common/ # this hierarchy represents a "role"
tasks/ #
main.yml # <-- tasks file can include smaller files if warranted
handlers/ #
main.yml # <-- handlers file
templates/ # <-- files for use with the template resource
ntp.conf.j2 # <------- templates end in .j2
files/ #
bar.txt # <-- files for use with the copy resource
foo.sh # <-- script files for use with the script resource
vars/ #
main.yml # <-- variables associated with this role

以上,是在工作学习过程中较为通用并且使用频率最高的,官网介绍的其他目录可以通过官网等渠道自行学习!

示例

我们以创建一个部署nginx的roles为例:

创建roles目录:

1
mkdir -p roles/<角色名>/{tasks, handlers, templates, files, vars}

创建各个文件:

nginx/tasks/main.yaml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
- name: Add group www
group:
name: '{{ user_group }}'
gid: 1000

- name: Add user www
user:
name: '{{ user_group }}'
group: '{{ user_group }}'
nocreatehome: yes
shell: /sbin/nologin

- name: Install package
yum:
name: nginx
state: present

- name: template nginx.conf.j2
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx_conf
notify:
- Restart nginx

- name: Start Nginx
systemd:
name: nginx
state: started
enabled: yes

nginx/handlers/main.yaml文件

1
2
3
4
- name: Restart nginx
systemd:
name: nginx
state: restarted

nginx/templates/nginx.conf.j2文件(这个配置文件不全,照抄是不对的,仅用作示例)

1
2
3
4
server {
listen {{ nginx_port }};
server_name {{ ansible_hostname }}; // ansible_hostname, 这是ansible内置的变量
}

nginx/vars/main.yaml文件

1
2
user_group: www
nginx_port: 80

playbook的入口文件roles_nginx.yaml(与roles在同一个目录):

1
2
3
4
- hosts: web
remote_user: root
roles:
- nginx

部署

使用命令执行部署就可以了:

1
ansible-playbook roles_nginx.yaml