【问题标题】:Ansible - Run Task Against Hosts in a with_together FashionAnsible - 以 with_together 方式对主机运行任务
【发布时间】:2017-09-21 19:51:59
【问题描述】:

我目前正在使用两台主机并将它们动态添加到一个组中,然后使用 with_together 执行 synchronize 任务,以并行使用 2 个元素的 3 个列表在两个远程服务器之间复制指定的文件。

这是一个基于这个想法的例子:

---
- name: Configure Hosts for Copying
  hosts: localhost
  gather_facts: no
  tasks:

    - name: Adding given hosts to new group...
      add_host:
        name: "{{ item }}"
        groups: copy_group
      with_items:
        - ["remoteDest1", "remoteDest2"]


- name: Copy Files between servers
  hosts: copy_group
  gather_facts: no
  tasks:    

    - name: Copying files...
      synchronize:
        src: "{{ item[1] }}"
        dest: "{{ item[2] }}"
      with_together:
        - ["remoteSrc1", "remoteSrc2"]
        - ["/tmp/remote/source/one/", "/tmp/remote/source/two/"]
        - ["/tmp/remote/dest/one/", "/tmp/remote/dest/two/"]
      delegate_to: "{{ item[0] }}"

目前,它对两台服务器都进行了这两项操作,总共进行了 4 次操作。

我需要它像这样同步:

  • remoteDest1 上将/tmp/remote/source/one/remoteSrc1 复制到/tmp/remote/dest/one/
  • /tmp/remote/source/two/remoteSrc2复制到/tmp/remote/dest/two/remoteDest2

这意味着它是 1:1 的比例;基本上以与with_together 对列表相同的方式作用于主机。

hosts是动态获取的,所以不能只为每个hosts做不同的玩法。

由于synchronize本质上是rsync的简化版本,那么如果有一个简单的解决方案直接使用rsync,那将不胜感激。

【问题讨论】:

    标签: ansible rsync


    【解决方案1】:

    这没有本机功能,所以我就是这样解决的:

    给定原始任务,添加以下两行:

      - "{{ groups['copy_group'] }}"
    when: inventory_hostname == item[3]
    

    获取:

    - name: Copying files...
      synchronize:
        src: "{{ item[1] }}"
        dest: "{{ item[2] }}"
      with_together:
        - ["remoteSrc1", "remoteSrc2"]
        - ["/tmp/remote/source/one/", "/tmp/remote/source/two/"]
        - ["/tmp/remote/dest/one/", "/tmp/remote/dest/two/"]
        - "{{ groups['copy_group'] }}"
      delegate_to: "{{ item[0] }}"
      when: inventory_hostname == item[3]
    

    本质上,通过将主机添加为列表,它们可以在when 语句中使用,仅当当前主机(inventory_hostname)与列表中当前被索引的主机匹配时执行任务。

    结果是该播放仅以串行方式对每个主机运行一次,并与具有相同索引的其他列表项一起运行。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2017-02-23
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多