一、YAML-非标记语言
YAML( yet another markup language)是一种直观的能够被电脑识别的数据序列化格式,是一个容易阅读,容易和脚本语言交互,用来表达资料序列的编程语言。它参考了其他多种语言,包括XML,C语言、Python,Perl 以及电子邮件格式RFC2822,是类似于标准通用标记语言的子集XML的数据描述语言,但语法比XML简单很多。
YAML的主要特点包括:
- 简洁性:YAML使用简洁的语法来表示数据,减少了冗余和噪音。
- 可读性:YAML的语法结构清晰,易于理解和阅读,对于人类来说更加友好。
- 可扩展性:YAML支持嵌套结构和复杂数据类型,可以表示各种数据结构和关联关系。
- 可序列化:YAML可以将数据序列化为字符串,方便存储和传输,也可以将字符串反序列化为数据对象。
二、Ansible PlayBook 应用
PlayBook是由一个或多个“play”组成的列表,play的主要功能是为Ansible中的task定义好的角色,指定剧本对应的服务器组。
从根本上说, task是一个任务, task调用Ansible各种模块module,将多个play组织在一个PlayBook剧本中,然后组成一个非常完整的流程控制集合。
基于Ansible PlayBook还可以收集命令.创建任务集,这样能够大大降低管理工作的复杂程度,PlayBook 采用YAML语法结构,易于阅读,方便配置。
一个简单的Ansible Playbook示例:
- name: Install and configure Nginx
hosts: web_servers
become: true
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Copy Nginx configuration file
copy:
src: /path/to/nginx.conf
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: 0644
- name: Restart Nginx
service:
name: nginx
state: restarted
三、Role-角色扮演
在 Ansible 中,roles是组织和构建剧本的一种方式。角色是任务、变量、模板和文件的集合,可以在多个 playbook 中轻松重用。角色允许您模块化基础结构自动化并提高代码可重用性。
要在 Ansible 中创建角色,您通常会在特定目录结构中组织任务、变量、模板和文件。建议的角色目录结构如下:
通过role远程部署nginx并配置:
roles/
├── nginx
│ ├── files
│ │ └── index.html
│ ├── handlers
│ │ └── main.yaml
│ ├── tasks
│ │ └── main.yaml
│ ├── templates
│ │ └── nginx.conf.j2
│ └── vars
│ └── main.yaml
└── site.yaml
6 directories, 6 files
1. 准备如上目录结构:
[root@localhost ~]# mkdir roles/nginx/{files,handlers,tasks,templates,vars} -p
[root@localhost ~]# touch roles/site.yaml roles/nginx/{handlers,tasks,vars}/main.yaml
[root@localhost ~]# echo 1234 > roles/nginx/files/index.html
[root@localhost ~]#yum install -y nginx && cp /etc/nginx/nginx.conf roles/nginx/templates/nginx.conf.j2
[root@localhost ~]# yum -y install tree
[root@localhost ~]# tree roles/
roles/
├── nginx
│ ├── files
│ │ └── index.html
│ ├── handlers
│ │ └── main.yaml
│ ├── tasks
│ │ └── main.yaml
│ ├── templates
│ │ └── nginx.conf.j2
│ └── vars
│ └── main.yaml
└── site.yaml
6 directories, 6 files
2. 编写任务:
vim roles/nginx/tasks/main.yaml
---
- name: install epel-release packge
yum: name=epel-release state=latest
- name: install nginx packge
yum: name=nginx state=latest
- 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 running
service: name=nginx state=started enabled=yes
3. 准备配置文件:
vim roles/nginx/templates/nginx.conf.j2
worker_processes { { ansible_processor_cores }}; #调用内部已知变量
worker_connections { { worker_connections }}; #自定义变量
4. 编写变量 :
vim roles/nginx/vars/main.yaml
worker_connections: 10240
5. 编写处理程序 :
vim roles/nginx/handlers/main.yaml
---
- name: restart nginx
service: name=nginx state=restarted
6. 编写剧本:
vim roles/site.yaml
- hosts: host4
roles:
- nginx
7. 实施:
cd roles
ansible-playbook site.yaml --syntax-check #语法检查
ansible-playbook site.yaml #实施剧本
8. 验证host4 :
在浏览器访问host4IP即可。