以下是一个完整的指南,介绍如何在 Debian 类系统(如 Debian、Ubuntu 等)中自动化部署 Apache HTTPD 虚拟主机。我们将创建一个名为 example.com 的虚拟主机,并配置自定义网页。同时,我们会确保服务在启动时自动运行,并开放相关的防火墙端口。

在 Debian 类系统中部署 Apache HTTPD 虚拟主机

任务步骤

  1. 安装 Apache HTTPD 软件包 ⇒ ansible.builtin.apt
  2. 创建网站根目录 ⇒ ansible.builtin.file
  3. 创建自定义 index.html 文件 ⇒ ansible.builtin.copy
  4. 配置 Apache 虚拟主机 ⇒ ansible.builtin.template
  5. 启用新站点 ⇒ ansible.builtin.command
  6. 启动 Apache HTTPD 服务并设置开机启动 ⇒ ansible.builtin.service
  7. 开放防火墙端口 ⇒ community.general.ufw

示例代码

以下是一个 Ansible Playbook,用于在 Debian 类系统中部署 Apache HTTPD 虚拟主机。

文件名:httpd_debian_vhost.yml

---
- name: 部署 Web 服务器虚拟主机
  hosts: all
  become: true
  vars:
    app_user: "www-data"  # 网站运行用户
    http_host: "example.com"  # 虚拟主机域名
    http_conf: "example.com.conf"  # 虚拟主机配置文件名
    http_port: "80"  # HTTP 服务端口
    disable_default: true  # 是否禁用默认站点

  tasks:
    - name: 安装 Apache HTTPD
      ansible.builtin.apt:
        name: apache2
        update_cache: true
        state: latest

    - name: 创建网站根目录
      ansible.builtin.file:
        path: "/var/www/{{ http_host }}"
        state: directory
        owner: "{{ app_user }}"
        mode: '0755'

    - name: 创建自定义 index.html
      ansible.builtin.copy:
        dest: "/var/www/{{ http_host }}/index.html"
        content: |
          Custom Web Page

    - name: 配置 Apache 虚拟主机
      ansible.builtin.template:
        src: "templates/apache.conf.j2"
        dest: "/etc/apache2/sites-available/{{ http_conf }}"
      notify: 重新加载 Apache

    - name: 启用新站点
      ansible.builtin.command: "/usr/sbin/a2ensite {{ http_conf }}"
      notify: 重新加载 Apache

    - name: 禁用默认 Apache 站点
      ansible.builtin.command: "/usr/sbin/a2dissite 000-default.conf"
      when: disable_default
      notify: 重新加载 Apache

    - name: 开放防火墙端口
      community.general.ufw:
        rule: allow
        port: "{{ http_port }}"
        proto: tcp

  handlers:
    - name: 重新加载 Apache
      ansible.builtin.service:
        name: apache2
        state: reloaded

模板文件:templates/apache.conf.j2

<VirtualHost *:{{ http_port }}>
    ServerAdmin webmaster@localhost
    ServerName {{ http_host }}
    ServerAlias www.{{ http_host }}
    DocumentRoot "/var/www/{{ http_host }}"
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

执行命令

$ ansible-playbook -i virtualmachines/ubuntu/inventory services/httpd_debian_vhost.yml

执行结果

PLAY [部署 Web 服务器虚拟主机] *******************************************************

TASK [Gathering Facts] ******************************************************
ok: [ubuntu.example.com]

TASK [安装 Apache HTTPD] ****************************************************
changed: [ubuntu.example.com]

TASK [创建网站根目录] *******************************************************
changed: [ubuntu.example.com]

TASK [创建自定义 index.html] *************************************************
changed: [ubuntu.example.com]

TASK [配置 Apache 虚拟主机] ***************************************************
changed: [ubuntu.example.com]

TASK [启用新站点] ************************************************************
changed: [ubuntu.example.com]

TASK [禁用默认 Apache 站点] ***************************************************
changed: [ubuntu.example.com]

TASK [开放防火墙端口] *********************************************************
ok: [ubuntu.example.com]

RUNNING HANDLER [重新加载 Apache] ********************************************
changed: [ubuntu.example.com]

