This guide provides a full Ansible playbook to install Nginx with distro-aware package handling and baseline service configuration for Debian 10+, Ubuntu LTS, and RHEL 9+ compatible systems.
- name: Install Nginx
hosts: nginx
become: true
vars:
app_config_dir: /etc/nginx
tasks:
- name: Install package on Debian/Ubuntu
apt:
name:
- nginx
state: present
update_cache: true
when: ansible_os_family == "Debian"
- name: Install package on RHEL family
dnf:
name:
- nginx
state: present
when: ansible_os_family == "RedHat"
- name: Create configuration directory
file:
path: "{{ app_config_dir }}"
state: directory
mode: "0755"
- name: Enable and start service
service:
name: nginx
state: started
enabled: true
failed_when: false
- name: Verify binary is available
command: "nginx --version"
register: app_version
changed_when: false
failed_when: false
- name: Show detected version output
debug:
var: app_version.stdout
- name: Ensure latest security updates are applied
block:
- name: Update package cache
apt:
update_cache: yes
when: ansible_os_family == "Debian"
- name: Update package cache (RHEL)
dnf:
update_cache: yes
when: ansible_os_family == "RedHat"
- name: Install latest nginx package
apt:
name: nginx
state: latest
when: ansible_os_family == "Debian"
- name: Install latest nginx package (RHEL)
dnf:
name: nginx
state: latest
when: ansible_os_family == "RedHat"
## Notes
- Debian baseline: Debian 10 works, but Debian 11/12 is preferred for package freshness.
- Ubuntu hint: Ubuntu 22.04+ is recommended for long-term maintenance.
- RHEL baseline: use RHEL 9+ compatible systems and enabled repositories.
- Validate package names, service units, and repository requirements for your exact distro.
- **Security Note:** The playbook includes steps to ensure the latest security updates are applied, including version 1.28.2+ or 1.29.5+ which fixes CVE-2026-1642 (SSL upstream injection vulnerability).
- Always verify the installed version: `nginx -v`
---
## Custom Ansible Playbooks Needed?
We develop tailored automation solutions for:
- ✨ Multi-server Nginx deployments
- 🔐 Vault integration for secrets
- 📊 Custom monitoring and alerting
- 🔄 Rolling updates and zero-downtime deployments
Let's discuss your requirements: [office@linux-server-admin.com](mailto:office@linux-server-admin.com) | [Contact](/contact)