Ansible 运维实战

一、目标:通过role远程部署nginx并配置

1.首先创建目录结构(每个目录名都是固定的,千万不能打错)
[root@ansible ~]# 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
1.1准备目录结构
[root@ansible ~]# mkdir roles/nginx/{files,handles,tasks,templates,vars} -p
[root@ansible ~]# touch roles/site.yaml roles/nginx/{handles,tasks,vars}/main.yaml
[root@ansible ~]# echo 1234 > roles/nginx/files/index.html
[root@ansible ~]# yum install  -y nginx && cp /etc/nginx/nginx.conf roles/nginx/templates/nginx.conf.j2
此处安装nginx是为了得到nginx的配置文件,通过修改此配置文件的配置,并将文件拷贝到服务主机上,实现修改服务主机的配置。
Ansible实战

2.编写任务

template不同于copy模块,复制的文件中可以存在变量
[root@ansible ~]# vim roles/nginx/tasks/main.yaml

---
- name: install nginx packge
  yum: name={{ item }} state=latest
  with_items:
  - 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 running
  service: name=nginx state=started enabled=yes

主任务文件

3.准备配置文件

[root@ansible ~]# vim roles/nginx/templates/nginx.conf.j2
配置文件内容

4.编写变量


[root@ansible roles]# vim nginx/vars/main.yaml 
worker_connections: 10240
变量文件内容

5.编写处理程序

[root@ansible ~]# vim roles/nginx/handlers/main.yaml 


--
 - name: restart nginx
   service: name=nginx state=restarted
处理程序内容

6.编写剧本(相当于c中的main函数)

[root@ansible ~]# vim roles/site.yaml

- hosts: host1
  roles:
  - nginx

剧本内容

7.实施

1.测试语法正确性:
ansible-playbook site.yaml --syntax-check
语法未报错
2.实施剧本
ansible-playbook site.yaml
3.验证host1:
访问主机host1

你可能感兴趣的:(Ansible 运维实战)