PLAY RECAP *******************************************************************
ubuntu.example.com         : ok=9    changed=7    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

脚本的幂等性测试

再次运行 Playbook 以验证幂等性:

$ ansible-playbook -i virtualmachines/ubuntu/inventory services/httpd_debian_vhost.yml

幂等性测试结果:

PLAY [部署 Web 服务器虚拟主机] *******************************************************

TASK [Gathering Facts] ******************************************************
ok: [ubuntu.example.com]

TASK [安装 Apache HTTPD] ****************************************************
ok: [ubuntu.example.com]

TASK [创建网站根目录] *******************************************************
ok: [ubuntu.example.com]

TASK [创建自定义 index.html] *************************************************
ok: [ubuntu.example.com]

TASK [配置 Apache 虚拟主机] ***************************************************
ok: [ubuntu.example.com]

TASK [启用新站点] ************************************************************
changed: [ubuntu.example.com]

TASK [禁用默认 Apache 站点] ***************************************************
changed: [ubuntu.example.com]

TASK [开放防火墙端口] *********************************************************
ok: [ubuntu.example.com]

RUNNING HANDLER [重新加载 Apache] ********************************************
changed: [ubuntu.example.com]

PLAY RECAP *******************************************************************
ubuntu.example.com         : ok=9    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

执行前的系统状态

$ ssh devops@ubuntu.example.com
Last login: Thu Feb 24 11:21:41 2022 from 192.168.76.111
$ sudo su
root@ubuntu:/home/devops# cat /etc/os-release 
NAME="Ubuntu"
VERSION="20.04.3 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.3 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal
root@ubuntu:/home/devops# apt list apache2
Listing... Done
apache2/focal-updates,focal-security 2.4.41-4ubuntu3.9 amd64
apache2/focal-updates,focal-security 2.4.41-4ubuntu3.9 i386
root@ubuntu:/home/devops# apt list apache2 --installed
Listing... Done
root@ubuntu:/home/devops# dpkg -l | grep apache
root@ubuntu:/home/devops# cat /etc/apache2/sites-available/example.com.conf
cat: /etc/apache2/sites-available/example.com.conf: No such file or directory
root@ubuntu:/home/devops# ls -al /var/www/example.com
ls: cannot access '/var/www/example.com': No such file or directory
root@ubuntu:/home/devops# cat /var/www/example.com/index.html
cat: /var/www/example.com/index.html: No such file or directory
root@ubuntu:/home/devops# systemctl status apache2
Unit apache2.service could not be found.
root@ubuntu:/home/devops# ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To                         Action      From
--                         ------      ----
80/tcp                     ALLOW IN    Anywhere         
22/tcp (OpenSSH)           ALLOW IN    Anywhere         
80/tcp (v6)                ALLOW IN    Anywhere (v6)     
22/tcp (OpenSSH (v6))      ALLOW IN    Anywhere (v6)
root@ubuntu:/home/devops#

执行后的系统状态

