Рефакторинг: вынес запуск ролей в отдельный файл deploy.yml

- Создан файл roles/deploy.yml с блоком запуска роли nginx
- Обновлен molecule/default/site.yml для импорта deploy.yml
- Улучшена модульность структуры проекта
- Автор: Сергей Антропов
This commit is contained in:
2025-10-22 22:34:07 +03:00
parent 0b981ca61e
commit c99df83bad
23 changed files with 661 additions and 659 deletions

13
roles/deploy.yml Normal file
View File

@@ -0,0 +1,13 @@
---
# Плейбук для развертывания ролей
# Автор: Сергей Антропов
# Сайт: https://devops.org.ru
- name: Test nginx role
hosts: all
become: true
roles:
- nginx
tags:
- nginx
- test

View File

@@ -0,0 +1,60 @@
---
# Переменные по умолчанию для роли nginx
# Автор: Сергей Антропов
# Сайт: https://devops.org.ru
# Основные настройки nginx
nginx_user: "nginx"
nginx_worker_processes: "auto"
nginx_worker_connections: 1024
nginx_keepalive_timeout: 65
# Настройки сервера
nginx_server_name: "{{ ansible_fqdn | default(ansible_hostname) }}"
nginx_listen_port: 80
nginx_root_dir: "/var/www/html"
nginx_index_file: "index.html"
# Настройки логов
nginx_access_log: "/var/log/nginx/access.log"
nginx_error_log: "/var/log/nginx/error.log"
# Настройки безопасности
nginx_server_tokens: "off"
nginx_hide_version: true
# Настройки производительности
nginx_sendfile: "on"
nginx_tcp_nopush: "on"
nginx_tcp_nodelay: "on"
# Настройки gzip
nginx_gzip: true
nginx_gzip_vary: "on"
nginx_gzip_min_length: 1024
nginx_gzip_types:
- "text/plain"
- "text/css"
- "text/xml"
- "text/javascript"
- "application/javascript"
- "application/xml+rss"
- "application/json"
# Настройки для разных ОС
nginx_packages:
- nginx
# Дополнительные пакеты для Ubuntu/Debian
nginx_ubuntu_packages:
- nginx
- nginx-common
# Дополнительные пакеты для RHEL/CentOS
nginx_rhel_packages:
- nginx
- nginx-mod-http-geoip
- nginx-mod-http-image-filter
- nginx-mod-http-xslt-filter
- nginx-mod-mail
- nginx-mod-stream

View File

@@ -0,0 +1,44 @@
---
# Обработчики для роли nginx
# Автор: Сергей Антропов
# Сайт: https://devops.org.ru
- name: Restart nginx
systemd:
name: nginx
state: restarted
listen: restart nginx
tags:
- nginx
- service
- restart
- name: Reload nginx
systemd:
name: nginx
state: reloaded
listen: reload nginx
tags:
- nginx
- service
- reload
- name: Start nginx
systemd:
name: nginx
state: started
listen: start nginx
tags:
- nginx
- service
- start
- name: Stop nginx
systemd:
name: nginx
state: stopped
listen: stop nginx
tags:
- nginx
- service
- stop

26
roles/nginx/meta/main.yml Normal file
View File

@@ -0,0 +1,26 @@
---
# Метаданные роли nginx
# Автор: Сергей Антропов
# Сайт: https://devops.org.ru
galaxy_info:
author: Сергей Антропов
description: Простая роль для установки и настройки nginx
company: DevOps.org.ru
license: MIT
min_ansible_version: "2.9"
platforms:
- name: Ubuntu
versions:
- jammy
- focal
- name: EL
versions:
- all
galaxy_tags:
- web
- nginx
- http
- server
dependencies: []

196
roles/nginx/tasks/main.yml Normal file
View File

