首页
/ NGINX Ansible 角色配置教程

NGINX Ansible 角色配置教程

2024-08-25 06:46:11作者:胡易黎Nicole

项目目录结构及介绍

NGINX Ansible 角色项目的目录结构如下:

ansible-role-nginx-config/
├── defaults/
│   └── main.yml
├── handlers/
│   └── main.yml
├── meta/
│   └── main.yml
├── tasks/
│   └── main.yml
├── templates/
│   └── nginx.conf.j2
├── tests/
│   ├── inventory
│   └── test.yml
└── vars/
    └── main.yml

目录介绍

  • defaults/: 包含默认变量文件 main.yml,定义了角色的默认配置。
  • handlers/: 包含处理程序文件 main.yml,定义了在任务完成后需要执行的操作。
  • meta/: 包含元数据文件 main.yml,定义了角色的依赖关系和其他元信息。
  • tasks/: 包含任务文件 main.yml,定义了角色需要执行的具体任务。
  • templates/: 包含模板文件 nginx.conf.j2,定义了 NGINX 配置文件的模板。
  • tests/: 包含测试文件 inventorytest.yml,用于测试角色的功能。
  • vars/: 包含变量文件 main.yml,定义了角色的其他变量。

项目的启动文件介绍

项目的启动文件主要是 tasks/main.yml,它定义了角色需要执行的具体任务。以下是 tasks/main.yml 的部分内容:

---
- name: Ensure NGINX is installed
  package:
    name: nginx
    state: present

- name: Ensure NGINX configuration directory exists
  file:
    path: /etc/nginx/conf.d
    state: directory

- name: Copy NGINX configuration file
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: '0644'

- name: Ensure NGINX service is running
  service:
    name: nginx
    state: started
    enabled: yes

启动文件介绍

  • Ensure NGINX is installed: 确保 NGINX 软件包已安装。
  • Ensure NGINX configuration directory exists: 确保 NGINX 配置目录存在。
  • Copy NGINX configuration file: 将模板文件 nginx.conf.j2 复制到 /etc/nginx/nginx.conf
  • Ensure NGINX service is running: 确保 NGINX 服务正在运行并已启用。

项目的配置文件介绍

项目的配置文件主要是 defaults/main.ymltemplates/nginx.conf.j2

defaults/main.yml

defaults/main.yml 文件定义了角色的默认变量,例如:

---
nginx_user: "nginx"
nginx_worker_processes: "auto"
nginx_error_log: "/var/log/nginx/error.log"
nginx_access_log: "/var/log/nginx/access.log"

templates/nginx.conf.j2

templates/nginx.conf.j2 文件是一个 Jinja2 模板,用于生成 NGINX 配置文件。以下是部分内容:

user {{ nginx_user }};
worker_processes {{ nginx_worker_processes }};

error_log {{ nginx_error_log }} {{ nginx_log_level }};
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/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 {{ nginx_access_log }} main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_
登录后查看全文
热门项目推荐