Ansible运维实战
1.Ansible自动化安装nginx
(1).环境准备
我们创建两台虚拟机分别为server节点、host1节点
两个节点根据节点规划来修改主机名
我们在server节点下安装ansible、其余节点不进行配置
|----------|----------------|
| 节点 | Ip地址 |
| Server节点 | 192.168.77.171 |
| Host1节点 | 192.168.77.172 |
我们先创建一个nginx角色
bash
[root@server ~]# ansible-galaxy init /etc/ansible/roles/nginx
将在当前目录下创建一个名为 nginx 的新目录,并填充标准的角色结构。角色结构如下:
bash
[root@server ~]# tree /etc/ansible/roles/nginx/
/etc/ansible/roles/nginx/
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml

我们先用wget命令在server节点上拉取nginx-1.9.6.tar.gz压缩包然后解压压缩包进行编译安装
bash
[root@server ~]# wget http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz
[root@server ~]# tar -zxvf nginx-1.9.6.tar.gz
[root@server ~]# cd nginx-1.9.6
[root@server nginx-1.9.6]# ./configure --prefix=/usr/local/nginx #编译安装
[root@server nginx-1.9.6]# make && make install
将nginx-1.9.6.tar.gz复制到/etc/ansible/roles/nginx/files目录下
bash
[root@server ~]# cp nginx-1.9.6.tar.gz /etc/ansible/roles/nginx/files/
(2).文件内容
定义配置文件
bash
[root@server ~]# vi /etc/ansible/roles/nginx/tasks/main.yml
[root@server ~]# cat /etc/ansible/roles/nginx/tasks/main.yml
- name: 创建 Nginx 用户
user:
name: "{{ nginx_user }}"
system: yes
shell: /sbin/nologin
state: present
- name: 安装依赖包
yum:
name: zlib-devel,pcre-devel,gcc
state: present
- name: 复制nginx压缩包
copy:
src: "{{ nginx_package_path }}"
dest: /root/nginx-1.9.6.tar.gz
owner: root
group: root
mode: 0644
- name: 解压压缩包
unarchive:
src: "/root/nginx-1.9.6.tar.gz"
dest: "/root/"
remote_src: yes # 如果文件已经在远程主机上,则设置为 no
- name: 编译安装 Nginx
shell: >
cd /root/nginx-1.9.6 &&
./configure --prefix=/usr/local/nginx &&
make && make install
- name: 编写 Nginx 启动文件
template:
src: "{{ nginx_service_j2_file_path }}"
dest: /etc/systemd/system/nginx.service
owner: root
group: root
mode: '0755'
notify: daemon-reload
- name: 编写 Nginx 配置文件
template:
src: "{{ nginx_conf_j2_file_path }}"
dest: /usr/local/nginx/conf/nginx.conf
owner: root
group: root
mode: '0644'
notify: reload nginx
- name: 检查 Nginx 配置文件语法
command: /usr/local/nginx/sbin/nginx -t
register: nginx_test
changed_when: false
failed_when: "'test failed' in nginx_test.stdout"
- name: 启动 Nginx 服务并设置开机自启
systemd:
name: nginx
state: started
enabled: true
when: nginx_test is succeeded
- name: 删除 Nginx 压缩包
file:
path: /root/nginx-1.9.6.tar.gz
state: absent
定义templates生成配置文件
Nginx配置文件
bash
[root@server ~]# vi /etc/ansible/roles/nginx/templates/nginx.conf.j2
[root@server ~]# cat /etc/ansible/roles/nginx/templates/nginx.conf.j2
user {{ nginx_user }}; # 设置 Nginx 服务使用的系统用户
worker_processes {{ ansible_processor_vcpus }}; # 工作进程数
error_log /usr/local/nginx/logs/error.log warn; # Nginx 的错误日志
pid /usr/local/nginx/logs/nginx.pid; # Nginx 启动时的 PID 文件
events {
worker_connections 1024; # 每个进程允许的最大连接数
}
http { # HTTP 请求配置,一个 http 可以包含多个 server
# 定义 Content-Type
include /usr/local/nginx/conf/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 访问日志
access_log /usr/local/nginx/logs/access.log main;
# 高效文件传输
sendfile on;
keepalive_timeout 65;
server { # HTTP 服务配置
listen {{ nginxport }};
server_name localhost;
location / {
root /usr/local/nginx/html; # 页面存放目录
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
include /usr/local/nginx/conf.d/*.conf;
}
Nginx启动脚本
bash
[root@server ~]# vi /etc/ansible/roles/nginx/templates/nginx.service.j2
[root@server ~]# cat /etc/ansible/roles/nginx/templates/nginx.service.j2
[Unit]
Description=A high performance web server and a reverse proxy server
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -q -g 'daemon on; master_process on;'
ExecStart=/usr/local/nginx/sbin/nginx -g 'daemon on; master_process on;'
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
定义变量
bash
[root@server ~]# vi /etc/ansible/roles/nginx/vars/main.yml
[root@server ~]# cat /etc/ansible/roles/nginx/vars/main.yml
nginx_user: qiu
nginx_package: nginx-1.9.6.tar.gz
nginx_package_path: /etc/ansible/roles/nginx/files/nginx-1.9.6.tar.gz
nginx_service_j2_file_path: /etc/ansible/roles/nginx/templates/nginx.service.j2
nginx_conf_j2_file_path: /etc/ansible/roles/nginx/templates/nginx.conf.j2
nginxport: 80
定义触发
因为上面通知已经定义,所以,还需要定义一个触发
bash
[root@server ~]# vi /etc/ansible/roles/nginx/handlers/main.yml
[root@server ~]# cat /etc/ansible/roles/nginx/handlers/main.yml
- name: daemon-reload
systemd: daemon-reload=yes
- name: reload nginx
systemd: name=nginx state=reloaded
定义剧本文件
bash
[root@server ~]# vi /etc/ansible/roles/nginx/install.yml
[root@server ~]# cat /etc/ansible/roles/nginx/install.yml
---
- hosts: host1
remote_user: root
roles:
- nginx
定义之后的角色结构
bash
[root@server ~]# tree /etc/ansible/roles/nginx/
/etc/ansible/roles/nginx/
├── defaults
│?? └── main.yml
├── files
│?? └── nginx-1.9.6.tar.gz
├── handlers
│?? └── main.yml
├── install.yml
├── meta
│?? └── main.yml
├── README.md
├── tasks
│?? └── main.yml
├── templates
│?? ├── nginx.conf.j2
│?? └── nginx.service.j2
├── tests
│?? ├── inventory
│?? └── test.yml
└── vars
└── main.yml

(3).执行文件
检查yml文件语法是否正确
bash
[root@server ~]# ansible-playbook --syntax-check /etc/ansible/roles/nginx/install.yml
# 检查install.yml会自动去检查其他的yml文件的语法。

执行roles.yml文件
bash
[root@server ~]# ansible-playbook /etc/ansible/roles/nginx/install.yml
PLAY [host1] *****************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************
ok: [192.168.77.172]
TASK [nginx : 创建 Nginx 用户] ***************************************************************************************************************
changed: [192.168.77.172]
TASK [nginx : 安装依赖包] *********************************************************************************************************************
changed: [192.168.77.172]
TASK [复制nginx压缩包] ************************************************************************************************************************
changed: [192.168.77.172]
TASK [nginx : 解压压缩包] *********************************************************************************************************************
changed: [192.168.77.172]
TASK [nginx : 编译安装 Nginx] ****************************************************************************************************************
changed: [192.168.77.172]
TASK [nginx : 编写 Nginx 启动文件] *************************************************************************************************************
changed: [192.168.77.172]
TASK [nginx : 编写 Nginx 配置文件] *************************************************************************************************************
changed: [192.168.77.172]
TASK [nginx : 检查 Nginx 配置文件语法] ***********************************************************************************************************
ok: [192.168.77.172]
TASK [nginx : 启动 Nginx 服务并设置开机自启] ********************************************************************************************************
changed: [192.168.77.172]
TASK [nginx : 删除 Nginx 压缩包] **************************************************************************************************************
changed: [192.168.77.172]
RUNNING HANDLER [nginx : daemon-reload] **************************************************************************************************
ok: [192.168.77.172]
RUNNING HANDLER [reload nginx] ***********************************************************************************************************
changed: [192.168.77.172]
PLAY RECAP *******************************************************************************************************************************
192.168.77.172 : ok=13 changed=10 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

查看服务启动状态
bash
[root@host1 ~]# systemctl status nginx

2.管理配置文件
生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook。
(1).环境准备
创建角色目录结构
bash
[root@server ~]# mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}

(2).文件内容
定义配置文件
new目录
bash
[root@server ~]# vi /etc/ansible/nginx_config/roles/new/tasks/main.yml
[root@server ~]# cat /etc/ansible/nginx_config/roles/new/tasks/main.yml
- name: copy conf file
copy: src="{{ item.src }}" dest="{{ nginx_basedir }}/{{ item.dest }}" backup=yes owner=root group=root mode=0644
with_items:
- { src: '/etc/ansible/nginx_config/roles/new/files/nginx.conf' , dest: 'conf/nginx.conf' }
- { src: '/etc/ansible/nginx_config/roles/new/files/vhosts' , dest: 'conf/vhosts' }
notify: restart nginx

old目录
bash
[root@server ~]# vi /etc/ansible/nginx_config/roles/old/tasks/main.yml
[root@server ~]# cat /etc/ansible/nginx_config/roles/old/tasks/main.yml
- name: copy conf file
copy: src="{{ item.src }}" dest="{{ nginx_basedir }}/{{ item.dest }}" backup=yes owner=root group=root mode=0644
with_items:
- { src: '/etc/ansible/nginx_config/roles/old/files/nginx.conf' , dest: 'conf/nginx.conf' }
- { src: '/etc/ansible/nginx_config/roles/old/files/vhosts' , dest: 'conf/vhosts' }
notify: restart nginx

定义files目录下内容
new目录和old目录都要配置
把nginx.conf和vhosts目录放到files目录下面
bash
[root@server ~]# cd /usr/local/nginx/conf/
[root@server conf]# cp -r nginx.conf vhosts /etc/ansible/nginx_config/roles/new/files/
[root@server conf]# ls /etc/ansible/nginx_config/roles/new/files/
nginx.conf vhosts

定义变量
new目录和old目录都要配置
bash
[root@server ~]# vi /etc/ansible/nginx_config/roles/new/vars/main.yml
[root@server ~]# cat /etc/ansible/nginx_config/roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx

定义触发
bash
[root@server ~]# vi /etc/ansible/nginx_config/roles/new/handlers/main.yml
[root@server ~]# cat /etc/ansible/nginx_config/roles/new/handlers/main.yml
- name: restart nginx
systemd:
name: nginx
state: restarted

定义剧本文件
new目录
bash
[root@server ~]# vi /etc/ansible/nginx_config/update.yml
[root@server ~]# cat /etc/ansible/nginx_config/update.yml
---
- hosts: host1
remote_user: root
roles:
- new

old目录
bash
[root@server ~]# vi /etc/ansible/nginx_config/backup.yml
[root@server ~]# cat /etc/ansible/nginx_config/backup.yml
---
- hosts: host1
remote_user: root
roles:
- old

定义之后的角色结构
bash
[root@server ~]# tree /etc/ansible/nginx_config/
/etc/ansible/nginx_config/
├── backup.yml
├── roles
│ ├── new
│ │ ├── files
│ │ │ ├── nginx.conf
│ │ │ └── vhosts
│ │ ├── handlers
│ │ │ └── main.yml
│ │ ├── tasks
│ │ │ └── main.yml
│ │ └── vars
│ │ └── main.yml
│ └── old
│ ├── files
│ │ ├── nginx.conf
│ │ └── vhosts
│ ├── handlers
│ │ └── main.yml
│ ├── tasks
│ │ └── main.yml
│ └── vars
│ └── main.yml
└── update.yml

其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令,tasks为执行的任务,vars为定义的变量。
(3).执行文件
在执行update.yml前,应备份当前配置文件,当执行之后发现错误,则进行回滚操作。命令如下:
执行update.yml文件之前一定要使用rsync命令备份配置文件
回滚操作就是把旧的配置覆盖,然后重新加载nginx服务, 每次改动nginx配置文件之前先备份到old里,对应目录为/etc/ansible/nginx_config/roles/old/files。
bash
[root@server ~]# rsync -av /etc/ansible/nginx_config/roles/new/files/ /etc/ansible/nginx_config/roles/old/files/
sending incremental file list
./
nginx.conf
sent 2,807 bytes received 39 bytes 5,692.00 bytes/sec
total size is 2,655 speedup is 0.93

修改new/files目录下的nginx.conf配置文件内容为123
bash
[root@server ~]# echo "123" > /etc/ansible/nginx_config/roles/new/files/nginx.conf
[root@server ~]# cat /etc/ansible/nginx_config/roles/new/files/nginx.conf
123

然后执行update.yml文件
bash
[root@server ~]# ansible-playbook /etc/ansible/nginx_config/update.yml
PLAY [host1] ************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************
ok: [192.168.77.172]
TASK [new : copy conf file] *********************************************************************************************************
changed: [192.168.77.172] => (item={u'dest': u'conf/nginx.conf', u'src': u'/etc/ansible/nginx_config/roles/new/files/nginx.conf'})
ok: [192.168.77.172] => (item={u'dest': u'conf/vhosts', u'src': u'/etc/ansible/nginx_config/roles/new/files/vhosts'})
RUNNING HANDLER [new : restart nginx] ***********************************************************************************************
fatal: [192.168.77.172]: FAILED! => {"changed": false, "msg": "Unable to restart service nginx: Job for nginx.service failed because the control process exited with error code. See \"systemctl status nginx.service\" and \"journalctl -xe\" for details.\n"}
NO MORE HOSTS LEFT ******************************************************************************************************************
PLAY RECAP **************************************************************************************************************************
192.168.77.172 : ok=2 changed=1 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

因为配置了错误的nginx配置文件所以nginx服务重启不了报错了,我们这时候想把配置文件还原需要执行backup.yml文件
bash
[root@server ~]# ansible-playbook /etc/ansible/nginx_config/backup.yml
PLAY [host1] ************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************
ok: [192.168.77.172]
TASK [old : copy conf file] *********************************************************************************************************
changed: [192.168.77.172] => (item={u'dest': u'conf/nginx.conf', u'src': u'/etc/ansible/nginx_config/roles/old/files/nginx.conf'})
ok: [192.168.77.172] => (item={u'dest': u'conf/vhosts', u'src': u'/etc/ansible/nginx_config/roles/old/files/vhosts'})
RUNNING HANDLER [old : restart nginx] ***********************************************************************************************
changed: [192.168.77.172]
PLAY RECAP **************************************************************************************************************************
192.168.77.172 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

我们这样就把配置文件还原到执行update.yml文件之前的样子了。
至此Ansible-运维实战部分结束。