Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Install and Set Up Apache with Ansible on Ubuntu

Install Apache on Ubuntu repeatably with Ansible: use apt and service modules, render virtual hosts, enable only needed modules, add TLS safely, and verify the final response.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install Ubuntu’s apache2 package with ansible.builtin.apt, manage the apache2 service declaratively, render virtual-host files into /etc/apache2/, and use handlers so Apache restarts only when its configuration changes. The result is repeatable on every host in an inventory group instead of a sequence of one-off shell commands.

This guide builds an HTTP virtual host, explains how to enable modules and sites safely, adds the requirements for HTTPS, and ends with checks that prove the package, service, configuration, and response are all correct.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you need before running the playbook

The target must be an Ubuntu system reachable by Ansible over SSH. The remote account needs privilege escalation because package installation and writes below /etc/apache2/ require root. Install Ansible on your control machine and define an inventory group named webservers.

Example inventory

[webservers]
web01 ansible_host=203.0.113.10
web02 ansible_host=203.0.113.11

[webservers:vars]
ansible_user=ubuntu

Use the SSH username appropriate for your image. If passwordless sudo is not configured, run the playbook with --ask-become-pass. Keep the Ubuntu release and ansible-core versions consistent with the systems you intend to manage; module parameters and package defaults can differ between releases.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Recommended project layout

apache-ansible/
├── inventory.ini
├── site.yml
└── templates/
    ├── site.conf.j2
    └── site-ssl.conf.j2

A role can later move these files into roles/apache/, but a playbook is enough for a single service or a small deployment.

Install Apache and keep the service enabled

Ubuntu’s package is named apache2. The documented manual sequence is an apt metadata refresh followed by installation; the Ansible equivalent combines both operations in one declarative task. state: present means the package must exist without forcing an upgrade on every run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Base playbook

---
- name: Install and configure Apache on Ubuntu
  hosts: webservers
  become: true
  vars:
    apache_package: apache2
    apache_service: apache2
    apache_server_name: example.com
    apache_document_root: /var/www/example.com

  tasks:
    - name: Refresh apt metadata and install Apache
      ansible.builtin.apt:
        name: "{{ apache_package }}"
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Create the document root
      ansible.builtin.file:
        path: "{{ apache_document_root }}"
        state: directory
        owner: root
        group: root
        mode: '0755'

    - name: Install a test index page
      ansible.builtin.copy:
        dest: "{{ apache_document_root }}/index.html"
        content: "<!doctype html>n<html><body><h1>{{ apache_server_name }}</h1></body></html>n"
        owner: root
        group: root
        mode: '0644'

    - name: Ensure Apache is running and enabled
      ansible.builtin.service:
        name: "{{ apache_service }}"
        state: started
        enabled: true

  handlers:
    - name: Restart Apache
      ansible.builtin.service:
        name: "{{ apache_service }}"
        state: restarted

The update_cache option performs the equivalent of apt update. cache_valid_time: 3600 avoids refreshing metadata more than once per hour on a host that has been managed recently. Adjust the interval or remove it when your change process requires a fresh index on every run.

The service task has two independent guarantees: Apache is started now, and it is enabled to start at boot. A service that is merely running can still be absent after a reboot, while an enabled but stopped service does not serve traffic.

Render an Apache virtual host from a template

Ubuntu keeps Apache directives in plain-text files below /etc/apache2/. On current Ubuntu releases, the main configuration file is /etc/apache2/apache2.conf; the old single-file httpd.conf layout is not the normal arrangement. Site-specific definitions belong in /etc/apache2/sites-available/ and are activated through /etc/apache2/sites-enabled/.

HTTP virtual-host template

Create templates/site.conf.j2:

<VirtualHost *:80>
    ServerName {{ apache_server_name }}
    DocumentRoot {{ apache_document_root }}

    <Directory {{ apache_document_root }}>
        Options FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/{{ apache_server_name }}-error.log
    CustomLog ${APACHE_LOG_DIR}/{{ apache_server_name }}-access.log combined
</VirtualHost>

ServerName identifies the domain handled by this virtual host. Set it to the DNS name that clients will request rather than relying on a broad default. DocumentRoot points to the application files, and the <Directory> block explicitly grants Apache access to that path. Change the access policy if the application requires a narrower rule.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add the template task and activate the site

Add these tasks before the service task in site.yml:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
    - name: Render the site virtual host
      ansible.builtin.template:
        src: site.conf.j2
        dest: "/etc/apache2/sites-available/{{ apache_server_name }}.conf"
        owner: root
        group: root
        mode: '0644'
      notify: Restart Apache

    - name: Enable the site
      ansible.builtin.command:
        cmd: "a2ensite {{ apache_server_name }}.conf"
        creates: "/etc/apache2/sites-enabled/{{ apache_server_name }}.conf"
      notify: Restart Apache

