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

能否使用Ansible Template模块生成文件后复制至其他远程主机或本地主机?

当然可以实现!Ansible的template模块默认是在目标节点生成定制文件,但我们可以通过几种变通的方法,把生成好的文件同步到其他远程主机甚至本地主机。下面给你几个实用的方案,按需选择就行:

方案1:先在目标节点生成,再拉取到控制节点后分发

这个方法适合需要保留每个customhosts节点生成的定制文件副本,再同步到其他目标的场景:

- name: 生成定制文件并同步到其他主机
  hosts: customhosts
  tasks:
    - name: 在customhosts节点生成定制化配置文件
      template:
        src: /mytemplates/foo.j2
        dest: /etc/file.conf
        mode: '0644'

    - name: 将生成的文件拉取到控制节点的临时目录
      fetch:
        src: /etc/file.conf
        dest: ./fetched_files/{{ inventory_hostname }}/etc/file.conf
        flat: no

- name: 将拉取的文件推送到目标主机组(比如other_hosts)
  hosts: other_hosts, localhost
  tasks:
    - name: 复制定制文件到目标位置
      copy:
        src: ./fetched_files/{{ item }}/etc/file.conf
        dest: /etc/file.conf_{{ item }}
        mode: '0644'
      loop: "{{ groups['customhosts'] }}"
      # 如果你只需要同步某一个customhosts节点的文件,去掉loop,直接指定主机名即可

方案2:直接在控制节点生成模板,再批量分发

如果不需要在customhosts节点保留文件,而是想基于customhosts的变量在本地生成文件后再分发,用这个方法更高效:

- name: 在控制节点生成定制文件并分发
  hosts: customhosts
  tasks:
    - name: 基于当前主机变量在控制节点生成定制文件
      template:
        src: /mytemplates/foo.j2
        dest: ./generated_files/{{ inventory_hostname }}_file.conf
        mode: '0644'
      delegate_to: localhost
      run_once: no  # 确保每个customhosts节点都生成对应的定制文件

- name: 分发生成的文件到目标主机(本地/其他远程组)
  hosts: localhost, other_hosts
  tasks:
    - name: 复制定制文件到目标节点
      copy:
        src: ./generated_files/{{ item }}_file.conf
        dest: /etc/file.conf_{{ item }}
        mode: '0644'
      loop: "{{ groups['customhosts'] }}"

方案3:跨主机直接复制(无需经过控制节点)

如果你的网络环境允许other_hosts直接访问customhosts节点,可以跳过控制节点,直接从源节点复制文件:

- name: 从customhosts节点直接复制文件到目标主机
  hosts: other_hosts
  tasks:
    - name: 直接从customhosts节点拉取定制文件
      copy:
        src: /etc/file.conf
        dest: /etc/file.conf
        mode: '0644'
      delegate_to: "{{ item }}"
      loop: "{{ groups['customhosts'] }}"
      # 仅需单个节点的文件?去掉loop,直接写delegate_to: customhost01即可

小提示

  • 如果只需要基于某一个customhosts节点的变量生成文件,记得加上run_once: yes并指定目标主机,避免重复生成。
  • 所有方案中的文件路径可以根据你的实际需求调整,比如把临时生成的文件放到Ansible的tmp目录下。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:52:56