$ ssh devops@ubuntu.example.com
Last login: Thu Feb 24 11:37:49 2022 from 192.168.76.111
$ sudo su
root@ubuntu:/home/devops# apt list apache2
Listing... Done
apache2/focal-updates,focal-security,now 2.4.41-4ubuntu3.9 amd64 [installed]
apache2/focal-updates,focal-security 2.4.41-4ubuntu3.9 i386
root@ubuntu:/home/devops# apt list apache2 --installed
Listing... Done
apache2/focal-updates,focal-security,now 2.4.41-4ubuntu3.9 amd64 [installed]
N: There is 1 additional version. Please use the '-a' switch to see it
root@ubuntu:/home/devops# apt list apache2 --installed -a
Listing... Done
apache2/focal-updates,focal-security,now 2.4.41-4ubuntu3.9 amd64 [installed]
apache2/focal 2.4.41-4ubuntu3 amd64
root@ubuntu:/home/devops# dpkg -l | grep apache2
ii  apache2                              2.4.41-4ubuntu3.9                     amd64        Apache HTTP Server
ii  apache2-bin                          2.4.41-4ubuntu3.9                     amd64        Apache HTTP Server (modules and other binary files)
ii  apache2-data                         2.4.41-4ubuntu3.9                     all          Apache HTTP Server (common files)
ii  apache2-utils                        2.4.41-4ubuntu3.9                     amd64        Apache HTTP Server (utility programs for web servers)
root@ubuntu:/home/devops# cat /etc/apache2/sites-available/example.com.conf 
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
root@ubuntu:/home/devops# ls -al /var/www/example.com/
total 12
drwxr-xr-x 2 www-data root 4096 Feb 24 11:37 .
drwxr-xr-x 4 root     root 4096 Feb 24 11:37 ..
-rw-r--r-- 1 root     root   16 Feb 24 11:37 index.html
root@ubuntu:/home/devops# cat /var/www/example.com/index.html 
Custom Web Page
root@ubuntu:/home/devops# systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2022-02-24 11:37:04 UTC; 2min 41s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 4191 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=0/SUCCESS)
   Main PID: 2318 (apache2)
      Tasks: 55 (limit: 1071)
     Memory: 5.7M
     CGroup: /system.slice/apache2.service
             ├─2318 /usr/sbin/apache2 -k start
             ├─4195 /usr/sbin/apache2 -k start
             └─4228 /usr/sbin/apache2 -k start
Feb 24 11:37:04 ubuntu systemd[1]: Starting The Apache HTTP Server...
Feb 24 11:37:04 ubuntu systemd[1]: Started The Apache HTTP Server.
Feb 24 11:37:12 ubuntu systemd[1]: Reloading The Apache HTTP Server.
Feb 24 11:37:13 ubuntu systemd[1]: Reloaded The Apache HTTP Server.
Feb 24 11:37:50 ubuntu systemd[1]: Reloading The Apache HTTP Server.
Feb 24 11:37:50 ubuntu systemd[1]: Reloaded The Apache HTTP Server.
root@ubuntu:/home/devops# ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To                         Action      From
--                         ------      ----
80/tcp                     ALLOW IN    Anywhere         
22/tcp (OpenSSH)           ALLOW IN    Anywhere         
80/tcp (v6)                ALLOW IN    Anywhere (v6)     
22/tcp (OpenSSH (v6))      ALLOW IN    Anywhere (v6)
root@ubuntu:/home/devops# cat /var/log/apache2/access.log 
192.168.76.111 - - [24/Feb/2022:11:41:21 +0000] "GET / HTTP/1.1" 200 299 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15"
192.168.76.111 - - [24/Feb/2022:11:41:23 +0000] "GET / HTTP/1.1" 200 299 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15"
192.168.76.111 - - [24/Feb/2022:11:41:23 +0000] "GET /favicon.ico HTTP/1.1" 404 497 "http://ubuntu.example.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15"
192.168.76.111 - - [24/Feb/2022:11:41:23 +0000] "GET /apple-touch-icon-precomposed.png HTTP/1.1" 404 497 "-" "Safari/16612.2.9.1.30 CFNetwork/1240.0.4 Darwin/20.6.0"
192.168.76.111 - - [24/Feb/2022:11:41:23 +0000] "GET /apple-touch-icon.png HTTP/1.1" 404 496 "-" "Safari/16612.2.9.1.30 CFNetwork/1240.0.4 Darwin/20.6.0"
192.168.76.111 - - [24/Feb/2022:11:41:49 +0000] "GET / HTTP/1.1" 200 299 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15"
192.168.76.111 - - [24/Feb/2022:11:41:49 +0000] "GET /favicon.ico HTTP/1.1" 404 492 "http://192.168.76.32/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15"
192.168.76.111 - - [24/Feb/2022:11:42:14 +0000] "-" 408 0 "-" "-"
192.168.76.111 - - [24/Feb/2022:11:42:17 +0000] "GET / HTTP/1.1" 304 180 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15"
root@ubuntu:/home/devops#

通过以上步骤,您可以在 Debian 类系统中使用 Ansible 自动化部署 Apache HTTPD 虚拟主机,确保服务正常运行并对外提供服务。