The creates guard makes the a2ensite command idempotent: once the enabled-site link exists, Ansible skips the command and does not report a change. If you deliberately change the site filename, remove the old link or manage it explicitly with ansible.builtin.file so an obsolete virtual host is not left enabled.

Ubuntu’s default setup is virtual-host-friendly. If the requested host name does not match any ServerName, Apache may answer with the first/default site instead of the intended application, so test the hostname rather than only the server IP.

Use handlers to avoid unnecessary restarts

A handler runs only when a notifying task reports a change. In this playbook, a modified template or newly enabled site queues Restart Apache; an unchanged second run does not restart the daemon. This prevents needless connection interruptions and keeps configuration changes tied to the service operation that makes them effective.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep one handler name for all Apache configuration changes, including module enablement and certificate deployment. Ansible coalesces multiple notifications during a play, so several changed files still produce one restart at the end of the relevant section.

Validate before restarting when the change is high risk

For production changes, add a configuration test task and restart only if it succeeds:

    - name: Check Apache configuration syntax
      ansible.builtin.command: apache2ctl configtest
      changed_when: false
      notify: Restart Apache

Because handlers normally run after tasks complete, a failed syntax check stops the play before the queued restart is applied. You can also run the command manually on a host when diagnosing a failed deployment.

Enable only the Apache modules the application needs

Apache is modular. Ubuntu provides a2enmod to enable a module and a2dismod to disable one. Do not enable a broad collection by default; each module expands the active configuration and, in some cases, the attack surface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Idempotent module enablement

For a module whose load file is known, use its file in /etc/apache2/mods-enabled/ as the guard:

    - name: Enable the headers module
      ansible.builtin.command:
        cmd: a2enmod headers
        creates: /etc/apache2/mods-enabled/headers.load
      notify: Restart Apache

Use the same pattern for other required modules, substituting the module name and its enablement marker. If a module has more than one generated file, verify the actual files on the target release before choosing the creates path. A reusable role can wrap this logic and expose a list of module names.

When to use ansible.builtin.package instead

Choice Best fit Trade-off
ansible.builtin.apt Ubuntu- or Debian-specific roles that need apt controls such as update_cache and cache_valid_time. Less portable to hosts using another package manager.
ansible.builtin.package A role shared across distributions where the package name and common state are the only package concerns. It abstracts the discovered package manager, so manager-specific options are not available through the generic interface.

For an Ubuntu-only Apache deployment, ansible.builtin.apt makes the metadata-refresh behavior explicit. Use package when cross-distribution reuse outweighs those apt-specific controls.

Add HTTPS with mod_ssl, a certificate, and a private key

HTTPS requires more than enabling a module. Ubuntu identifies mod_ssl as the component that adds encrypted communication. You also need a certificate and its matching private key, a TLS virtual host, and a policy for protecting the key.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Enable SSL

    - name: Enable the SSL module
      ansible.builtin.command:
        cmd: a2enmod ssl
        creates: /etc/apache2/mods-enabled/ssl.load
      notify: Restart Apache

The module is supplied according to the target Ubuntu release’s Apache packaging. Confirm that the enablement marker exists after the task; do not assume a module package name that belongs to a different release.

Deploy certificate material carefully

Store the certificate and key outside ordinary source control, commonly in encrypted Ansible variables or a secrets system. The key should be readable only by root unless your chosen Apache setup requires a more specific group.

    - name: Install the TLS certificate
      ansible.builtin.copy:
        content: "{{ apache_tls_certificate }}"
        dest: "/etc/ssl/{{ apache_server_name }}.crt"
        owner: root
        group: root
        mode: '0644'
      notify: Restart Apache

    - name: Install the TLS private key
      ansible.builtin.copy:
        content: "{{ apache_tls_private_key }}"
        dest: "/etc/ssl/private/{{ apache_server_name }}.key"
        owner: root
        group: root
        mode: '0600'
      no_log: true
      notify: Restart Apache

Use a certificate issued for the hostname clients will request. Ubuntu notes that its auto-generated certificate is suitable for testing only; it is not a production trust solution.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

HTTPS virtual-host template

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName {{ apache_server_name }}
    DocumentRoot {{ apache_document_root }}

    SSLEngine on
    SSLCertificateFile /etc/ssl/{{ apache_server_name }}.crt
    SSLCertificateKeyFile /etc/ssl/private/{{ apache_server_name }}.key

    <Directory {{ apache_document_root }}>
        Options FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/{{ apache_server_name }}-ssl-error.log
    CustomLog ${APACHE_LOG_DIR}/{{ apache_server_name }}-ssl-access.log combined
</VirtualHost>
</IfModule>

Render this file to /etc/apache2/sites-available/{{ apache_server_name }}-ssl.conf, enable it with a2ensite {{ apache_server_name }}-ssl.conf using a creates guard, and notify the same restart handler. Ensure the certificate’s DNS names, file paths, and permissions match the virtual host before testing port 443.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run the playbook safely

