06Ansible角色
Ansible角色
roles是在ansible中,playbooks的目录组织结构。
而模块化之后,成为roles的组织结构,易读,代码可重用,层次清晰。
需求:通过role远程部署nginx并配置
准备目录结构
[ ~]# mkdir -p /tmp/roles/nginx/{files,handlers,tasks,templates,vars} [ ~]# touch /tmp/roles/site.yaml [ ~]# touch /tmp/roles/nginx/{handlers,tasks,vars}/main.yaml [ ~]# echo 1234 > roles/nginx/files/index.html [ ~]# yum install -y nginx && cp /etc/nginx/nginx.conf roles/nginx/templates/nginx.conf.j2 [ ~]# tree /tmp/roles/ /tmp/roles/ ├── nginx │?? ├── files │?? │?? └── index.html │?? ├── handlers │?? │?? └── main.yaml │?? ├── tasks │?? │?? └── main.yaml │?? ├── templates │?? │?? └── nginx.conf.j2 │?? └── vars │?? └── main.yaml └── site.yaml
编写任务
[ ~]# 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
准备配置文件
[ ~]# vim /tmp/roles/nginx/templates/nginx.conf.j2 # 调用内部已知变量 worker_processes {{ ansible_processor_cores }}; # 自定义变量 events { worker_connections {{ ansible_connections }}; } # ...
自定义变量需要在vars/main.yaml文件中声明
编写变量
[ ~]# vim /tmp/roles/nginx/vars/main.yaml ansible_connections: 1024
编写处理程序
[ ~]# vim /tmp/roles/nginx/handlers/main.yaml --- - name: restart nginx service: name=nginx state=restarted
编写剧本
[ ~]# vim /tmp/roles/site.yaml - hosts: web roles: - nginx
检查剧本语法
[ ~]# ansible-playbook /tmp/roles/site.yaml --syntax-check
执行剧本
[ ~]# ansible-playbook /tmp/roles/site.yaml
访问页面
相关推荐
nginxs 2020-11-14
Guanjs0 2020-11-13
小木兮子 2020-11-11
yserver 2020-11-11
ssihc0 2020-11-11
windle 2020-11-10
HanksWang 2020-11-10
liuchen0 2020-11-10
Freshairx 2020-11-10
ccschan 2020-11-10
liwf 2020-11-10
Guanjs0 2020-11-09
AderStep 2020-11-09
zrtlin 2020-11-09
mqfcu 2020-11-10
windle 2020-10-29