@@ -0,0 +1,196 @@
---
# Основные задачи для роли nginx
# Автор: Сергей Антропов
# Сайт: https://devops.org.ru
- name: Установка nginx на Ubuntu/Debian
apt:
name: "{{ nginx_ubuntu_packages }}"
state: present
update_cache: true
when: ansible_os_family == "Debian"
tags:
- nginx
- install
- debian
- name: Установка nginx на RHEL/CentOS
yum:
name: "{{ nginx_rhel_packages }}"
state: present
when: ansible_os_family == "RedHat"
tags:
- nginx
- install
- rhel
- name: Включение и запуск nginx на Ubuntu/Debian
systemd:
name: nginx
enabled: true
state: started
when: ansible_os_family == "Debian"
tags:
- nginx
- service
- debian
- name: Включение и запуск nginx на RHEL/CentOS
systemd:
name: nginx
enabled: true
state: started
when: ansible_os_family == "RedHat"
tags:
- nginx
- service
- rhel
- name: Создание директории для веб-контента
file:
path: "{{ nginx_root_dir }}"
state: directory
owner: "{{ nginx_user }}"
group: "{{ nginx_user }}"
mode: '0755'
tags:
- nginx
- config
- directories
- name: Создание тестовой страницы
copy:
content: |
<!DOCTYPE html>
<html>
<head>
<title>Nginx Test Page</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.container { max-width: 600px; margin: 0 auto; }
h1 { color: #333; }
.info { background: #f4f4f4; padding: 20px; border-radius: 5px; }
</style>
</head>
<body>
<div class="container">
<h1>Nginx работает!</h1>
<div class="info">
<p><strong>Сервер:</strong> {{ ansible_hostname }}</p>
<p><strong>ОС:</strong> {{ ansible_distribution }} \
{{ ansible_distribution_version }}</p>
<p><strong>Время:</strong> {{ ansible_date_time.iso8601 }}</p>
<p><strong>Роль:</strong> nginx (Сергей Антропов)</p>
</div>
</div>
</body>
</html>
dest: "{{ nginx_root_dir }}/{{ nginx_index_file }}"
owner: "{{ nginx_user }}"
group: "{{ nginx_user }}"
mode: '0644'
notify: restart nginx
tags:
- nginx
- config
- content
- name: Создание резервной копии конфигурации nginx
copy:
src: "{{ item }}"
dest: "{{ item }}.backup"
remote_src: true
mode: '0644'
owner: root
group: root
loop:
- /etc/nginx/nginx.conf
- /etc/nginx/sites-available/default
ignore_errors: true
when: ansible_os_family == "Debian"
tags:
- nginx
- config
- backup
- name: Создание резервной копии конфигурации nginx (RHEL)
copy:
src: "{{ item }}"
dest: "{{ item }}.backup"
remote_src: true
mode: '0644'
owner: root
group: root
loop:
- /etc/nginx/nginx.conf
- /etc/nginx/conf.d/default.conf
ignore_errors: true
when: ansible_os_family == "RedHat"
tags:
- nginx
- config
- backup
- name: Настройка основной конфигурации nginx
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
backup: true
notify: restart nginx
tags:
- nginx
- config
- main
- name: Настройка виртуального хоста (Ubuntu/Debian)
template:
src: default.conf.j2
dest: /etc/nginx/sites-available/default
owner: root
group: root
mode: '0644'
backup: true
when: ansible_os_family == "Debian"
notify: restart nginx
tags:
- nginx
- config
- vhost
- debian
- name: Настройка виртуального хоста (RHEL/CentOS)
template:
src: default.conf.j2
dest: /etc/nginx/conf.d/default.conf
owner: root
group: root
mode: '0644'
backup: true
when: ansible_os_family == "RedHat"
notify: restart nginx
tags:
- nginx
- config
- vhost
- rhel
- name: Проверка конфигурации nginx
command: nginx -t
register: nginx_config_test
changed_when: false
tags:
- nginx
- config
- test
- name: Показать результат проверки конфигурации
debug:
msg: "{{ nginx_config_test.stdout_lines }}"
when: nginx_config_test.stdout_lines is defined
tags:
- nginx
- config
- test

View File

@@ -0,0 +1,67 @@
# Конфигурация виртуального хоста nginx
# Автор: Сергей Антропов
# Сайт: https://devops.org.ru
# Сгенерировано: {{ ansible_date_time.iso8601 }}
server {
listen {{ nginx_listen_port }};
server_name {{ nginx_server_name }};
# Настройки безопасности
{% if nginx_hide_version %}
server_tokens off;
{% endif %}
# Корневая директория
root {{ nginx_root_dir }};
index {{ nginx_index_file }};
# Настройки логов для этого виртуального хоста
access_log {{ nginx_access_log }};
error_log {{ nginx_error_log }};
# Основная локация
location / {
try_files $uri $uri/ =404;
}
# Настройки для статических файлов
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Настройки безопасности
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# Настройки для favicon
location = /favicon.ico {
log_not_found off;
access_log off;
}
# Настройки для robots.txt
location = /robots.txt {
log_not_found off;
access_log off;
}
# Настройки для health check
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# Настройки для статуса nginx
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}

View File

@@ -0,0 +1,58 @@
# Основная конфигурация nginx
# Автор: Сергей Антропов
# Сайт: https://devops.org.ru
# Сгенерировано: {{ ansible_date_time.iso8601 }}
user {{ nginx_user }};
worker_processes {{ nginx_worker_processes }};
error_log {{ nginx_error_log }};
pid /run/nginx.pid;
events {
worker_connections {{ nginx_worker_connections }};
}
http {
# Основные настройки
sendfile {{ nginx_sendfile }};
tcp_nopush {{ nginx_tcp_nopush }};
tcp_nodelay {{ nginx_tcp_nodelay }};
keepalive_timeout {{ nginx_keepalive_timeout }};
types_hash_max_size 2048;
server_tokens {{ nginx_server_tokens }};
# Настройки MIME типов
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;
# Настройки gzip
{% if nginx_gzip %}
gzip {{ nginx_gzip_vary }};
gzip_min_length {{ nginx_gzip_min_length }};
gzip_types
{% for gzip_type in nginx_gzip_types %}
{{ gzip_type }}{% if not loop.last %} {% endif %}
{% endfor %};
{% endif %}
# Настройки безопасности
{% if nginx_hide_version %}
server_tokens off;
{% endif %}
# Включение конфигураций виртуальных хостов
{% if ansible_os_family == "Debian" %}
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
{% elif ansible_os_family == "RedHat" %}
include /etc/nginx/conf.d/*.conf;
{% endif %}
}