2016-06-14 33 views
0

下面是一個劇本的Ansible 2.1部分:Ansible:註冊內容不適用於其他主機

- hosts: localhost 
    any_errors_fatal: true 
    tasks: 
    - name: Bla Bla 
     file: path=/var/tmp/somedir state=directory 
     #ignore_errors: no 
    - name: Create directory for every host 
     file: path=/var/tmp/somedir/{{ item }} state=directory 
     with_items: "{{ groups['XYZ'] }}" 
    - name: Get File contents of NewFile 
     shell: cat NewFile.txt executable=/bin/bash 
     register: file_contents 
- hosts: XYZ 
    #any_errors_fatal: true 
    vars: 
    num_hosts: "{{ groups['XYZ'] | length }}" 
    serial: num_hosts 
    tasks: 
    - name: Copy files to corresponding directories 
     vars: 
     path: /var/tmp/somedir/{{ item[0] }} 
     synchronize: mode=pull src={{ item[1] }} dest={{ path }} 
     with_nested: 
      - "{{ groups['XYZ'] }}" 
      - with_lines: cat NewFile.txt 

這是行不通的。 現在的問題是我不能夠引用已在本地主機註冊file_contents和Ansible不會從hosts: XYZ

支持到catNewFile有沒有辦法以某種簡單的方式做到這一點?我只需要在本劇本中查看NewFile的內容,然後使用相同的方法將文件從遠程複製到本地。

+0

您是否嘗試過set_fact,如果不是嘗試使用set_fact將file_contents的值賦給某個​​變量,那麼它將在整個劇本中可用。 –

+0

我試圖'set_fact'的值設定「'file_contents'到可變'lines',然後在所使用的相同變量: 'with_nested: - 「{{基團[ 'XYZ']}}」 - with_items:lines' 我得到以下錯誤: 'link_stat \「/ home/XYZ/with_items \」失敗:沒有這樣的文件或目錄' –

+0

使用調試模塊並檢查行的值 –

回答

0

正如在評論中提到的,事實(或所有變量)是以主機爲基礎存儲的。如果您已註冊localhost上運行的任務的值,則可以通過全局hostvars字典從其他主機上下文中運行的任何任務訪問該值。所有主機和他們的事實被保存在那裏:

hostvars['localhost']['file_contents'] 

我不能完全肯定只是註冊變量在HOSTVARS字典可用。如果不是,則必須在第一次播放時使用set_fact作爲事實存儲。

+0

您希望我使用類似這樣的內容, 'tasks: - name:將日誌文件複製到相應的節點目錄 var: path:/ var/tmp/somedir/{{item [0]}} #shell:scp -pr ogw @ {{item [0 ]}} {{item} [1]}} {{path}} executable =/bin/bash synchronize:mode = pull src = {{item [1]}} dest = {{path}} 012_with_nested: - 「{{groups ['XYZ']}}」 - with_items:「{{hostvars ['localhost'] ['file_contents']}}」' 即使上面給出我錯誤''with_items'。沒有值存儲在'with_items'中 –

相關問題