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

Ansible:如何根据主机名动态复制文件/目录至对应远程主机

动态映射IP与目录的Ansible批量复制方案

需求目标

实现本地app/_data/repo-list-N目录与远程主机的动态映射复制:

  • repo-list-0 → 10.0.0.1
  • repo-list-1 → 10.0.0.2
  • repo-list-2 → 10.0.0.3
  • 以此类推,避免AWS新增实例时手动修改Playbook的IP匹配规则

现有环境

主机清单(ansible/hosts)

10.0.0.1
10.0.0.2
10.0.0.3
...

本地源目录结构

app/_data/repo-list-0/repo-list-[1-10].json
app/_data/repo-list-1/repo-list-[2-20].json
app/_data/repo-list-2/repo-list-[3-30].json
...

当前手动配置的Playbook(ansible/playbooks/copy_data.yml)

# ansible/playbooks/copy_data.yml
---
  - name: Copy Data
    hosts: all
    user: ec2-user
    vars:
      app: ...
    tasks:
     - name: copy repo-range to hosts
       copy:
         src: "app/_data/repo-list-0"
         dest: "{{ ansible_env.HOME }}/{{ app }}/_data"
       when: inventory_hostname == "10.0.0.1"
     - name: copy repo-range to hosts
       copy:
         src: "app/_data/repo-list-1"
         dest: "{{ ansible_env.HOME }}/{{ app }}/_data"
       when: inventory_hostname == "10.0.0.2"
     - name: copy repo-range to hosts
       copy:
         src: "app/_data/repo-list-2"
         dest: "{{ ansible_env.HOME }}/{{ app }}/_data"
       when: inventory_hostname == "10.0.0.3"
...

动态实现方案

方法一:利用主机清单索引自动匹配

直接通过主机在all组中的位置索引,对应repo-list的后缀数字,无需修改主机清单:

# ansible/playbooks/copy_data.yml
---
- name: Copy Data Dynamically
  hosts: all
  user: ec2-user
  vars:
    app: ...
  tasks:
    - name: 获取当前主机在清单中的索引
      set_fact:
        repo_index: "{{ groups['all'].index(inventory_hostname) }}"
    - name: 复制对应repo-list目录
      copy:
        src: "app/_data/repo-list-{{ repo_index }}"
        dest: "{{ ansible_env.HOME }}/{{ app }}/_data"

说明:

  • groups['all'].index(inventory_hostname)会自动获取当前主机在清单中的顺序索引(从0开始),刚好对应repo-list的后缀编号
  • 新增实例只需添加到hosts文件,Playbook无需任何修改

方法二:主机清单绑定自定义变量(更灵活)

如果后续主机顺序可能调整,建议给每个主机单独指定对应的repo索引:

修改ansible/hosts:

10.0.0.1 repo_index=0
10.0.0.2 repo_index=1
10.0.0.3 repo_index=2
...

修改Playbook:

# ansible/playbooks/copy_data.yml
---
- name: Copy Data Dynamically
  hosts: all
  user: ec2-user
  vars:
    app: ...
  tasks:
    - name: 复制对应repo-list目录
      copy:
        src: "app/_data/repo-list-{{ repo_index }}"
        dest: "{{ ansible_env.HOME }}/{{ app }}/_data"

说明:

  • 这种方式不受主机在清单中的排序影响,适合主机顺序可能变动的场景
  • 新增实例时只需在hosts中添加IP和对应的repo_index变量即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:45:34