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

Ansible:通过Jinja模板将一台服务器主机名复制到另一台

解决Ansible跨Windows服务器传递主机名并处理依赖的方案

步骤1:获取serverA的主机名

无需使用ansible.builtin.hostname模块,可通过两种方式直接获取serverA的主机名:

方案A:利用Ansible Facts收集

通过setup模块收集系统内置信息,其中包含主机名字段:

- name: 收集serverA主机名
  hosts: serverA
  tasks:
    - name: 收集系统facts
      ansible.builtin.setup:
    - name: 将serverA主机名存储到控制节点
      ansible.builtin.set_fact:
        serverA_hostname: "{{ ansible_hostname }}"
      delegate_to: localhost

方案B:执行Windows命令获取

如果未开启facts收集,可直接执行Windows原生命令获取:

- name: 获取serverA主机名
  hosts: serverA
  tasks:
    - name: 执行hostname命令
      ansible.windows.win_command: hostname
      register: serverA_hostname_raw
    - name: 格式化主机名变量
      ansible.builtin.set_fact:
        serverA_hostname: "{{ serverA_hostname_raw.stdout }}"
      delegate_to: localhost

步骤2:处理跨服务器依赖并部署模板

将play拆分为两个阶段,Ansible会按顺序执行play,天然保证依赖关系:

# 第一阶段:获取serverA主机名
- name: 收集serverA主机名
  hosts: serverA
  tasks:
    - name: 收集系统facts
      ansible.builtin.setup:
    - name: 保存主机名到控制节点
      ansible.builtin.set_fact:
        serverA_hostname: "{{ ansible_hostname }}"
      delegate_to: localhost

# 第二阶段:渲染模板并部署到serverB
- name: 部署模板到serverB
  hosts: serverB
  tasks:
    - name: 渲染Jinja模板并复制到目标路径
      ansible.windows.win_template:
        src: ./your_template.j2
        dest: C:\target\file_path\result.txt
      vars:
        target_hostname: "{{ hostvars['localhost']['serverA_hostname'] }}"

关键说明

  • 变量传递:通过delegate_to: localhost将serverA的主机名变量存储在控制节点,后续serverB的play可通过hostvars['localhost']['serverA_hostname']调用该变量。
  • 依赖保障:Ansible按play顺序执行,第一阶段完成后才会启动第二阶段,确保获取到serverA主机名后再处理模板部署。
  • Windows兼容性:针对Windows服务器,文件模板操作优先使用ansible.windows.win_template模块,而非通用template模块。

内容的提问来源于stack exchange,提问作者Atul Abhi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:25:27