ansible批量部署nginx脚本
时间: 2023-11-19 16:47:26 浏览: 93
以下是一个简单的ansible批量部署nginx的脚本示例:
1. 创建一个新的ansible playbook文件,例如nginx.yml。
2. 在playbook文件中定义主机组和变量,例如:
```
- hosts: webservers
vars:
nginx_version: "1.18.0"
nginx_conf_file: "/etc/nginx/nginx.conf"
nginx_sites_dir: "/etc/nginx/sites-enabled"
nginx_service_name: "nginx"
```
3. 定义任务和角色,用于安装和配置nginx,例如:
```
tasks:
- name: Install nginx
apt:
name: nginx
state: present
update_cache: yes
cache_valid_time: 3600
vars:
ansible_python_interpreter: /usr/bin/python3
- name: Configure nginx
template:
src: nginx.conf.j2
dest: "{{ nginx_conf_file }}"
mode: 0644
notify:
- restart nginx
- name: Enable default site
file:
src: "{{ nginx_sites_dir }}/default"
dest: "{{ nginx_sites_dir }}/default.conf"
state: link
force: yes
notify:
- restart nginx
handlers:
- name: restart nginx
service:
name: "{{ nginx_service_name }}"
state: restarted
```
4. 创建一个nginx配置模板文件,例如nginx.conf.j2,用于自定义nginx服务器块的配置:
```
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
# access_log /var/log/nginx/access.log;
# error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
include /etc/nginx/conf.d/*.conf;
include {{ nginx_sites_dir }}/*;
}
```
5. 运行ansible playbook来部署nginx:
```
ansible-playbook -i hosts nginx.yml
```
注意事项:
- 确保在运行playbook之前在hosts文件中定义了正确的主机名或IP地址。
- 在运行playbook之前,请确保在远程主机上安装了ansible和python。
- 在运行playbook之前,请确保在远程主机上启用了SSH身份验证。
阅读全文