06Ansible角色

Ansible角色

roles是在ansible中,playbooks的目录组织结构。

而模块化之后,成为roles的组织结构,易读,代码可重用,层次清晰。

需求:通过role远程部署nginx并配置

准备目录结构

[root@ansible-server ~]# mkdir -p /tmp/roles/nginx/{files,handlers,tasks,templates,vars} 
[root@ansible-server ~]# touch /tmp/roles/site.yaml
[root@ansible-server ~]# touch /tmp/roles/nginx/{handlers,tasks,vars}/main.yaml
[root@ansible-server ~]# echo 1234 > roles/nginx/files/index.html
[root@ansible-server ~]# yum install -y nginx && cp /etc/nginx/nginx.conf roles/nginx/templates/nginx.conf.j2

[root@ansible-server ~]# tree /tmp/roles/
/tmp/roles/
├── nginx
│   ├── files
│   │   └── index.html
│   ├── handlers
│   │   └── main.yaml
│   ├── tasks
│   │   └── main.yaml
│   ├── templates
│   │   └── nginx.conf.j2
│   └── vars
│       └── main.yaml
└── site.yaml

编写任务

[root@ansible-server ~]# vim /tmp/roles/nginx/tasks/main.yaml
---
- name: install nginx package
  yum: name={{ packages }} state=latest
  vars:
    packages:
      - epel-release
      - nginx
- name: copy index.html
  copy: src=index.html dest=/usr/share/nginx/html/index.html
- name: copy nginx.conf template
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart nginx
- name: make sure nginx service is running
  service: name=nginx state=started enabled=yes

准备配置文件

[root@ansible-server ~]# vim /tmp/roles/nginx/templates/nginx.conf.j2
# 调用内部已知变量
worker_processes {{ ansible_processor_cores }};
# 自定义变量
events {
    worker_connections {{ ansible_connections }};
}
# ...

自定义变量需要在vars/main.yaml文件中声明

编写变量

[root@ansible-server ~]# vim /tmp/roles/nginx/vars/main.yaml 
ansible_connections: 1024

编写处理程序

[root@ansible-server ~]# vim /tmp/roles/nginx/handlers/main.yaml
---
- name: restart nginx
  service: name=nginx state=restarted

编写剧本

[root@ansible-server ~]# vim /tmp/roles/site.yaml
- hosts: web
  roles:
  - nginx

检查剧本语法

[root@ansible-server ~]# ansible-playbook /tmp/roles/site.yaml --syntax-check

执行剧本

[root@ansible-server ~]# ansible-playbook /tmp/roles/site.yaml

访问页面

网址:http://172.22.69.97/

posted on 2020-03-28 19:05  D小调的微笑  阅读(172)  评论(0编辑  收藏  举报