2016-08-23 27 views
0

這裏是我的打法:何時填充hostvars數據以及如何訪問?

- name: Tag ec2 instances 
    hosts: localhost 
    tasks: 
    - name: Print Hosts 
     debug: var=hostvars[item]['ec2_id'] 
     with_inventory_hostnames: all 

    - name: Print Hosts 2 
     debug: msg={{hostvars[item]['ec2_id']}} 
     with_inventory_hostnames: all 

    - name: Tag Hosts 
     ec2_tag: 
     resource: "{{ hostvars[item]['ec2_id'] }}" 
     region: ap-southeast-2 
     args: 
      tags: {mytag: 'myvalue'} 
     with_inventory_hostnames: all 

任何人都可以解釋爲什麼第二個任務失敗,出現以下錯誤,第一個是成功的?如果什麼等號的右邊是未定義

... 
ok: [localhost] => (item=172.31.11.37) => { 
    "hostvars[item]['ec2_id']": "i-xxxxxx", 
    "item": "172.31.11.37" 
} 

TASK [Print Hosts 2] *********************************************************** 
fatal: [localhost]: FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'ec2_id'"} 
+0

無法理解!兩個任務使用同一個對象,但第二個任務失敗。 –

+0

感謝user2864740。我明白你的意思。將問題標題更改爲「何時填充Hostvars數據以及如何訪問?」 有關如何解決此問題的任何建議嗎? –

+0

得到它的工作: ' - 名稱:標籤EC2實例 主機:本地主機 任務: - 名稱:打印主機 調試:VAR = HOSTVARS [項目] [ 'ec2_id'] with_inventory_hostnames:所有 寄存器:醜 # - 名稱:新的打印主機 #調試:味精= {{項目[ 「HOSTVARS [項目] [ 'ec2_id']」]}} #with_items:ugly.results - 名稱:標籤主機 ec2_tag: 狀態:目前 資源:「{{item [\」hostvars [item] ['ec2_id'] \「]}}」 region:ap-southeast-2 標籤: ShutDownAfterHours:沒有 with_items:ugly.results' –

回答

2

debug模塊var=hostvars[item]['ec2_id']不會失敗。
雖然msg={{hostvars[item]['ec2_id']}}將失敗,如果大括號中的部分不能模板化。

在你的例子中,這可能會因爲localhost而失敗,因爲我幾乎可以肯定ec2_id沒有爲localhost定義。

爲了避免這種情況,你可以申請when語句的循環,如下所示:

- name: Print Hosts 2 
    debug: msg={{hostvars[item]['ec2_id']}} 
    when: hostvars[item]['ec2_id'] is defined 
    with_inventory_hostnames: all 
+0

非常感謝康斯坦丁! 多麼愚蠢的問題! 不確定localhost是否是列表中的第一個,所以任務在開始時失敗,或者如果ansible首先檢查整個列表,然後運行循環。 –

相關問題