This guide provides a full Ansible playbook to install Apache with distro-aware package handling and baseline service configuration for Debian 10+, Ubuntu LTS, and RHEL 9+ compatible systems.
- name: Install Apache
hosts: apache
become: true
vars:
apache_packages_debian:
- apache2
- apache2-utils
apache_packages_rhel:
- httpd
- httpd-tools
tasks:
- name: Install Apache on Debian/Ubuntu
apt:
name: "{{ apache_packages_debian }}"
state: present
update_cache: true
when: ansible_os_family == "Debian"
- name: Install Apache on RHEL family
dnf:
name: "{{ apache_packages_rhel }}"
state: present
when: ansible_os_family == "RedHat"
- name: Enable and start service on Debian/Ubuntu
systemd:
name: apache2
state: started
enabled: true
when: ansible_os_family == "Debian"
- name: Enable and start service on RHEL
systemd:
name: httpd
state: started
enabled: true
when: ansible_os_family == "RedHat"
- name: Verify Apache is installed
command: "apachectl -v"
register: apache_version
changed_when: false
failed_when: false
- name: Show Apache version
debug:
var: apache_version.stdout_lines
- name: Ensure latest security updates are applied
block:
- name: Update package cache (Debian/Ubuntu)
apt:
update_cache: yes
upgrade: dist
when: ansible_os_family == "Debian"
- name: Update packages (RHEL)
dnf:
update_cache: yes
upgrade: yes
when: ansible_os_family == "RedHat"
- name: Ensure latest Apache version (Debian/Ubuntu)
apt:
name: apache2
state: latest
when: ansible_os_family == "Debian"
- name: Ensure latest Apache version (RHEL)
dnf:
name: httpd
state: latest
when: ansible_os_family == "RedHat"
- name: Configure firewall (UFW)
ufw:
rule: allow
name: Apache Full
when:
- ansible_os_family == "Debian"
- ufw_status.stdout.find("Status: active") != -1
failed_when: false
- name: Configure firewall (firewalld)
firewalld:
service: "{{ item }}"
permanent: true
state: enabled
loop:
- http
- https
when: ansible_os_family == "RedHat"
failed_when: false
Save the playbook as apache_setup.yml and run:
ansible-playbook -i inventory.ini apache_setup.yml
Package Names:
apache2, apache2-utilshttpd, httpd-toolsService Names:
apache2httpdDebian 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
Security Note: The playbook includes steps to ensure the latest security updates are applied (currently version 2.4.66+)
Version Verification: Check installed version with apachectl -v
After running the playbook, verify Apache is working:
# Check service status
sudo systemctl status apache2 # Debian/Ubuntu
sudo systemctl status httpd # RHEL/CentOS
# Check version
apachectl -v
# Test web server
curl -I http://localhost
We develop tailored automation solutions for:
Let’s discuss your requirements: office@linux-server-admin.com | Contact