0%

通过ansible更新nginx配置

现状

​ nginx两台,目前nginx配置域名较多,管理nginx人员也较多,容易出现nginx管理混乱,修改没有记录等。因此引入将nginx 配置移入gitlab 代码库中统一修改提交,通过ansible发布两台nginx配置并重载配置。

gitlab

ansible 配置

配置hosts

1
2
3
4
## 指定同步主机名或IP

[nginx-sit]
10.0.0.1

配置Handlers

1
2
3
4
5
6
## 被剧本notify,等到play中的所有task执行完成之后,handlers也只会被执行一次)

- name: reload nginx
shell: nginx -s reload
when:
- auto_reload_safe|bool == true

配置全局参数

1
2
3
## 指定全局用户或者变量

ansible_ssh_user: ansible

公私钥配置

1
2
3
4
5
6
7
8
## 免密码输入,ansible_ssh_pass不适用于python3版本以下,拷贝普通用户ansible的pub以及ansible控制主机root的pub到远程的普通用户authrorized_keys文件中

[root@localhost]# cat /etc/ansible/ansible.cfg | grep private

#private_role_vars = yes
# if set, always use this private key file for authentication, same as
# if passing --private-key to ansible or ansible-playbook
private_key_file = /home/ansible/.ssh/id_rsa

制定task任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
## 确保同步conf,cert文件目录存在,同步后删除远程template,并最后notify handlers进行重载


---
- name: Ensure target directories
file:
path: "{{ item }}"
state: directory
recurse: yes
with_items:
- /usr/local/nginx/conf
- /usr/local/nginx/conf/cert

- name: Rotate nginx log
template:
src: "{{ role_path }}/templates/nginx.j2"
dest: /etc/logrotate.d/nginx
mode: 0644
validate: '/sbin/logrotate -d %s'
ignore_errors: yes

- name: Creating temporary directory
tempfile:
state: directory
register: temp_file_path

- name: Synchronize nginx configuration into temporary directory
synchronize:
src: "{{ nginx_conf_path }}/conf"
dest: "{{ temp_file_path.path }}"
recursive: yes
owner: no
group: no

- name: Update nginx configuration
synchronize:
src: "{{ temp_file_path.path }}/conf"
dest: /usr/local/nginx
recursive: yes
delete: yes
checksum: yes
delegate_to: "{{ inventory_hostname }}"
notify:
- reload nginx

- name: Deleting temporary directory (optional)
file:
path: "{{ temp_file_path.path }}"
state: absent


- name: Synchronize SSL certificates
synchronize:
src: "{{ playbook_dir }}/../cert/"
dest: /usr/local/nginx/conf/cert
recursive: yes
owner: no
group: no
notify:
- reload nginx

具体yaml剧本

1
2
3
4
5
6
7
8
9
10
11
12
---
- name: update dev-nginx
hosts: dev-nginx
become: yes
become_method: sudo
become_user: root
roles:
- nginx
tags:
- dev-nginx
vars:
nginx_conf_path: "{{ playbook_dir }}/conf/dev-nginx"

执行脚本

1
2
3
4
5
## -i 指定主机hosts所在目录

#!/usr/bin/bash
git pull
ansible-playbook -i inventory/sccpcloud dev-nginx.yml

注意点

1
2
3
4
5
1.(公钥配置未生效,排查~/.ssh目录为700 ~/.ssh/authroied_keys文件为600)
2.对于使用synchronize这个模块
本地和远程系统必须安装 rsync 包,否则无法使用这个模块;
本地主机是同步任务发起的主机,目标主机是同步时被连接的主机;
也可以使用 delegate_to 将本地主机更改为其他主机。这样可以在两个远程主机之间进行复制,或者在一台远程机器上执行两个目录的同步。