Check mode first

Preview the intended changes where the modules and tasks support check mode:

ansible-playbook -i inventory.ini site.yml --check

Check mode can predict template, package, file, and service changes, but command tasks may provide limited prediction. Treat command-based module and site enablement tasks as requiring an ordinary run for final confirmation.

Apply the configuration

ansible-playbook -i inventory.ini site.yml

If sudo prompts for a password:

ansible-playbook -i inventory.ini site.yml --ask-become-pass

A successful run should show the package task as unchanged or changed as appropriate, the service as started and enabled, and the template or enablement task as changed only when its state differs from the host.

Understand the second run

Run the same command again. With stable variables and files, the package, service, template, and guarded commands should report no changes. A restart on every run usually indicates a template that changes nondeterministically, a missing idempotency guard, or a task that writes generated content with unstable formatting.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Verify package, service, configuration, and response

Do not stop at a green Ansible recap. Verify each layer independently.

  1. Package: confirm the host reports apache2 installed and that the apt task did not fail while refreshing metadata.
  2. Service: confirm the apache2 service is running and enabled for boot.
  3. Rendered configuration: inspect /etc/apache2/sites-available/{{ apache_server_name }}.conf and confirm the corresponding link exists under /etc/apache2/sites-enabled/.
  4. Syntax: run apache2ctl configtest and require a successful result before treating the deployment as valid.
  5. HTTP: request the expected hostname and verify that the intended virtual host, not the default site, returns the application response.
  6. HTTPS: for TLS deployments, request the HTTPS URL and check that the certificate, key, and port-443 virtual host are all being used.

When testing by IP address, send the correct host name in the request if you need to exercise name-based virtual-host selection. A successful TCP connection alone does not prove that the desired site answered.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Troubleshoot the most common failures

“Package apache2 cannot be found”

Check that the target is actually Ubuntu, that apt repositories are configured, and that metadata refresh completed successfully. Review the task output rather than changing the package name: Ubuntu’s Apache package is apache2.

Apache is installed but not serving

Inspect the service result and run the configuration test directly. A syntax error, missing include, invalid directive, or unavailable module can prevent startup. Correct the rendered file or module list, rerun the playbook, and test again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The default site answers instead of your domain

Check the ServerName value, the enabled-site link, and the hostname used in the request. Confirm that the file was rendered in sites-available and activated in sites-enabled. If the default site is no longer required, disable it deliberately rather than deleting configuration files informally.

The playbook restarts Apache every time

Look for a template value that changes on every render, such as a timestamp, and verify that the a2enmod and a2ensite commands have creates guards. Keep ownership, group, and mode fixed so Ansible does not detect avoidable drift.

HTTPS fails after the module is enabled

Separate the possible causes: confirm that ssl.load is enabled, that the certificate and key files exist with the expected permissions, that the certificate matches the requested name, and that the SSL virtual host is enabled. Then run the configuration test before attempting another restart. An auto-generated certificate may work for a test connection while still producing a browser trust warning.

Playbook versus a reusable Apache role

A hand-written playbook is transparent and easy to adapt to one Ubuntu application. A role becomes useful when several hosts need the same defaults, multiple virtual hosts, module lists, TLS files, or OS-specific conditionals.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Decision factor Hand-written playbook Reusable role
Idempotency You must add guards, templates, and handlers directly. Can centralize those patterns and test them once.
Ubuntu release support Simple when every host follows one release family. Can isolate release-specific paths and defaults.
Virtual hosts Clear for one or two sites. Scales better with a list of site dictionaries.
TLS and modules Explicit tasks make the security impact visible. Variables can standardize enablement, but poor defaults may enable more than needed.
Testing Fewer files to understand initially. Worthwhile when you need repeated check-mode and integration testing.

Whichever form you choose, preserve the same boundaries: package installation, service state, rendered configuration, explicit module and site enablement, and a single change-triggered handler.

Production readiness checklist

  • Use the exact Ubuntu package name apache2 and keep apt metadata behavior intentional.
  • Set state: present unless a controlled package upgrade is part of the deployment.
  • Keep site files in /etc/apache2/sites-available/ and enable only the ones required.
  • Set a deliberate ServerName for every hosted domain.
  • Render configuration from templates instead of editing managed files by hand.
  • Notify one Apache restart handler from changed configuration, module, site, and certificate tasks.
  • Enable only required modules; HTTPS specifically needs SSL support plus a matching certificate and private key.
  • Protect private keys with root ownership, restrictive permissions, and secret handling outside ordinary plaintext variables.
  • Run check mode where supported, then validate syntax and perform an HTTP or HTTPS request after applying.
  • Re-check package defaults and ansible-core behavior when changing Ubuntu releases.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.