2017-09-21 68 views
0

我目前正在兩臺主機上動態地將它們添加到一個組中,接着是使用with_togethersynchronize任務使用3個並列的2個元素列表來複制兩個指定文件遠程服務器。Ansible - 以with_together方式對主機運行任務

下面是基於這樣的想法的例子:

--- 
- 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個操作。

我需要它,像這樣同步:從remoteSrc1remoteDest1

  • 副本/tmp/remote/source/two/remoteSrc2

    • 副本/tmp/remote/source/one//tmp/remote/dest/one//tmp/remote/dest/two/remoteDest2

    這將意味着這是一個1: 1比率;主要以與with_together相同的方式對主機進行操作。

    主機是動態獲取的,所以我不能只爲每個主機制作不同的播放。

    由於synchronize實質上是rsync的簡化版本,那麼如果有直接使用rsync的簡單解決方案,那麼將非常感謝。

  • 回答

    0

    沒有此機功能,所以這是我如何解決它:

    由於原始任務,添加以下兩行:

    - "{{ 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語句中使用它們來僅在當前主機(​​)墊使當前在列表中編入索引的主機變爲可用狀態。

    結果是該播放只對每個主機以與其他具有相同索引的列表項以串行方式運行一次。

    相關問題