【问题标题】:Copying local directories to remote hosts with the same directory name将本地目录复制到具有相同目录名称的远程主机
【发布时间】:2021-07-24 09:01:13
【问题描述】:

我有三个本地目录,结构如下:

$ tree .
|_ inventory
|_ deploy.yml
|_ key
    |_ node1
    |   |_ ...  # several files, like id_rsa.pub etc
    |_ node2 
    |   |_ ...  # several files, like id_rsa.pub etc
    |_ node3 
        |_ ...  # several files, like id_rsa.pub etc

我的库存文件在下面:

[remote_cluster]
node1 ansible_host=192.168.100.100
node2 ansible_host=192.168.100.101
node3 ansible_host=192.168.100.102

我要做的是将目录从我的本地机器复制到主机名与目录名称相同的远程机器上,例如,将node1复制到名为node1的远程机器上。我真的不想硬编码这个特性,因为 remote_cluster 节点的数量并不总是三个。未来可能会增加或减少。

我搜索了一些示例,但没有一个符合我的目标。而且我也做了一些尝试,也没有成功:

- hosts: remote_cluster
  name: copy local directories to related nodes
  gather_facts: False
  tasks:
  - name: copy task
    ansible.builtin.copy:
      src:  '{{ item.src }}'
      dest: '{{ item.dest }}'
    with_items:
      - { src: 'key/{{hostvar}}/', dest: '~/.ssh/'}
    tags:
      - copy

在我看来,ansible 可能能够通过某个变量或其他东西来识别哪个远程主机当前正在执行任务。但是我没有弄清楚这个魔术变量的名称是什么。为了清楚起见,我暂时将变量名替换为 hostvar

有人可以帮忙吗?提前致谢!

【问题讨论】:

  • 如果我对问题的理解正确,您应该将hostvar 替换为inventory_hostname

标签: ansible ansible-inventory ansible-facts


【解决方案1】:

您采取了错误的方式。您的游戏已经在您组中的每台机器上循环播放。这里不需要循环(除非您只希望源目录中的文件子集)。

copy 模块能够复制整个树,但如果您有很多文件,则性能会很差。如果是这种情况,请查看更适合的 syncrhonize module

我的感觉是你缺少一些关于你可以在游戏中使用的内部 ansible 变量的知识。作为第一个介绍,我建议您阅读the documentation section on magic variables。我将在下面使用的一个(正如@JBone 评论中已经报道的那样)是inventory_hostname

这是您的固定剧本(根据我的理解和未经测试)。请注意src: 值中的结尾/ 并阅读corresponding description in the documentation

如果 path 是一个目录,它会被递归复制。在这种情况下,如果路径以“/”结尾,则仅将该目录的内部内容复制到目标。否则,如果它不以“/”结尾,则复制包含所有内容的目录本身。

---
- hosts: remote_cluster
  name: copy local directories to related nodes
  gather_facts: false

  tasks:
    - name: copy task
      ansible.builtin.copy:
        src:  'key/{{ inventory_hostname }}/'
        dest: '~/.ssh/'
      tags:
        - copy

【讨论】:

  • 非常感谢!这就是我想要的。我会逐字阅读您在上面发布的文件。
猜你喜欢
  • 1970-01-01
  • 2019-10-07
  • 2012-04-20
  • 2012-06-25
  • 2018-02-15
  • 2022-12-05
  • 2016-11-08
  • 2010-11-30
  • 2021-06-04
相关资源
最近更新 更多