【问题标题】:How to arrange a website deployment with Ansible such that Apache is not restarted if there is no vhost change?如何使用 Ansible 安排网站部署,以便在没有虚拟主机更改的情况下不重新启动 Apache?
【发布时间】:2024-05-18 01:50:02
【问题描述】:

我目前正在学习 Ansible,为了应用我所学的知识,我正在转换一些旧的 Bash 安装脚本来构建一个 Web 服务器。我的一个用例是安装或升级网站。流程一般是:

  • 将 Apache 虚拟主机定义复制到 /etc/apache2/available-sites
  • /etc/apache2/enabled-sites 中的符号链接虚拟主机定义
  • /var/www/sitename 中的结帐分支或从源文件夹复制
  • 在该项目中运行自定义设置或迁移脚本,例如与 Phing
  • Apache 优雅重启

如果需要虚拟主机,我只对重新启动网络服务器感兴趣,主要是因为我的 SSL 证书上有密码,如果发生这种情况,需要重新输入。由于此 playbook 的大多数运行将是升级而不是安装,因此在不需要的地方禁止重新启动是有意义的。

我已经围绕这个用例进行了一些搜索,但我似乎无法在网上找到很多相关材料。因此,我创建了以下内容,使用文件哈希来检测更改,我想知道是否有更好的方法来做到这一点。这里是:

---

# Copy site contents unconditionally
- file: path=/var/www/html state=directory
- copy: src=../../build-files/default/index.html dest=/var/www/html/index.html

# Copy vhost to a temporary file so we can checksum it remotely
- copy: src=../../build-files/apache/000-default.conf dest=/tmp/000-default.conf

# Get the checksum of the existing vhost
- shell: md5sum /etc/apache2/sites-available/000-default.conf | cut -f 1 -d ' '
  register: old_checksum_default_site

# Get the checksum of the new vhost
- shell: md5sum /tmp/000-default.conf | cut -f 1 -d ' '
  register: new_checksum_default_site

- debug: msg="Old checksum is {{ old_checksum_default_site.stdout }}, new checksum is {{ new_checksum_default_site.stdout }}"

# Copy our default vhost into place if necessary
- copy: src=../../build-files/apache/000-default.conf dest=/etc/apache2/sites-available/000-default.conf
  notify: restart apache
  when: old_checksum_default_site.stdout != new_checksum_default_site.stdout

这对于所有网站来说都是相当多的样板文件,而且它甚至还没有符号链接 - 有没有更短的方法?我不是 Python 程序员,但请告诉我编写自定义模块是否是最佳解决方案。

【问题讨论】:

    标签: apache ansible vhosts


    【解决方案1】:

    不知道 apache/vhost 的内部结构,这应该足够了

    # Copy site contents unconditionally
    - file: path=/var/www/html state=directory
    - copy: src=../../build-files/default/index.html dest=/var/www/html/index.html
    
    # Copy vhost to a temporary file so we can checksum it remotely
    - copy: src=../../build-files/apache/000-default.conf dest=/etc/apache2/sites-available/000-default.conf
      notify:
        - restart apache
    

    如果您的 000-default.conf 的本地副本没有更改,那么当您运行 ansible 步骤时,它将报告为绿色。

    如果发生了变化,则颜色为黄色,您将看到处理程序在最后运行。

    【讨论】:

    • 哦,对了,Ansible 副本是否只有在产生变化时才运行?
    • 这是正确的。它在内部完成所有 md5sum 的工作(或者它使用另一种方式 - 我不确定这是如何完成的)。编辑:您可以将 ansible 视为使您的服务器达到所需状态的东西。如果你没有指定状态变化(通过更新你的配置),那么 ansible 将不采取任何行动