You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ansible自动化管理Nginx虚拟主机配置文件遇阻求助

解决Ansible生成Nginx虚拟主机配置时多域名混杂的问题

问题根源

你直接在J2模板中引用了列表变量domains,Ansible会将整个列表转换为字符串输出,导致所有域名被批量塞进同一个配置文件里。要实现每个域名对应独立配置,需要遍历域名列表,为每个域名单独渲染模板。

修正步骤

1. 调整J2模板(vhost_config.j2)

将模板中所有的{{ domains }}替换为单个域名变量{{ domain }},确保每个配置文件只包含当前域名的信息:

server {
    root /var/www/{{ domain }}/public_html;
    index index.html index.htm index.php;

    server_name {{ domain }} www.{{ domain }};

    access_log  /var/log/nginx/{{ domain }}_access.log;
    error_log   /var/log/nginx/{{ domain }}_error.log;

    location / {
            try_files $uri $uri/ =404;
    }
}

2. 编写正确的Playbook

通过loop遍历域名列表,结合条件判断仅处理未存在的配置文件,完整Playbook示例:

---
- name: 自动化部署Nginx虚拟主机
  hosts: your_target_hosts  # 替换为你的目标主机组/主机名
  vars:
    nginx_vhost_available: /etc/nginx/sites-available
    nginx_vhost_enabled: /etc/nginx/sites-enabled
    nginx_web_root: /var/www
  tasks:
    # 创建每个域名的网站根目录
    - name: 创建网站根目录及public_html子目录
      ansible.builtin.file:
        path: "{{ nginx_web_root }}/{{ domain }}/public_html"
        state: directory
        mode: '0755'
        owner: www-data
        group: www-data
      loop: "{{ domains }}"
      loop_control:
        loop_var: domain

    # 仅为不存在的域名生成配置文件
    - name: 部署Nginx虚拟主机配置文件
      ansible.builtin.template:
        src: vhost_config.j2
        dest: "{{ nginx_vhost_available }}/{{ domain }}.conf"
        mode: '0644'
        owner: root
        group: root
      loop: "{{ domains }}"
      loop_control:
        loop_var: domain
      when: not (nginx_vhost_available ~ '/' ~ domain ~ '.conf') is file

    # 仅为未启用的域名创建软链接(启用虚拟主机)
    - name: 启用Nginx虚拟主机
      ansible.builtin.file:
        src: "{{ nginx_vhost_available }}/{{ domain }}.conf"
        dest: "{{ nginx_vhost_enabled }}/{{ domain }}.conf"
        state: link
      loop: "{{ domains }}"
      loop_control:
        loop_var: domain
      when: not (nginx_vhost_enabled ~ '/' ~ domain ~ '.conf') is link
      notify: 重启Nginx服务

  # 配置变更后重启Nginx
  handlers:
    - name: 重启Nginx服务
      ansible.builtin.service:
        name: nginx
        state: restarted

关键说明

  • 循环遍历:通过loop遍历host_vars中定义的domains列表,loop_control将循环变量命名为domain,与模板中的变量保持一致。
  • 条件判断:使用when语句检查目标文件/软链接是否存在,仅处理新域名,避免覆盖已有配置。
  • 权限与生效:设置正确的文件权限,并通过handler在配置变更后自动重启Nginx,确保新配置生效。

内容的提问来源于stack exchange,提问作者HOVNetworks LLC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:43:14